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

Base It On A Percentage

Right now, you pick numbers that represent some ‘absolute’ value. If you can relate the capacity of each server to something absolute, that’s great, but what if you just want to decide the whole, rather than each value – for example, have them all share 100% of the load?

You just tweak the array to suit – so for example

$server=array(10,50,20);

would become

$server=array(12,63,25);

Which adds to 100, but keeps about the same ratios – and so if you want one server at 95% capacity, just make sure the rest of the entries add up to 5%.

Speed It Up More

Want it fast? Create a table like this:

$server=array(0,1,1,1,1,1,2,2);
$range=count($server)-1;
$i=$server[ mt_rand(0,$range) ];

Now the array contains the server index, and we pick randomly and evenly – but the number of entries will skew it to a particular server. You’ll notice that Server #0 gets called 1/8 of the time, #1 is 5/8 and #2 is 2/8th of the time, exactly as the first example.

To use this, just add more entries for the more powerful servers, and less for the lesser ones.

And to speed it up more, precalculate and store $server and $range, and you’ll only need the third line called each time, at least until you adjust $server.

Comments are closed.