Konrad Reiche About Photos Talks

Executing Redis cluster commands

Using redis-cli with Redis cluster may differ from using it against a single instance. Generally, read and write operations for keys work fine as long as cluster mode is enabled by using the -c option. However, certain commands are specific to a particular Redis node, such as SCAN or FLUSHDB, where the cluster mode option is silently ignored and the command is only executed against the node the CLI has connected to.

Each time I try to find out how to do this, I encounter outdated or incorrect answers. As someone who has experienced this problem many times, I feel that it is a good opportunity to share two use cases and document the method here.

Find all keys with a pattern

You may need to create a list of all keys that match a certain pattern, whether for debugging, migration or clean up purposes. The following command lists all keys from master nodes that match the pattern user:*:

redis-cli -h localhost CLUSTER NODES \
  | grep master \
  | awk '{print $2}' \
  | cut -f1 -d '@' \
  | xargs -I '{}' redis-cli -u redis://{} --scan --pattern 'user:*'
  1. redis-cli -h localhost CLUSTER NODES obtains all information from the cluster configuration, including the node addresses to connect to for running commands
  2. grep master selects only the master nodes
  3. awk '{print $2}' selects the second column containg IP, port and cluster bus port
  4. cut -f1 -d '@' to truncate the cluster bus port
  5. xargs in combination with redis-cli to run the desired command. The -u flag makes it possible to provide server address and port in one string

Clear cluster

Similar to the previous example, you can empty a Redis cluster by running FLUSHDB against all nodes. Here is an example of how to do it:

redis-cli -h localhost CLUSTER NODES \
  | grep master
  | awk '{print $2}' \
  | cut -f1 -d '@' \
  | xargs -I '{}' redis-cli -u redis://{} FLUSHDB

These examples should give you a good idea of how to run commands across the entire Redis cluster. If you are looking to run a different type of command, try experimenting with the various parts of these piped commands to fully understand their semantic. By doing so, you will be able to create your own commands without the need for additional tools, libraries or code.