Video in progress
What problems does a "big key" in Redis cause (say, a hash with 2 million elements or a 50 MB string), and how do you fix it?
Redis runs commands on a single thread, so reading or deleting a big key in full can freeze the whole node for seconds. To find them, use --bigkeys and MEMORY USAGE; to fix it, split the key, read in pieces with HSCAN, and use UNLINK instead of DEL.
📖 Answer
On prod the symptom usually looks like this: every few minutes Redis p99 latency jumps to 2 seconds, and SLOWLOG GET shows HGETALL or DEL. Or after a failover the replica can't finish syncing for a long time.
Why a big key is dangerous:
HGETALL,SMEMBERS,LRANGE 0 -1areO(N). Every other client waits until 2 million elements have been read;DELis alsoO(N), and freeing the memory happens on the main thread. The same goes when the TTL expires and the key deletes itself, unless lazyfree is configured;- in Redis Cluster a key can't be split, so one node's memory and network fill up, and slot migration gets stuck on that key;
- network: reading a 50 MB value 100 times a second is 5 GB/s.
Finding them:
redis-cli --bigkeys # the biggest keys of each type, using SCAN
redis-cli --memkeys # by memory size
redis-cli MEMORY USAGE feed:seen:42
Fixing them:
- Split the key. Instead of
followers:42usefollowers:42:{bucket}, withbucket = hash(followerId) % 256. Each piece is about 8 thousand elements, and they spread across different slots. If you need multi-key Lua orMGET, you can keep them in one slot with a hash tag, but then you lose the benefit of spreading them out, so you have to choose. - Change how you read. Instead of fetching everything, read in pieces with
HSCAN/SSCAN, or fetch only the fields you need (HMGET). - Change how you delete. Use
UNLINKinstead ofDEL, so the memory is freed on a background thread. Turn onlazyfree-lazy-expire,lazyfree-lazy-evictionandlazyfree-lazy-user-delin the config. - Big strings shouldn't live in Redis at all: files or large JSON go to object storage, and Redis keeps only a link or a small summary.
Prevention is the cheapest: in code review ask "can this collection grow without limit?", and add a metric for element count. A big key usually grows slowly over years, for example a "posts the user has seen" set that never gets cleaned.
Sign up to mark studied questions and save your progress.