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

Preventing Cache Avalanche
with TTL Jitter.

When tens of thousands of hot cache keys are warmed together with an identical fixed TTL (e.g., 3600s), they expire simultaneously, unleashing a massive thundering herd onto the database that exhausts connection pools and triggers cascading 504s.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When tens of thousands of hot cache keys are warmed together with an identical fixed TTL (e, break TTL synchronization with randomized jitter (`base_ttl + random(0, 20%)`), coalesce concurrent misses via `singleflight`, and serve `stale-while-revalidate` fallbacks using logical expiration metadata.

TL;DR30-second simplified summary
▾

Core Mechanics: An e-commerce catalog serves 80,000 QPS from a 4-shard Redis 7 cluster (64 GB RAM, 99.4% hit rate) backed by PostgreSQL (4,000 QPS max).

Visual & Structural Flow: Depicts TTL Jitter + Singleflight + Stale-While-Revalidate (40 App Pods (80k QPS) -> Redis 7 (64 GB) -> Stale Fallback -> Postgres (4k QPS max)); 01:00:00 UTC Synchronized Cliff vs. Smooth Jittered Refresh (80k QPS Traffic -> App (Singleflight) -> Redis 7 -> Postgres (4k max)).

Trade-Offs & Production: Simply raising the uniform TTL from 1 hour to 24 hours only delays the avalanche to 00:00 UTC the next day. Break expiration synchronization and cap DB refresh concurrency: Randomized TTL Jitter: Never write uniform TTLs in batch warmers; set ttl = 3600 + random.randint(0, 720) so.

Failure Modes & Application: TTL jitter and soft-expiration are standard across high-QPS read-heavy systems: E-Commerce Product Catalogs & Pricing: Prevents nightly batch pre-warming from causing midnight DB cliffs.

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.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Preventing Cache Avalanche Matters.

Why this matters: The mechanism: understand how Why Preventing Cache Avalanche Matters works from first principles.

An e-commerce catalog serves 80,000 QPS from a 4-shard Redis 7 cluster (64 GB RAM, 99.4% hit rate) backed by PostgreSQL (4,000 QPS max).

Every night at 00:00 UTC, a batch job pre-warms 120,000 product keys with an identical EX 3600 TTL.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Synchronized TTL Expiry.

Why this matters: The problem: see what breaks without Real-World Impact of Synchronized TTL Expiry under real concurrency or scale.

Synchronized expiration turns a 99.4% cache hit ratio into an instant DB outage:

  1. 17.5× DB Overload: 70,000 QPS hits a 4,000 QPS Postgres cluster, exhausting connections and CPU.
  2. Retry Amplification: Timed-out pods retry, compounding DB saturation.
  3. Slow Recovery: Even after Redis starts repopulating, Postgres cannot respond fast enough to refill 120,000 keys.
Cache Avalanche Defense

TTL Jitter + Singleflight + Stale-While-Revalidate

40 App Pods (80kQPS)singleflight coalesceRedis 7 (64 GB)TTL = 3600 +…Stale FallbackServe soft-expired…Postgres (4k QPSmax)Protected <= 1…Coalesced DB refresh

1.TTL Jitter: base_ttl + random(0, 20%) spreads 120k expirations across 12 minutes.

2.Singleflight: Coalesces concurrent pod misses for the same key into 1 DB query.

3.Soft/Hard TTL: Serve stale data up to 60s while refreshing asynchronously.

4.Circuit Breaker: Shed/serve stale if DB latency spikes.

TTL jitter spreads expirations over 12 minutes while soft-TTL stale-while-revalidate shields Postgres.

Engineering Decision Framework
Problem
How to implement Preventing Cache Avalanche with TTL Jitter 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 tens of thousands of hot cache keys are warmed together with an identical fixed TTL (e, break TTL synchronization with randomized jitter (base_ttl + random(0, 20%)), coalesce concurrent misses via singleflight, and serve stale-while-revalidate fallbacks using logical expiration metadata.
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 Cache Avalanche with TTL Jitter 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 Cache Avalanche with TTL Jitter: The problem: see what breaks without Naive Solution under real concurrency or scale.

Simply raising the uniform TTL from 1 hour to 24 hours only delays the avalanche to 00:00 UTC the next day. Setting no-eviction without TTLs causes stale catalog data or OOM, and adding more Redis shards doesn't help when all 120,000 keys expire at the exact same timestamp.

Component Topology

Naive Solution (and Why It Breaks)

App ServersingressSingleflightcomputeRedis L2storagePrimary DBcontrolGET hot_keyL2 lookup1x origin fetch
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: Randomized TTL Jitter, Singleflight & Soft-TTL Refresh.

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

Break expiration synchronization and cap DB refresh concurrency:

  • Randomized TTL Jitter: Never write uniform TTLs in batch warmers; set ttl = 3600 + random.randint(0, 720) so 120,000 keys expire smoothly at ~166 keys/sec instead of 120,000/sec.
  • Logical Soft-TTL (stale-while-revalidate): Store {payload, soft_exp} with a longer Redis physical TTL (hard_exp = soft_exp + 300s). When now > soft_exp, serve the cached value immediately (within the 60s staleness SLA) and trigger a background refresh.
  • In-Process Singleflight + Mutex: Coalesce concurrent misses per pod via singleflight and guard Postgres with a Redis SET NX lease.
Soft-TTL Background Refresh

01:00:00 UTC Synchronized Cliff vs. Smooth Jittered Refresh

80k QPS TrafficApp (Singleflight)Redis 7Postgres (4k max)1. Naive (01:00:00): 120k keysexpire -> 70k miss2. 70k QPS slams 4k QPS Postgres-> crash!3. Fixed: TTL=3600+rand(720s) +soft_exp4. Serve soft-stale immediately(<1ms)5. 1 async background refresh perkey

Soft-TTL stale serving + randomized jitter keeps Postgres load flat across batch-warmed key expirations.

import asyncio, json, random, time

inflight: dict[str, asyncio.Future] = {}

async def get_product(redis, db, key: str, base_ttl: int = 3600):
    raw = await redis.get(key)
    now = time.time()
    if raw:
        payload = json.loads(raw)
        if now > payload["soft_exp"] and key not in inflight:
            asyncio.create_task(_singleflight_refresh(redis, db, key, base_ttl))
        return payload["data"]
    return await _singleflight_refresh(redis, db, key, base_ttl)

async def _singleflight_refresh(redis, db, key: str, base_ttl: int):
    if key in inflight:
        return await inflight[key]
    fut = asyncio.get_running_loop().create_future()
    inflight[key] = fut
    try:
        data = await asyncio.wait_for(db.fetch_product(key), timeout=0.5)
        jitter = random.randint(0, int(base_ttl * 0.2))
        payload = {"data": data, "soft_exp": time.time() + base_ttl + jitter}
        await redis.set(key, json.dumps(payload), ex=base_ttl * 2 + jitter)
        fut.set_result(data)
        return data
    except Exception as exc:
        fut.set_exception(exc)
        raise
    finally:
        inflight.pop(key, None)
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Cache Avalanche Defense Applies in System Design.

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

TTL jitter and soft-expiration are standard across high-QPS read-heavy systems:

  • E-Commerce Product Catalogs & Pricing: Prevents nightly batch pre-warming from causing midnight DB cliffs.
  • CDN & Edge Caching: Cache-Control: max-age=3600, stale-while-revalidate=60.
  • Session & Feature-Flag Stores: Spreads bulk-loaded key expirations evenly.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

How does adding `random(0, 20%)` jitter to a 3600s batch-warmed TTL prevent a cache avalanche?

Recommended Learning Flow