Video in progress
What do you understand by a "big key", how do you find one, and why is it dangerous?
A big key is a single key with a huge value, or a collection with millions of elements. When it is deleted, read or migrated, it keeps Redis's single thread busy for a long time, saturates the network, and overloads one node in a cluster.
📖 Answer
Examples: a 50 MB JSON string, a set with 5 million members, a whole catalog in one hash.
Where the problems show up:
DEL big:set: freeing millions of elements takes several seconds, and during that time Redis is "dead";HGETALL,SMEMBERS,LRANGE 0 -1: a big reply clogs the client and the network;- in a cluster, slot migration gets stuck on that key;
- the replication buffer and the AOF suddenly balloon.
Finding them:
redis-cli --bigkeys # finds the biggest per type using SCAN
redis-cli --memkeys # the biggest by memory size
redis-cli MEMORY USAGE cart:42
On prod it's better to run this on a replica. Another way is to analyze the RDB file offline (with tools like rdb-tools).
The cure:
- use
UNLINKfor deletion, which frees memory in a background thread; thelazyfree-lazy-evictionandlazyfree-lazy-expiresettings serve the same purpose; - split the collection into pieces: buckets like
cart:42:{0..15}instead ofcart:42; - compress the big value, or move it out of Redis into S3/the DB and keep only a reference in Redis;
- when reading, use
HSCAN/SSCANor fetch page by page.
I usually set an internal rule on key size: if a string goes over 100 KB or a collection over 10 thousand elements, it gets a question in review.
Sign up to mark studied questions and save your progress.