FullStack AI Hub
Studio
System Design · 02. Scaling
12 min
11 steps
Beginner

Caching Strategies

Master cache-aside, write-through, TTL jitter, and preventing thundering-herd cache stampedes.

System Design02. ScalingLesson 3 of 5
12 minBeginner11 steps

Caching Strategies

Master cache-aside, write-through, TTL jitter, and preventing thundering-herd cache stampedes.

READ RPS
3,200/s
CACHE HIT
0%
P95 LATENCY
640 ms
DB LOAD
94%
24k shoppersAPI Server A54%API Server B54%Primary DB94%94% CPU3,200/s repeat reads melting disk I/O
cache hit / read
cache miss / DB query
write / backfill
dropped / overload
In This LessonStep 1 of 11
What You Will Master
  • ✓Shield read-heavy databases with Cache-Aside and calculate effective hit-rate latency
  • ✓Compare Write-Through consistency against Write-Back throughput and durability risks
  • ✓Tune LRU/LFU eviction and TTL windows to balance memory usage against stale reads
  • ✓Stop thundering-herd stampedes using Singleflight coalescing, TTL jitter, and L1/L2 tiers

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Cache-Aside (Lazy)Read-heavy feeds, product pages, user profilesFirst read misses; brief staleness if invalidation lags
Write-ThroughSession stores, config flags, strong read freshnessHigher write latency; caches keys that may never be read
Write-Back (Behind)Like counters, telemetry bursts, write-heavy analyticsRisk of data loss if cache crashes before async DB flush
L1 + L2 + SingleflightViral hot keys and global high-RPS API fleetsExtra coordination complexity and tiny per-node L1 drift

Step-by-Step Architectural Breakdown (11 Steps)

Full architectural walkthrough transcript and state transitions for Caching Strategies.

STEP 01 · PROBLEMJump to step →

90% repeat reads slamming the Primary DB

Your storefront serves **3,200 read requests/sec**, yet over **85%** of those queries fetch the exact same top 500 product pages and homepage banners.

Because every API server queries **Primary DB** directly on disk, the database is pinned at **94% CPU**, P95 latency has ballooned to **640 ms**, and checkout queries are timing out.

watch:Disk-backed databases are built for durable transactions—not answering the exact same hot read thousands of times per second.

Read-Heavy WorkloadPower-Law Hot KeysDatabase Saturation
STEP 02 · SOLUTIONJump to step →

Add Cache-Aside (Lazy Loading) with Redis

We introduce an in-memory **Redis Cache** beside the database. On every read, the API server checks Redis first: if the key exists (**cache hit**), it returns in **< 2 ms** and never touches Postgres.

Only on a **cache miss** does the server query Primary DB and lazily backfill Redis with a TTL. At an **85% hit rate**, database traffic drops from 3,200/s down to just **480/s**.

good:Cache-Aside is resilient by default: if Redis restarts empty, requests gracefully fall back to the DB instead of failing hard—as long as DB headroom holds.

Cache-AsideLazy LoadingCache Hit vs Miss
STEP 03 · TECHNIQUEJump to step →

Hit-rate math: why 95% vs 75% is a 5× DB swing

Engineers often underestimate small drops in cache hit rate. Dropping from **95% → 75% hit rate** sounds like a modest 20-point dip, yet the **miss rate jumps from 5% to 25%**—a **5× surge** in database load!

Effective latency follows **T_eff = h · T_cache + (1 − h) · T_db**. With a 2 ms cache and 80 ms DB, 95% hits average **5.9 ms**, while 75% hits average **21.5 ms** and multiply DB CPU fivefold.

idea:Always track Miss Rate (1 − Hit Rate) on database dashboards—it is directly proportional to backend database load.

Miss Rate AmplificationEffective Latency FormulaWorking Set Size
STEP 04 · TECHNIQUEJump to step →

Write-Through: keep cache fresh on every write

With pure Cache-Aside, updating a product price in the database leaves the old value sitting in Redis until TTL expires. **Write-Through** routes every write synchronously through the cache into the database.

Reads always see fresh data right away—zero stale window—at the cost of **higher write latency** (two sequential hops) and RAM spent storing cold keys that may never be read.

idea:Pair Write-Through with a reasonable TTL so rarely-read writes still get reclaimed cleanly instead of filling RAM forever.

Write-ThroughSynchronous ConsistencyWrite Latency Penalty
STEP 05 · TRADE-OFFJump to step →

Write-Back (Write-Behind): absorb massive write bursts

What if you are ingesting **6,000 view counts or likes per second**? Waiting for disk commits on every increment is too slow. **Write-Back** writes straight to Redis, ACKs the user in **3 ms**, and coalesces dirty keys into batched async DB flushes.

Throughput skyrockets and DB write IOPS drop by **80%**, but there is a sharp trade-off: **if the cache node crashes before flushing its dirty buffer, those recent writes are lost forever.**

watch:Never use Write-Back for payments or inventory balances—reserve it for high-volume counters, analytics, or replicated durable caches.

Write-Back (Write-Behind)Write CoalescingDurability vs Speed
STEP 06 · TECHNIQUEJump to step →

Memory fills up: LRU vs LFU eviction

RAM is expensive and finite. Once Redis hits **maxmemory**, every new write must evict an existing key. **LRU (Least Recently Used)** drops the key untouched for the longest time—simple and great for recency-driven feeds.

However, a single batch scan of 100k cold archival items can flush out your hottest items under LRU! **LFU (Least Frequently Used)** tracks access frequency so evergreen hot keys survive one-time scan pollution.

idea:Redis supports allkeys-lru and allkeys-lfu natively via approximated sampling—giving O(1) eviction without sorting millions of keys.

LRU EvictionLFU EvictionCache Pollution
STEP 07 · TRADE-OFFJump to step →

TTL tuning: freshness vs database pressure

A **Time-To-Live (TTL)** bounds how long stale data can linger if an explicit delete message is lost. Set TTL too **long (24 hours)** and users see outdated prices; set it too **short (5 seconds)** and keys expire constantly, slashing your hit rate.

Production teams pair **explicit invalidation on write** with a **moderate safety TTL (5–15 min)** so normal updates appear immediately while missed invalidations self-heal automatically.

good:Use Event-Driven Invalidation for freshness, and TTL as your safety net—never rely on tiny 5-second TTLs alone.

TTL (Time-To-Live)Explicit InvalidationBounded Staleness
STEP 08 · PROBLEMJump to step →

The Cache Stampede (Thundering Herd)

Imagine a viral flash-sale item cached with a **60-second TTL**. At second 60, that single key expires. Within the next 50 milliseconds, **500 concurrent requests** all miss Redis at the exact same instant.

Every single API thread launches the **exact same expensive SQL query** simultaneously. Primary DB spikes past **100% CPU**, queries time out, and the cache never even gets repopulated—a cascading **thundering herd** outage.

watch:Setting identical fixed TTLs across keys loaded at boot also causes synchronized mass expiries every hour on the dot.

Cache StampedeThundering HerdDog-Pile Effect
STEP 09 · SOLUTIONJump to step →

Stop stampedes with Singleflight & TTL Jitter

Two lightweight defenses neutralize stampedes permanently. First, **Request Coalescing (Singleflight)** lets only **one** flight per missing key query Postgres while the other 499 waiting goroutines share that single returned result.

Second, **TTL Jitter** adds a random offset (`300s + rand(0..60s)`) to every key so bulk-loaded entries expire smoothly over a minute instead of all dying on the exact same second.

good:For ultra-hot keys, combine Singleflight with probabilistic early refresh (refreshing in the background before TTL hits zero).

Singleflight CoalescingTTL JitterProbabilistic Early Refresh
STEP 10 · TECHNIQUEJump to step →

Two-tier caching: In-process L1 + Shared L2 Redis

Even Redis has a network ceiling: a single celebrity hot key served at **50,000 req/s** can saturate one Redis shard’s NIC and CPU. Adding a tiny **in-process L1 cache** inside each API server absorbs **70%** of repeats in **< 0.1 ms** with zero network hops.

L1 misses fall through to the shared **L2 Redis cluster**, and only double-misses reach **Primary DB**. Keep L1 TTLs short (e.g., 5–15s) so per-node staleness stays tightly bounded.

idea:L1 eliminates the network round-trip for the hottest 1% of keys while L2 gives the whole fleet a large shared memory pool.

L1 In-Process CacheL2 Distributed CacheHot-Key Shielding
STEP 11 · RECAPJump to step →

Production caching blueprint

Great caching is not “put Redis in front and hope.” Start with **Cache-Aside** for read-heavy workloads, add **Singleflight + TTL Jitter** so hot expirations never stampede Postgres, and layer a tiny **L1 cache** if one hot key threatens a single Redis shard.

Use the live chaos triggers below to stress-test the complete production stack before moving to the Practice Quiz or Design Lab.

good:Default to Cache-Aside + Singleflight + Jittered TTLs; use Write-Through when staleness is unacceptable and Write-Back only when losing a few seconds of counters is safe.

Cache-Aside BlueprintSingleflight + JitterL1/L2 Shield

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-101Model Serving and Inference

Understand inference engines memory scheduling batching routing scaling distributed execution lifecycle controls observability and economics.

19 concepts~23h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.