Video in progress

Strong Middle ⚡ Redis and caching

Redis response time suddenly went up in prod. How do you track down the cause?

First I find out whether the problem is inside Redis or in the network/client: SLOWLOG, LATENCY DOCTOR, INFO (CPU, memory, fork time, connections), --bigkeys/--hotkeys. Common causes are an O(N) command on a big key, a fork, swapping and a single hot key.

📖 Answer

I usually go in this order.

  1. Is Redis itself slow?
redis-cli --latency -i 1          # ping from the server side
redis-cli SLOWLOG GET 20          # commands longer than 10 ms (slowlog-log-slower-than)
redis-cli LATENCY DOCTOR          # if latency-monitor-threshold is enabled

If --latency is low while the p99 in the application is high, the problem is in the network, in the client pool, or in the application's GC.

  1. What's in SLOWLOG? Usually: HGETALL/SMEMBERS/LRANGE 0 -1 on a huge key, KEYS, a long Lua script, a big DEL. The fix is to split the key, use HSCAN/SSCAN, UNLINK.

  2. INFO checks:

  • latest_fork_usec: if the RDB/AOF rewrite fork takes hundreds of ms, it lines up with the latency spikes;
  • mem_fragmentation_ratio well below 1 means it has gone into swap, which is very bad;
  • connected_clients, blocked_clients, rejected_connections;
  • jumps in evicted_keys and expired_keys: mass TTL expiry.
  1. A hot key: redis-cli --hotkeys (needs an LFU policy), or turn on MONITOR for a few seconds and count the most frequent keys. 100 thousand requests per second on a single key will occupy the single thread. The fix: an L1 cache, or copying and splitting the key.

  2. The server: if THP (transparent huge pages) is on, latency goes up after a fork; the Redis log warns about this.

After a change, I check the result with the same metrics, not by guessing.