A short HowTo on memcached consistent hashing. Of course also works with memcached protocol compatible software as CouchBase, MySQL...
Papers
Papers to read to learn about what consistent hashing is about:
Consistent Hashing with nginx
upstream somestream {
consistent_hash $request_uri;
server 10.0.0.1:11211;
server 10.0.0.2:11211;
...
}
Consistent Hashing with PHP
Note: the order of setOption() and addServers() is important. When using OPT_LIBKETAMA_COMPATIBLE the hashing is compatible with all other runtimes using libmemcached.
$memcached = new Memcached();
$memcached->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT);
$memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
$memcached->addServers($servers);
Consistent Hashing in Perl
As in PHP the order of setOptions() and addServers() matters. After all both languages use the same library in the background, so behaviour is the same.
$m = new Memcached('mymemcache');
$m->setOptions(array(
...
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
...
));
$m->addServers(...);