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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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
- What is a cache stampede?
- How do you stop it?
- What is stale-while-revalidate?
- Why do you add jitter to TTLs?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.