How to delete a range of keys in memcached (using Dalli+RoR)

3.1k views Asked by At

I am running Ruby on Rails and am using the Dalli gem to access memcached.

Question: how do I delete a range of keys (not multiple, but a range) for something like: delete all memcached entries with a key that begins with "USERINFO", in other words, how can I use wildcards to delete a range of keys?

2

There are 2 answers

0
Shyam Habarakada On

Short answer is, no and you don't want to do that.

The dalli gem nor memcached support deleting multiple keys with a single command out of the box and for good reason. Since memcached determines the location of cached values by hashing the key, in a production environment with multiple cache nodes, a delete_matched operation would need to scan across all the nodes looking for keys that potentially match. This defeats a key goal of memcached which is performance.

There exist several implementations that extend dalli and promise to provide an implementation of deleted_matched. These all appear to trade-off programmer convenience over performance so use them with caution. Taking a look at sources of these gems before using them is a good start.


Related questions Is it possible to get/search Memcached keys by a prefix?

2
demental On

You should have a look at Rails.cache.delete_matched : http://apidock.com/rails/ActiveSupport/Cache/Store/delete_matched

Does exactly what you want, theorically :

Rails.cache.delete_matched /^USERINFO/