Weighted Round-Robin Redirection

  • warning: Invalid argument supplied for foreach() in /home/locker/www/randomfoo.net/htdocs/code/modules/filter.module on line 592.
  • user warning: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OR format = 1' at line 1 query: SELECT * FROM filter_formats WHERE OR format = 1 in /home/locker/www/randomfoo.net/htdocs/code/includes/database.mysql.inc on line 108.
by lhl ( | | | )

Here's a quick and dirty way to do weighted round-robin redirection. I assign the key rather than the entire array for weighted array creation so it's not the most inefficient way to do it ever (a more efficient way is to call rand(1,100) and then have a big switch, but it's a PITA to shuffle, especially as you add more sites).

Anyway, the following example shows 50% of the traffic going to url-3, 37.5% to url-2, and 12.5% to url-1:


<?php
  $s[] = array( 1, 'http://url-1' );
  $s[] = array( 3, 'http://url-2' );
  $s[] = array( 4, 'http://url-3' );

  foreach($s as $k => $v) {
    $i = 0;
    for($i=0; $i < $v[0]; $i++) {
      $w[] = $k;
    }
  }

  $location = $s[$w[array_rand($w)]][1];
  Header("Location: $location");
?>

If you want to test out your ratios:

for($i=0; $i<1000; $i++) {
  $c[ $w[array_rand($w)] ] += 1; 
}