CodePark/ questions / What Redis is & how it works
START PRACTICINGPRACTICE
Backend question · Redis & caching › What Redis is & how it works

Your Redis latency spikes every few minutes. What kinds of commands or keys can block the server, and how do you find and fix them?

Slow commands on big keys are the usual cause. Redis runs commands one at a time, so one slow command makes every other client wait.

Common causes are O(N) commands on big collections:

  • KEYS.
  • SMEMBERS on a huge set, or HGETALL on a hash with millions of fields.
  • LRANGE 0 -1 on a huge list.
  • SORT.
  • DEL on a very large key. DEL frees the memory synchronously, so the thread waits until it is done.

How to find them:

  • SLOWLOG GET lists commands that took longer than the threshold.
  • LATENCY DOCTOR reports latency events.
  • redis-cli --bigkeys or --memkeys finds keys that are too big.
  • Long-running Lua scripts also show up in these tools.

Fixes:

  • Replace KEYS with SCAN.
  • Replace full reads with HSCAN or SSCAN, or read a range at a time.
  • Split big keys into smaller ones.
  • Delete large keys with UNLINK. It removes the key at once and frees the memory in a background thread.
  • Commands run on a single thread, so one slow command delays everyone.
  • Big keys and O(N) commands are the usual cause.
  • Find them with SLOWLOG, LATENCY DOCTOR and --bigkeys or --memkeys.
  • Use the SCAN family of commands and split big keys.
  • UNLINK frees memory in the background, while DEL blocks the thread.