How To Split Randomly But Unevenly – PHP Code For Load UNBalancing

No More Random

It his article, Tom mentioned md5(), which hashes the numbers. This is a nice fast way of getting a similar effect as mt_rand(), as long as we make sure to scale it within range, so

$x=mt_rand(0,array_sum($server)-1);

becomes

$seed='something or other';
$x=hexdec(substr(md5($seed),0,8))%(array_sum($server));

(I use the substr() to limit the input to 8 hex characters – more than that and hexdec() will convert to float, an extra step not really needed here).

The value is now repeatable for any given $seed value. However, we’ve just offloaded the work – now we need a $seed that is random and evenly distributed, which is what our mt_rand() was doing for us before!

One advantage however, is that if we relate it to a repeatable value (say IP addresses), then the same IP address will get the same server – so this helps with repeatability, at least until we change the number of servers!

Keeping The Server Information Handy

We can use the array to store server details in one place for convenience:

$server=array(
  array('name'=>'alpha','load'=>10),
  array('name'=>'beta','load'=>50),
  array('name'=>'gamma','load'=>20) );

But then the call array_sum($server) won’t work – so for speed I’d recommend parallel arrays:

// info on servers
$serverInfo=array(
  array('name'=>'alpha'),
  array('name'=>'beta'),
  array('name'=>'gamma') );
// our ratio list separated for speed
$server=array(10,50,20);

Comments are closed.