phprandomload-balancing

Use randomizing for server load balancing?


I am using an array as an attempt for "load balance" several RTMP servers.

$servers = array(
    '1.1.1.1',
    '2.2.2.2',
);
$edge = $servers[array_rand($settings)];

but this code does not help much; I end up with 3k on one servers 2k in the other.

I was thinking of taking advantage of APC and cache the last IP given, to keep track of a better IP distribution among the users.

What I need is like the person gets IP 1.1.1.1 the next gets IP 2.2.2.2 to maintain the servers with a closer range of users instead of 3k on one and 2k in the other.

I could use MySQL, but I'll probably hammer the server with all the request.

What is the best way I can achieve a proper distribution of the IPs?


Solution

  • Here's a simple example of how you could cycle three array keys using php memcached:

    $servers = ['1.1.1.1','2.2.2.2','3.3.3.3'];
    $m = new Memcached();
    $m->addServer('localhost', 11211);
    $key = $m->get('server');
    if ($key === false) $key = 0;
    echo $servers[$key];
    if (++$key > count($servers) - 1) $key = 0;
    $m->set('server', $key);