Data, ORMs and caching · senior
Cache stampede, locks and hot keys
A cache stampede happens when a popular key expires and thousands of requests miss at once and all hit the database; you prevent it with single-flight loading or a short lock, early or jittered refresh, and serving slightly stale data while one request refreshes.
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
- Stampede (thundering herd): hot key expires -> every concurrent request misses -> the DB gets N identical expensive queries and may fall over.
- Single-flight in one process: share the in-flight promise per key, so 1,000 concurrent misses cause 1 load.
- Across instances: a short Redis lock (SET lock:key token NX PX 5000); the winner loads and fills the cache, the others wait briefly and re-read, or serve stale data. Release the lock only if the token still matches (the Redis docs show a compare-and-delete script).
- Stale-while-revalidate: store a soft expiry inside the value; after it, serve the old value and refresh in the background; the hard TTL is longer.
- Jitter TTLs (e.g. 300 s +- 10%) so keys written together do not expire together; probabilistic early refresh is another option.
- Hot keys (one celebrity's profile, IPL live score) can overload one Redis shard: add an in-process cache in front with a short TTL, or replicate the key.
- Negative caching: cache 'not found' briefly so repeated lookups of missing ids do not hit the DB (cache penetration).
The red pen
Common traps: mistake → fix
Mistake: A longer TTL solves stampedes
Fix: it only makes them rarer; the expiry still triggers a herd.
Mistake: A Redis lock with DEL to release is safe
Fix: if the lock expired and someone else took it, DEL removes their lock; compare the token first.
Easy to hard
Questions interviewers ask, easy to hard
- What is a cache stampede? When have you seen one?
- How do you make sure only one request rebuilds an expired key?
- How do you do that across 20 instances?
- How would you cache the live score for 20 million viewers?
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.