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 -1 are O(N). Every other client waits until 2 million elements have been read;
  • DEL is also O(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:

  1. Split the key. Instead of followers:42 use followers:42:{bucket}, with bucket = hash(followerId) % 256. Each piece is about 8 thousand elements, and they spread across different slots. If you need multi-key Lua or MGET, 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.
  2. Change how you read. Instead of fetching everything, read in pieces with HSCAN/SSCAN, or fetch only the fields you need (HMGET).
  3. Change how you delete. Use UNLINK instead of DEL, so the memory is freed on a background thread. Turn on lazyfree-lazy-expire, lazyfree-lazy-eviction and lazyfree-lazy-user-del in the config.
  4. 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.