Delete Memcached keys efficiently in PHP

When you build a Web Application it's required to implement Cache in any moment. Memcached is one of the best caching system to reduce database load.

Recently, while working on an applocation, we faced some difficulties to remove caches on demand.

Problem

Normally on PHP to delete a cache we use a snippet like below to remove caches.

<?php

$mem = new Memcached();
//connect the memcached
$mem->addServer('127.0.0.1', 11211);

//flush all cache keys
$mem->flush();
?>

The function flush does not delete the cached key actually. It just invalidates the key after 0 second.

Normally it'll work for an application which has normal traffic. But when your web application has lots of traffic, every page is loaded by thousands users, there it won't work. Because the keys will be invalidated in 0 seconds, but just after executing the code someone loads the page in some milliseconds and request to cache the page in the thread. This will overwrite the previous flush request.

Solution

To solve this issue we found out a easy fix. The code is given below.

<?php
$mem = new Memcached();
//connect the memcached
$mem->addServer('127.0.0.1', 11211);

//cache keys
$keys = array("key1", "key2", "key3")

//delete the keys
$mem->deleteMulti($keys);

?>

Here, deleteMulti function will delete the keys from server immediately.

The actual benefit for using this function is when you execute this code, it'll send the keys to delete queue. And when some keys are in delete queue, then those keys can't be retrieved, added or replaced. After removing the keys, they can be used like before deleting the cache keys.

comments powered by Disqus