Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Preventing Hot-Key
Cache Stampedes.

When a celebrity hot key's 60-second Redis TTL expires, 50,000 concurrent requests miss simultaneously and stampede the primary PostgreSQL database.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a celebrity hot key's 60-second Redis TTL expires, 50,000 concurrent requests miss simultaneously and stampede, combine in-process singleflight request coalescing, distributed Redis lease locks, and XFetch probabilistic early expiration to keep DB load at 1 query per refresh.

TL;DR30-second simplified summary
▾

Core Mechanics: A global flash-deal key (deal:global:active) is cached in Redis with a 60s TTL and read at 50,000 req/s across 200 stateless API pods.

Visual & Structural Flow: Depicts L1 Local Cache + Singleflight + Redis Lease + XFetch (200 Pods (50k/s) -> L1 Local (2s) -> Redis + Lease -> Postgres (<=5 max)); Bounding DB Refresh to 1 Query Across 200 Stateless Pods (L1 Pod Cache (2s) -> Pod Singleflight -> Redis Lease + XFetch -> Postgres).

Trade-Offs & Production: Using only Redis without L1 local caching still sends 50,000 req/s to a single Redis shard for one key. Combine three lightweight layers using existing infrastructure: Layer 1 — Short L1 In-Process Cache (1–2s TTL): Absorbs >98% of the 50,000 req/s in pod RAM so Redis isn't saturated on one shard.

Failure Modes & Application: Hot-key coalescing is critical in high-fan-out consumer applications: Flash Sales & Homepage Banners: Protects databases during viral traffic spikes.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Preventing Hot-Key Cache Stampedes Matters.

Why this matters: The mechanism: understand how Why Preventing Hot-Key Cache Stampedes Matters works from first principles.

Think of Why Preventing Hot-Key Cache Stampedes Matters as the intuition layer for Preventing Hot-Key Cache Stampedes: The mechanism: understand how Why Preventing Hot-Key Cache Stampedes Matters works from first principles.

A global flash-deal key (deal:global:active) is cached in Redis with a 60s TTL and read at 50,000 req/s across 200 stateless API pods. Every 60 seconds, the key expires instantaneously—causing thousands of workers to miss Redis in the same 50 ms window and fire identical 180 ms SQL joins simultaneously (violating the <= 5 concurrent DB queries limit).

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Hot-Key Stampedes.

Why this matters: The problem: see what breaks without Real-World Impact of Hot-Key Stampedes under real concurrency or scale.

A single hot-key expiration creates periodic 60-second outages:

  1. 5,000× DB Spike: Thousands of workers across 200 pods miss Redis in the 50 ms window and hammer Postgres with identical 180 ms joins.
  2. Single-Shard Redis Hot-Spotting: 50,000 req/s for one key hits a single Redis shard's single-threaded CPU.
  3. Self-Reinforcing Delay: As DB latency degrades from 180 ms to 5s, even more pods miss and pile onto the same query.
3-Layer Stampede Defense

L1 Local Cache + Singleflight + Redis Lease + XFetch

200 Pods (50k/s)L1 Local (2s)Redis + LeasePostgres (<=5 max)1. 99% served from 2s L1 RAM (0Redis RTT)2. Singleflight collapses podmisses to 13. XFetch / SET NX lease: 1 winnerqueries DB4. Other pods wait 25ms or readstale copy

L1 local cache + per-pod singleflight + Redis distributed lease / XFetch reduces 50k/s misses to 1 DB query.

Engineering Decision Framework
Problem
How to implement Preventing Hot-Key Cache Stampedes without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a celebrity hot key's 60-second Redis TTL expires, 50,000 concurrent requests miss simultaneously and stampede, combine in-process singleflight request coalescing, distributed Redis lease locks, and XFetch probabilistic early expiration to keep DB load at 1 query per refresh.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Preventing Hot-Key Cache Stampedes experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Think of Naive Solution (and Why It Breaks) as the intuition layer for Preventing Hot-Key Cache Stampedes: The problem: see what breaks without Naive Solution under real concurrency or scale.

Using only Redis without L1 local caching still sends 50,000 req/s to a single Redis shard for one key. Using only per-pod singleflight still allows 200 concurrent DB queries (1 per pod) to hit Postgres simultaneously—40× over the <= 5 query limit.

Design Trade-Off

Naive Solution (and Why It Breaks)

Before · Fixed TTL + Direct DB
  • Synchronized cache avalanche
  • 1,000 duplicate DB queries
  • Big-key event-loop freeze
After · Jittered TTL + Singleflight
  • 1 origin fetch per expired key
  • Randomized TTL spreads expiry
  • O(1) HashMap + DLL eviction
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: L1 Micro-Cache + Singleflight + Redis Lease / XFetch.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Combine three lightweight layers using existing infrastructure:

  • Layer 1 — Short L1 In-Process Cache (1–2s TTL): Absorbs >98% of the 50,000 req/s in pod RAM so Redis isn't saturated on one shard.
  • Layer 2 — In-Pod singleflight: Coalesces concurrent worker misses inside each pod into 1 outbound call.
  • Layer 3 — Redis SET NX Lease + XFetch Probabilistic Early Refresh: Store {value, delta, expiry} and recompute early when time() - delta * beta * log(rand()) >= expiry—or acquire a short SET lock:deal 1 NX PX 1000 lease so at most 1 pod queries Postgres while others wait briefly or serve stale.
Hot-Key Caching Hierarchy

Bounding DB Refresh to 1 Query Across 200 Stateless Pods

L1 Pod Cache (2s)Absorbs 50k/s hot keyPod SingleflightN workers -> 1…Redis Lease +XFetch200 pods -> 1 DB…Postgres1 query / 60s (<=5…Coalesce cross-pod

1.L1 Micro-Cache: 2s in-memory TTL shields single Redis shard from 50k RPS.

2.XFetch Algorithm: Probabilistically refreshes hot keys *before* TTL hits 0.

3.Redis SET NX PX: Cross-pod distributed lease ensures <= 1-2 concurrent DB queries.

4.Zero New Infra: Uses existing Redis cluster and in-process Python/Java maps.

L1 + singleflight + XFetch/Redis lease guarantees <= 5 concurrent DB queries without sticky sessions or new infrastructure.

import math, random, time, json

def get_with_xfetch(redis_client, key: str, fetch_fn, soft_ttl=60, hard_ttl=300, beta=1.0):
    raw = redis_client.get(key)
    now = time.time()
    if raw:
        entry = json.loads(raw)
        should_refresh = (now - entry['delta'] * beta * math.log(random.random())) >= entry['soft_exp']
        if should_refresh and redis_client.set(f'lock:{key}', '1', nx=True, px=2000):
            t0 = time.time()
            val = fetch_fn()
            delta = time.time() - t0
            redis_client.set(key, json.dumps({'val': val, 'delta': delta, 'soft_exp': time.time() + soft_ttl}), ex=hard_ttl)
        return entry['val']
    # Cold cache fallback: acquire lease or wait
    for _ in range(10):
        if redis_client.set(f'lock:{key}', '1', nx=True, px=2000):
            t0 = time.time()
            val = fetch_fn()
            redis_client.set(key, json.dumps({'val': val, 'delta': time.time()-t0, 'soft_exp': time.time() + soft_ttl}), ex=hard_ttl)
            return val
        time.sleep(0.05 + random.uniform(0, 0.02))
        raw = redis_client.get(key)
        if raw:
            return json.loads(raw)['val']
    return fetch_fn()
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Hot-Key Stampede Defense Applies in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Hot-key coalescing is critical in high-fan-out consumer applications:

  • Flash Sales & Homepage Banners: Protects databases during viral traffic spikes.
  • Celebrity Profiles & Trending Feeds: L1 + singleflight shields Redis shards from 100k+ RPS on one user ID.
  • Auth Public Key (JWKS) & Config Caches: XFetch refreshes rotating keys seamlessly before expiration.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is in-process `singleflight` alone insufficient to protect Postgres across 200 stateless API pods during a hot-key expiration?

Recommended Learning Flow