Skip to the page

Redis and caching · senior

Cache stampede and hot keys

When a hot key expires, every request misses at once and all of them run the expensive query. You need one rebuilder, a stale fallback and spread-out expiry.

The notes

What you must know

  • A hot key expires, thousands of requests miss together and each runs the same query. This is a stampede (or thundering herd).
  • In the moment: serve a static or stale fallback, rate-limit, warm the key by hand, switch off non-essential features.
  • One rebuilder per key: single-flight inside each process plus a short Redis lock (SET lock:deals token NX PX 5000). Everyone else serves the stale value.
  • Stale-while-revalidate: store a soft expiry inside the value, and refresh in the background while old data is still served.
  • Probabilistic early refresh (the XFetch method) and random jitter on TTLs spread the expiry times.
  • Hot keys can be refreshed by a background job and never left to expire. Warm the cache before a known event, such as a sale.
  • Make the rebuild cheap: precompute the data into a table instead of a five-table join.
  • One Redis key lives on one shard, so also add a short in-process cache in each pod or keep copies of the hot key.

The red pen

Common traps: mistake → fix

  • Mistake: Add more database replicas

    Fix: it is not enough; stop the herd.

  • Mistake: A lock alone solves it

    Fix: without a stale fallback, requests pile up while they wait.

  • Mistake: Use the same TTL for all keys

    Fix: they expire together.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is a cache stampede?
  2. How do you stop it?
  3. What is stale-while-revalidate?
  4. Why do you add jitter to TTLs?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview