How can I perform massive key deletion in Redis without impacting performance?

Last updated 08, Apr 2024

Question

How can I perform massive key deletion in Redis without impacting performance?

Answer

You can use either redis-cli or RedisInsight with bulk actions.

Using the command line

Using redis-cli, you can indicate a pattern and make sure you:

  • Use -i option so you don’t block the execution of the shard
  • Use unlink, so you execute tasks in the background
  -i <interval>      When -r is used, waits <interval> seconds per command.                     
                     It is possible to specify sub-second times like -i 0.1.

So an example using the command would be:

redis-cli -p <PORT> --scan --pattern city:* -i 0.01 | xargs redis-cli -p <PORT> unlink

Find a few examples here.

Alternatively, it is possible to use xargs with the -L option (max lines) to reduce the chance of blocking the service for other commands.

man xargs

[...]

-L number   Call utility for every number non-empty lines read.

Using RedisInsight

RedisInsight has a "Bulk Actions" functionality and it has the option to Delete Keys.

  • In the “Find keys” form field it is possible to provide a pattern
  • The Preview Pane returns a list of keys that will be removed
  • Click on the 'Delete' button to perform the delete operation