How to flush Redis cache and delete everything using the CLI

Posted on in Categories , last updated December 25, 2017

I setup Redis cache for my web app. I want a blank database and get rid of all keys. How can I delete everything in Redis cache? How do I flush my Redis cache using the Linux/Unix command line option?

You can flush cache/database and delete all keys using any one of the following command:

  1. FLUSHDB command – Delete all the keys of the currently selected DB.
  2. FLUSHALL command – Delete all the keys of all the existing databases, not just the currently selected one.

How to Delete All Data in Redis
Please note that Redis version 4.0.0 and above is now able to delete keys in the background in a different thread without blocking the server. An ASYNC option was added to FLUSHALL and FLUSHDB in order to let the entire dataset or a single database to be freed asynchronously.

Warning: Once removed data/keys/values can not be recovered. Be careful when typing the following commands.

Syntax to flush Redis cache

The syntax is:

redis-cli FLUSHDB
redis-cli -n DB_NUMBER FLUSHDB
redis-cli -n DB_NUMBER FLUSHDB ASYNC
redis-cli FLUSHALL
redis-cli FLUSHALL ASYNC

Examples

Type the following command to delete all the keys of the DB # 4:
$ redis-cli -n 4 FLUSHDB
Sample outputs:

OK

To remove all the keys of all the existing database, run:
$ redis-cli FLUSHALL
Sample outputs:

OK

Automation of deleting Redis cache using Ansible devops tool

Say you have 10 different Redis server running and you want to remove all the keys of all existing DBs. Create a host file as follows:
$ cat hosts
Sample outputs:

[redis]
ansible_user=vivek
vm1-eu
vm2-us
vm3-bom
vm4-del
vm5-nyc
vm6-eu-2
vm7-linod-fr-1
vm8-do-blr-1
vm9-do-blr-2
vm10-linod-tx-1

Now all you have to do is run the following command (assuming that SSH keys are set between your workstation and all other VMs/bare metal servers)
$ ansible -i hosts redis -m command -a '/usr/bin/redis-cli FLUSHALL'
Sample outputs:

vm1-eu | SUCCESS | rc=0 >>
OK

vm2-us | SUCCESS | rc=0 >>
OK

vm3-bom | SUCCESS | rc=0 >>
OK

vm4-del | SUCCESS | rc=0 >>
OK

vm5-nyc | SUCCESS | rc=0 >>
OK

vm6-eu-2 | SUCCESS | rc=0 >>
OK

vm7-linod-fr-1 | SUCCESS | rc=0 >>
OK

vm8-do-blr-1 | SUCCESS | rc=0 >>
OK

vm9-do-blr-2 | SUCCESS | rc=0 >>
OK

m10-linod-tx-1 | SUCCESS | rc=0 >>
OK

For more info read the official redis docs here and here.

This entry is 2 of 2 in the Redis Server Tutorial series. Keep reading the rest of the series:
  1. How to install Redis server on Ubuntu Linux 16.04
  2. How to flush Redis cache and delete everything using the CLI

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 0 comments/add one below):