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.
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.
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:
- 17.5× DB Overload: 70,000 QPS hits a 4,000 QPS Postgres cluster, exhausting connections and CPU.
- Retry Amplification: Timed-out pods retry, compounding DB saturation.
- Slow Recovery: Even after Redis starts repopulating, Postgres cannot respond fast enough to refill 120,000 keys.
TTL Jitter + Singleflight + Stale-While-Revalidate
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.
- 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 viasingleflight, and servestale-while-revalidatefallbacks using logical expiration metadata. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
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?
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.
Naive Solution (and Why It Breaks)
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). Whennow > 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
singleflightand guard Postgres with a RedisSET NXlease.
01:00:00 UTC Synchronized Cliff vs. Smooth Jittered Refresh
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)
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: Make the trade-off yourself.
How does adding `random(0, 20%)` jitter to a 3600s batch-warmed TTL prevent a cache avalanche?