views:

621

answers:

2

Is there a way to invalidate entries in memcache according to a wildcard key?

So if I have the following memcache keys:

data/1
data/2
data/3

Is there a way I can invalidate those keys with something like data/*? It would be extremely helpful to clear out a bunch of stale data in one swoop.

A: 

memcached does not support namespaced deletes.

The official wiki has a suggestion on how to work around it:

http://code.google.com/p/memcached/wiki/FAQ#Deleting_by_Namespace

Crad
+5  A: 

The best way is to provide a versioning key when creating your memcache key. We do this by providing a single function/method for creating a key on our system.

$var1 = 123;
$var2 = 456;
$cacheKey = makeKey('monkeyInfo', $var1, $var2, ...);

MakeKey uses the information in the cacheKeyVersions array and returns:

5:monkeyInfo:123:456

Notice the '5' at the beginning. That comes from a hard-coded array of keyNames => versions. So if we want to invalidate EVERY 'monkeyInfo' cache value in the system we simply have to change that number to 6 in the array. From then on the same call will be looking for

6:monkeyInfo:123:456

Here is an example of what the key version array might look like. The 'makeKey()' call simply looks into this array to get the version number for any given key.

$cacheKeyVersions = array(
    'monkeyInfo'   => 5,
    'zebraInfo'    => 2
);

You could do all sorts of things to make the implementation match your needs, but that's the basic gist of it.

conceptDawg
Also note that your makeKey function/method could also include a global version that would allow you to flush the entire cache if needed. Or you could use it to flush specific domains of keys, etc. It's up to you.
conceptDawg
Very clever way to accomplish the task. Thanks for the insight.
Kekoa