How do you prevent a Redis Cache Stampede (Thundering Herd) on hot keys?
Quick Summary: Prevent cache stampedes by combining randomized TTL jitter (stopping synchronized expirations), single-flight request coalescing or distributed mutex locks so only one worker recomputes on a miss, and stale-while-revalidate serving.
Direct Interview Answer
When a popular homepage or product key expires in Redis while 50,000 users arrive concurrently, all 50,000 requests suffer a cache miss simultaneously and slam the primary SQL database—crashing it cleanly.
Effective mitigation stacks three layers: (1) TTL Jitter so bulk keys spread expiry naturally; (2) Single-Flight / Mutex Lock allowing only one loader thread per key per instance (or short Redis NX lease) to hit the DB while peers wait or read stale values; and (3) Logical background refresh before hard eviction.
Detailed Technical Explanation
Also guard against cache penetration (bots requesting nonexistent IDs repeatedly that never cache): store short-TTL null sentinel markers or check a Bloom Filter before querying SQL.
Practical Walkthrough
Adding ±15% random TTL jitter cleanly avoids mass midnight cache expiry waves.
function ttlWithJitter(baseSeconds, spreadRatio = 0.15) {
const delta = Math.floor(baseSeconds * spreadRatio);
const offset = Math.floor(Math.random() * (delta * 2 + 1)) - delta;
return Math.max(10, baseSeconds + offset);
}
console.log("Randomized TTLs:", ttlWithJitter(3600), ttlWithJitter(3600));
Randomized TTLs: 3412 3891
Real-World Production Use Case
E-commerce flash sales, viral news feeds, and high-traffic SaaS configuration endpoints.
Common Interview Mistakes to Avoid
- Setting identical fixed TTLs across 10,000 warmed cache items at 00:00 UTC.
- Acquiring a Redis mutex lock without a short expiry lease, causing permanent deadlocks if the holder crashes.