Skip to main content
Interactive redis-cache Configurator →Open Architecture Blueprint ↗
P0 INCIDENTL6 BARM01 · 5 MIN READ

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.

PRODUCTION SYMPTOM & ALERT SIGNATURE

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"} > 80
01 · ROOT-CAUSE MECHANICS (WHY IT HAPPENS)

When 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.

02 · LIVE TRIAGE COMMANDS (COPY & RUN)
Detect hot keys in live Redis traffic without blocking the event loop
$ redis-cli --hotkeys --memkeys
Smoking gun: Top 1-3 keys accounting for a disproportionate share of reads (requires LFU eviction policy for --hotkeys).
Monitor Redis evicted keys and memory fragmentation
$ redis-cli INFO stats | grep -E "keyspace_hits|keyspace_misses|evicted_keys"
Smoking gun: Spikes in evicted_keys or sudden burst in keyspace_misses matching DB CPU spikes.
Verify maxmemory-policy is not noeviction on a pure cache tier
$ redis-cli CONFIG GET maxmemory-policy
Smoking gun: allkeys-lfu (or volatile-lfu) for cache clusters; noeviction causes OOM write errors.
03 · PRODUCTION DIFF (BROKEN VS HARDENED)
BROKEN · Broken Cache-Aside (zero jitter + zero singleflight -> 500x DB herd)
def get_featured_catalog(key: str):
    val = redis.get(key)
    if val is not None:
        return json.loads(val)
    # DANGER: 500 concurrent requests all execute this query at once!
    fresh = db.query_heavy_catalog()
    redis.setex(key, 900, json.dumps(fresh))  # Fixed TTL synchronizes expiry
    return fresh
HARDENED · Stampede-Proof Cache (Singleflight + Soft/Hard TTL + Jitter)
def get_featured_catalog(key: str):
    payload = redis.get(key)
    if payload:
        entry = json.loads(payload)
        # Serve slightly stale value while 1 leader refreshes asynchronously
        if entry["soft_exp"] > time.time():
            return entry["data"]
        if redis.set(f"lock:{key}", "1", nx=True, ex=5):
            enqueue_async_refresh(key)
        return entry["data"]

    # Hard miss: coalesce identical in-flight calls per process + lease lock
    return singleflight.do(key, lambda: fetch_and_cache_with_jitter(key, base_ttl=900))
04 · MINUTE-24 BAR-RAISER CHECKPOINT (L6 · M01)TEST YOUR INSTINCT · ZERO SIGNUP

A single hot Redis key expires under 2,000 RPS and takes down PostgreSQL. Which combination prevents the thundering herd without blocking readers?

05 · POST-FIX VERIFICATION CHECKLIST
  • 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.
06 · FREQUENTLY ASKED ENGINEERING QUESTIONS

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.