iTranslated by AI
Practices for Preventing Outages Caused by the Redis KEYS Command
The Redis KEYS Command is Dangerous
Redis has a KEYS command that scans all keys to search for them.
During development and operation, it's a "Redis common scenario" to frequently encounter situations where you want to search for keys, but
this KEYS command blocks Redis processing proportionally to the number of keys being scanned.
Isn't it true that many people, when still unfamiliar with Redis, have issued the KEYS command in a production environment, causing issues, because the number of keys in the development environment was small and caused no problems?
Rename the command to prevent accidental KEYS execution
Redis has a rename-command configuration setting.
redis/redis.conf at 6.0 · redis/redis · GitHub
Add the following to redis.conf and restart Redis:
rename-command KEYS KEYS_KAKUGO_OK
This ensures that only those who are prepared (KAKUGO_OK) can use the KEYS command.
127.0.0.1:6379> keys *
(error) ERR unknown command 'keys'
127.0.0.1:6379> keys_kakugo_ok *
1) "hoge"
Appendix
rename-command cannot be configured online
A caveat of this method is that Redis restart is required.
Redis has the CONFIG SET command to modify configuration values online, but
this rename-command setting is not supported for online modification.
How to safely search for keys?
Mainly, there are three methods to consider.
1. Use KEYS on a Replica that is not referenced by applications
If you absolutely need to use KEYS, use it on a dedicated Replica.
By enabling the cluster-replica-no-failover setting,
it is possible to create a Replica that does not automatically fail over even in a Redis Cluster.
Since issuing commands to the wrong instance can cause a failure, use MONITOR and CLIENT LIST commands in conjunction to ensure that no application queries are being sent to the instance where you intend to run KEYS.
2. Search by paging with the SCAN command
If you cannot prepare a dedicated Replica, search by paging with the SCAN command.
3. Analyze persistence files (RDB)
If it's sufficient to search data from the RDB acquisition point in a batch-processing manner,
use tools like sripathikrishnan/redis-rdb-tools: to convert it to CSV or JSON.
This is the method I have used the most in the past.
Discussion