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

Design a Thundering-Herd Cache Stampede
Shield with Singleflight Coalescing.

Combine L1 in-process caching, Redis L2 with Stale-While-Revalidate, a Consistent-Hash Singleflight Coalescer tier, and Probabilistic Early Refresh.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, local singleflight alone still sends 200 queries across 200 pods; consistent-hash routing to a coalescer tier + SWR keeps origin QPS <= 1 per hot key and p99 latency < 15 ms.

TL;DR30-second simplified summary
▾

200 stateless pods require cluster-wide coalescing via consistent hashing. Pairing that with Redis dual-TTL Stale-While-Revalidate and XFetch probabilistic early refresh eliminates both thundering herds and miss-latency spikes.

Negative caching blocks non-existent key scans.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Singleflight Request Coalescing: Eliminating Thundering Herds
Singleflight maintains an in-flight map of active keys so that concurrent callers for the same key await a single leader execution instead of stampeding the origin.
Distributed & Application Caching
Caching keeps a reusable copy of data so an application can avoid repeating a database query, calculation, or network call. It can make responses faster and reduce database load. The trade-off: the copy may be out of date.
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Full walkthrough · 7 stages
01
STAGE 01 · CAPACITY MATHfoundation

Quantifying Pod-Level vs. Cluster-Wide Amplification.

Why this matters: Quantify why 200 API pods with local-only singleflight still overload a 2,000 QPS PostgreSQL ceiling.

Assume 500K total QPS across 200 API pods (2,500 QPS/pod) and a PostgreSQL origin ceiling of 2,000 QPS.

If 20 hot keys expire simultaneously, local-only singleflight emits 20 * 200 = 4,000 origin queries—double the database limit. Consistent-hash coalescing reduces that to 20 * 1 = 20 origin queries (1% of DB capacity).

STAGE 01 · CAPACITY MATH

Quantifying Pod-Level vs. Cluster-Wide Amplification

500K Total Read QPSCluster Load20 Hot Keys Expire4,000 Origin QPSPostgreSQL CeilingOrigin CollapseGlobal CoalescerRing20 Origin QPSexceeds 2x

1.Pod Amplification Math: 20 simultaneously expiring keys x 200 pods = 4,000 concurrent DB queries—2x PostgreSQL capacity.

2.Global Coalescing Goal: Reduce origin queries per expired key from N_pods (200) down to exactly 1.

3.Latency Target: Hold p99 read latency <10 ms even during mass TTL expirations.

Local-only singleflight across 200 pods still emits 200x origin queries; global coalescing collapses 4,000 QPS to 20.

02
STAGE 02 · MULTI-TIER CACHEfoundation

L1 Process Cache + L2 Redis with Dual-TTL SWR.

Why this matters: Pair a 2s L1 process cache with L2 Redis Dual-TTL Stale-While-Revalidate for <2 ms hot reads.

Store {payload, soft_ttl_ts, hard_ttl_ts} in Redis. When now < soft_ttl_ts, return immediately (< 2 ms). When soft_ttl_ts <= now < hard_ttl_ts, serve the stale payload immediately to the caller while triggering an async singleflight background refresh.

Only when now >= hard_ttl_ts (cold miss) does the caller block on the Singleflight Coalescer.

STAGE 02 · MULTI-TIER CACHE

L1 Process Cache + L2 Redis with Dual-TTL SWR

L1 Process Cache(2s)Sub-ms HitL2 Redis Dual-TTLShared Cachesoft <= now < hardZero Caller WaitAsync Ring RefreshOrigin Updateif soft expired

1.Three-State TTL: Fresh (<soft_ttl) returns immediately; Stale (<hard_ttl) serves stale + refreshes async; Expired (>=hard_ttl) blocks on Singleflight.

2.Why L1 Matters: A 2-second in-process LRU shields Redis and the coalescer ring from 100K QPS single-key spikes.

3.Payload Overhead: Storing soft_ttl_ts alongside the JSON/protobuf value adds just 16 bytes per Redis key.

L1 2s process caching plus L2 Redis Dual-TTL SWR serves stale payloads in <2 ms while refreshing in the background.

Engineering Decision Framework
Problem
How to implement Design a Thundering-Herd Cache Stampede Shield with Singleflight Coalescing 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 traffic spikes expose hidden coupling, local singleflight alone still sends 200 queries across 200 pods; consistent-hash routing to a coalescer tier + SWR keeps origin QPS <= 1 per hot key and p99 latency < 15 ms.
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 Design a Thundering-Herd Cache Stampede Shield with Singleflight Coalescing experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · COALESCER RINGintermediate

Consistent-Hash Routing & Bounded-Wait Singleflight.

Why this matters: Route cache misses through a Maglev/Ketama consistent-hash coalescer ring with backup failover.

Use Maglev or Ketama consistent hashing with 150 virtual nodes per coalescer pod so key K always hashes to primary node P(K) (with backup B(K) if P(K) fails health checks).

class StampedeShield:
    def __init__(self, ring, singleflight, redis_client, origin_fn) -> None:
        self.ring = ring
        self.sf = singleflight
        self.redis = redis_client
        self.origin_fn = origin_fn
STAGE 03 · COALESCER RING

Consistent-Hash Routing & Bounded-Wait Singleflight

L2 Cache MissConsistent RoutePrimary CoalescerP(K)Singleflight GroupBackup Node B(K)Zero SPOF1 Origin DB QueryCoalesced Fan-Outif P(K) down

1.150 Virtual Nodes: 150 vnodes per coalescer pod keep key distribution within ~5% variance across the ring.

2.Bounded Follower Wait: Followers wait at most 150 ms on P(K) before falling back or returning stale data.

3.Detached Leader Context: Leader refresh uses an independent backend timeout so one caller abort never fails others.

Consistent-hash routing to Primary/Backup coalescer pods collapses 200 pods into 1 origin query with fast failover.

04
STAGE 04 · XFETCHintermediate

Eliminating Cold Misses via Probabilistic Early Refresh.

Why this matters: Eliminate cold-miss waiting altogether by triggering XFetch probabilistic early refreshes before soft_ttl.

Each read computes -delta * beta * ln(rand()), where delta is the last recomputation duration and beta = 1.0. If now - delta * beta * ln(rand()) >= soft_ttl, one caller triggers an async Singleflight refresh early.

Hot keys are refreshed proactively, while cold keys never waste background CPU.

STAGE 04 · XFETCH

Eliminating Cold Misses via Probabilistic Early Refresh

Redis Read HitNormal Requestnow - d*b*ln(rand)XFetch Formula1 Early RefreshPre-ExpiryFresh Before ExpirySmooth p99if triggered

1.Why XFetch Works: As now approaches soft_ttl, high-QPS keys have exponentially rising probability of refreshing early.

2.Recompute-Time Aware: Keys with larger delta (longer DB query) start refreshing earlier automatically.

3.Zero Extra Infrastructure: XFetch runs inline using random() and the stored last-recompute duration delta.

XFetch uses recomputation duration delta to probabilistically refresh hot keys before soft_ttl expires.

05
STAGE 05 · HOT-KEY PROTECTIONadvanced

Protecting the Coalescer Node from 100K QPS on One Key.

Why this matters: Protect the coalescer pod NIC from 100K QPS single-key spikes using L1 caches and salted key striping.

Think of Protecting the Coalescer Node from 100K QPS on One Key as the intuition layer for Design a Thundering-Herd Cache Stampede Shield with Singleflight Coalescing: Protect the coalescer pod NIC from 100K QPS single-key spikes using L1 caches and salted key striping.

If 100K QPS hits one coalescer pod for product:999, even a fast hash lookup can saturate that pod's NIC. Solve this with a 2-second L1 in-process cache on every API pod (absorbing 99%+ of hot reads locally) plus 2-choice power-of-two sharding (K#0, K#1) only when qps(K) > threshold.

STAGE 05 · HOT-KEY PROTECTION

Protecting the Coalescer Node from 100K QPS on One Key

100K QPS Hot KeyNIC Saturation2s L1 In-Process LRU1K QPS to RingOptional KeySalting8x Ring SpreadBalanced PodCPU/NICProtected Ringif still hot

1.L1 Shield Math: A 2-second L1 cache reduces 100K QPS on a single key to at most 100 misses/sec across 200 pods.

2.Hot-Key Salting: For ultra-hot keys, striping across 8 salts trades 8x origin calls for 8x coalescer NIC distribution.

3.Singleflight + L1: Populate L1 directly from the Singleflight response to heal all 200 pods within 1 round-trip.

2s L1 process caches and optional 8-way key salting prevent single hot keys from saturating one coalescer pod.

06
STAGE 06 · FAILURE ISOLATIONadvanced

Origin Circuit Breakers, Negative Caching & Shedding.

Why this matters: Prevent cascading DB outages with per-shard origin semaphores, circuit breakers, and stale-if-error.

Cap concurrent origin queries per shard via a semaphore (e.g., max 500 in-flight). If PostgreSQL p99 exceeds 200 ms, trip the circuit breaker: immediately return hard_ttl stale data if available or short-circuit with 503 Retry-After.

Cache NOT_FOUND tombstones for 30s (negative caching) to block cache-penetration attacks.

STAGE 06 · FAILURE ISOLATION

Origin Circuit Breakers, Negative Caching & Shedding

Origin SemaphoreConcurrency CapLatency BreakerOrigin ShieldStale-If-ErrorGraceful DegradeFast 503 +Retry-AfterFail Fastif hard_ttl ok

1.Semaphore Cap: Hard-capping in-flight origin queries at 500 prevents PostgreSQL connection-pool exhaustion.

2.Stale-If-Error: When the origin breaker is open, extending hard_ttl stale serves keeps 99% of reads healthy.

3.No Negative 503 Caching: Call Forget(key) on transient 5xx errors so the next healthy probe can recover immediately.

Per-shard origin semaphores, >200 ms breakers, and stale-if-error keep reads serving during DB degradation.

07
STAGE 07 · OBSERVABILITYadvanced

Tracking Coalesce Ratio, Stale-Serve Rate & Ring Churn.

Why this matters: Track coalesce ratio, stale-serve rate, XFetch early refreshes, and graceful ring draining during deploys.

Think of Tracking Coalesce Ratio, Stale-Serve Rate & Ring Churn as the intuition layer for Design a Thundering-Herd Cache Stampede Shield with Singleflight Coalescing: Track coalesce ratio, stale-serve rate, XFetch early refreshes, and graceful ring draining during deploys.

Emit singleflight_coalesce_ratio (followers / leaders), stale_serve_rate, xfetch_early_refresh_count, and origin_qps. During rolling deployments, use graceful draining on the coalescer ring so in-flight leaders finish and populate Redis before pod termination.

STAGE 07 · OBSERVABILITY

Tracking Coalesce Ratio, Stale-Serve Rate & Ring Churn

coalesce_ratioEfficiency KPIstale_serve_rateFreshness KPIGraceful Ring DrainDeploy Safetyorigin_qps > 1,600Headroom Guardprotected by

1.Coalesce Ratio: A high followers/leaders ratio confirms the ring is actively collapsing stampedes.

2.Graceful Ring Draining: Drain coalescer pods sequentially during deploys so only 1/N keys remap per step.

3.Origin Headroom Alert: Page on-call if origin QPS crosses 80% of the 2,000 QPS PostgreSQL ceiling.

Monitoring coalesce ratios, stale-serve rates, and origin QPS headroom ensures stampede protection holds during deploys.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does local-only Singleflight on 200 API pods still risk overwhelming a 2,000-QPS PostgreSQL origin?

Recommended Learning Flow