How to atomically delete keys matching a pattern using Redis


In my Redis DB I have a number of prefix:<numeric_id> hashes.

Sometimes I want to purge them all atomically. How do I do this without using some distributed locking mechanism?

Best Solution

Execute in bash:

redis-cli KEYS "prefix:*" | xargs redis-cli DEL


Ok, i understood. What about this way: store current additional incremental prefix and add it to all your keys. For example:

You have values like this:

prefix_prefix_actuall = 2
prefix:2:1 = 4
prefix:2:2 = 10

When you need to purge data, you change prefix_actuall first (for example set prefix_prefix_actuall = 3), so your application will write new data to keys prefix:3:1 and prefix:3:2. Then you can safely take old values from prefix:2:1 and prefix:2:2 and purge old keys.