Redis Hot-Key Expiration Thundering Herd & Singleflight Collapse
Prevent database collapse when a hot Redis key expires simultaneously across thousands of workers using singleflight request coalescing, TTL jitter, and stale-while-revalidate.
Every 15 minutes on the dot, PostgreSQL CPU spikes to 100% for 40 seconds and API error rates surge even though Redis overall cache hit rate is 99.1%.
rate(redis_keyspace_misses_total[1m]) > 500 AND pg_stat_activity_count{state="active"} > 80When a hot key (such as a homepage catalog or feature-flag payload cached with a uniform 900s TTL) expires, hundreds of concurrent app workers see a cache miss within the same 50ms window.
Without request coalescing or a distributed refresh lease, all 500 workers slam PostgreSQL with the exact same heavy aggregation query simultaneously, saturating DB connections and multiplying query latency.
Uniform TTLs (without +/- 10-20% random jitter) synchronize cache expirations across entire cohorts of keys, causing periodic 15-minute load spikes.
A single hot Redis key expires under 2,000 RPS and takes down PostgreSQL. Which combination prevents the thundering herd without blocking readers?
- Confirm maxmemory-policy is set to allkeys-lfu on pure cache instances so hot keys are never evicted before cold keys.
- Add +/- 15% random jitter to every TTL and wrap hard-miss loaders in process-local singleflight + short SET NX refresh leases.
- Verify PostgreSQL active queries remain flat when flushing a single hot key in staging.
When should I use singleflight vs a distributed Redis SET NX lock?
Use both for hot keys: in-process singleflight collapses 100 concurrent goroutines/coroutines on each pod to 1 call, and a short SET NX lease (or soft-TTL background refresh) collapses N pods to 1 database query.
Why is allkeys-lfu better than allkeys-lru for Zipfian hot-key workloads?
LFU (Least Frequently Used) tracks access frequency rather than just recency, preventing one-off scan bursts from evicting genuinely hot keys.
What if a single hot key saturates one Redis shard CPU even when cached?
Add a tiny 2-5 second L1 in-process cache in front of Redis (or replicate/shard the read key across N suffixed replicas key#0..key#7) to fan out single-threaded Redis reads.