17

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.

braX
  • 11,506
  • 5
  • 20
  • 33
Kekoa
  • 27,892
  • 14
  • 72
  • 91

2 Answers2

23

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.

Niyojan
  • 544
  • 1
  • 6
  • 23
conceptDawg
  • 732
  • 3
  • 12
  • 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 Sep 16 '09 at 04:27
  • Very clever way to accomplish the task. Thanks for the insight. – Kekoa Dec 30 '09 at 02:06
  • @ConceptDawg do you have or know any libraries (preferably PHP) which would implement this algorithm? – romaninsh Jul 27 '11 at 13:01
  • I don't know of any. We started using memcache when it was still fairly new so I ended up writing our own PHP memcache handling library. I can't release it because it's not mine to release. – conceptDawg Jul 28 '11 at 02:48
  • 2
    Where do you store the version number? – Seun Osewa Aug 07 '13 at 15:30
  • We store the version numbers in a globally accessible array (hey, you can't win 'em all). But you could store them in any way that you can access them. It's really up to you. You just need to be able to reference the values. – conceptDawg Sep 16 '13 at 23:25
  • Very elegant solution! we ended up mixing our database object version into the key. – Sergey Grechin Sep 07 '16 at 11:41
5

memcached does not support namespaced deletes.

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

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
Gavin M. Roy
  • 4,551
  • 4
  • 33
  • 29