Consistent Memcache Hashing and Failover with PHP
Monday, August 11th, 2008I’ve written about Memcache before because it’s one of the best pieces of software written. It’s power lies in it’s simplicity and how easily you can plug it into any application. One of the things I really wanted was to implement consistent hashing and failover.
After checking out the PHP/Memcache documentation, the code to achieve this is fairly simple:
ini_set('memcache.allow_failover', true); // default is usually true ini_set('memcache.hash_strategy', 'consistent');
Somewhere in your configuration/initialization script, make sure these memcache settings are in place. Allow failover tells the memcache client to try another server if it cannot connect to a particular memcache daemon. The hash strategy is pretty self explanatory. Now onto the actual server code:
$failCount = 0; $realInstance = new Memcache; $testInstance = new Memcache; $servers = array("server1", "server2", "server3"); $defautlPort = '1'; foreach($servers as $host) { if($testInstance->connect($host)) { $realInstance->addServer($host); $testInstance->close(); // only close if connection was success } else { $realInstance->addServer($host, defautlPort, true, 1, 1, -1, false); $failCount++; } } $isConnected = true; if($failCount == count($servers)) { // set false if every server is marked as failed $isConnected = false; }
I use two instances of Memcache (might not be most optimal solution) to check the availability of that server and if it is available, add it to the pool with all of the default options. If it is not available, set up the connection to automatically failover but also maintain its position in the server pool. These options are set using this paragraph from the PHP docs:
bool Memcache::addServer ( string $host [, int $port [, bool $persistent [, int $weight [, int $timeout [, int $retry_interval [, bool $status [, callback $failure_callback ]]]]]]] )
retry_interval: Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry.
status: Controls if the server should be flagged as online. Setting this parameter to FALSE and retry_interval to -1 allows a failed server to be kept in the pool so as not to affect the key distribution algoritm. Requests for this server will then failover or fail immediatly depending on the memcache.allow_failover setting.
There’s also error checking to ensure that at least one server is online to be considered connected to a memcache pool.