Modern System Design & API Architecture · Chapter 4 · ~25 min · Intermediate
Caching Strategies: Cache-Aside, Write-Through & CDN Edge
Master high-performance caching across multi-tier topologies. Understand lazy Cache-Aside, Write-Through, and Write-Back architectures, eviction algorithms (LRU vs. LFU), and how to protect origin databases from Thundering Herd stampedes.
- Master the three core write patterns: Cache-Aside, Write-Through, and Write-Back
- Eliminate race conditions and stale cache overwrites with post-commit key deletion
- Prevent Thundering Herd stampedes using Singleflight mutexes and probabilistic expiration
- Implement multi-tier topologies spanning App Memory, Redis, and Edge CDN PoPs
Caching Strategies: Cache-Aside, Write-Through & CDN Edge: learn it visually
Master multi-tier caching architectures: Cache-Aside vs Write-Through vs Write-Back, TTL invalidation, cache stampede mitigation, and CDN edge termination.
1The Memory Hierarchy: The Sub-Millisecond Imperative
In computer science, disk I/O is thousands of times slower than accessing CPU registers or system RAM. A PostgreSQL query executing an index scan on SSD storage requires 5 to 30 milliseconds. By comparison, reading an in-memory key from Redis takes 0.5 to 1.5 milliseconds, and reading from process RAM takes under 0.001 milliseconds.
In-Process Heap
Guava, Caffeine, or Node memory cache. Instantaneous 0.01ms lookup, but local to a single server instance.
Redis / Memcached
Shared by all web application servers. 1ms network RTT, scales to terabytes of key-value memory.
Cloudflare / Fastly Edge
Terminates TLS geographically closest to users. Caches static assets, images, and public GET endpoints in 10ms.
2The 3 Write Architectures: Cache-Aside vs. Write-Through vs. Write-Back
How your application handles writes dictates whether your system remains consistent or serves dangerous stale data:
1. Cache-Aside (Lazy Loading)
The application logic is responsible for talking to both storage layers. On read: check cache; if miss, read database, write result to cache, and return. On write: update database first, then delete (invalidate) the cache key.
// Cache-Aside Read Flow
async function getAuthor(authorId: string) {
const cached = await redis.get(`author:${authorId}`);
if (cached) return JSON.parse(cached); // Cache Hit (1ms)
const author = await db.authors.findUnique({ where: { id: authorId } }); // Cache Miss (25ms)
if (author) {
await redis.setex(`author:${authorId}`, 3600, JSON.stringify(author)); // TTL 1 hour
}
return author;
}2. Write-Through
The cache acts as the main data store. When a write occurs, the cache synchronously updates the backing database before acknowledging success. Ensures cache is never stale, but incurs higher write latency.
3. Write-Back (Write-Behind)
Writes update the in-memory cache immediately and return success to the client in 0.5ms. The cache marks the record as "dirty" and flushes changes to the database in background asynchronous batches. Danger: if the cache node crashes before flushing, data is lost!
Wrong idea: Directly overwrite the cache with new values whenever database updates occur
Assuming dual-writing to both database and Redis synchronously never results in out-of-order race condition overwrites.
Real system: Cache-Aside with post-commit key deletion guarantees freshness
Instead of writing new values, delete the cache key after committing the database transaction. The next reader lazily repopulates the latest data.
Why does the Cache-Aside pattern recommend DELETING the cache key on update rather than directly setting the new value?
3Eviction Policies: LRU vs. LFU & Memory Sizing
Cache memory is expensive and strictly finite. When Redis reaches its configured maxmemory limit, it must systematically prune old data using an eviction algorithm:
LRU (Least Recently Used)
Discards items that haven't been read or written for the longest duration of time. Excellent for temporal locality (e.g., today's breaking news is hot, yesterday's news is cold).
LFU (Least Frequently Used)
Counts access frequency per key. Discards keys with the lowest hit counter. Prevents a sudden burst of one-off scans from flushing out chronically popular items.
In Redis, what is the key operational difference between 'allkeys-lru' and 'volatile-lru'?
4The Thundering Herd: Cache Stampede Mitigation
Imagine the homepage banner of an e-commerce site with 20,000 requests per second. The cache key has a 60-second TTL. At second 60, the key expires. Over the next 50 milliseconds, 1,000 requests miss simultaneously. Every single worker thread attempts to query the database to recompute the banner. This catastrophic spike is known as a Cache Stampede (Thundering Herd).
Solution A: Singleflight (Mutex Locking)
When a miss occurs, the worker acquires a local or distributed lock (e.g., Redis SET NX). Only ONE thread queries the database; the other 999 threads wait and subscribe to the shared result promise.
Solution B: Probabilistic Early Expiration (XFetch)
As the TTL nears expiration, incoming requests probabilistically trigger a background refresh before the key actually expires, guaranteeing zero misses for active readers.
How does the Singleflight pattern protect an origin database during a cache stampede?
5Hands-On: Multi-Tier Cache Invalidation & Stampede Simulator
Experience cache operations in real time. Read and write items across L1, L2, and DB, test different write strategies, and trigger a 500-request cache stampede with and without Singleflight mutex protection:
Multi-Tier Cache Invalidation & Stampede Simulator
Lazy read load. Writes delete the cache key after DB commit.
Deduplicates concurrent misses into one shared query.
Local Node RAM (0.1ms)
key: item_42
v1.0 (authoritative)
TTL Remaining: 30s
Redis Cluster (1.5ms)
key: item_42
v1.0 (authoritative)
TTL Remaining: 120s
PostgreSQL DB (25ms)
Row: item_42
v1.0 (authoritative)
ACID Committed Storage
12
8
1
0
0
6Bug Hunt: Fix Caching Resiliency & Invalidation Flaws
A production caching service was shipped to reduce database load, but the configuration contains three severe operational bugs: keys are configured without TTL causing memory leaks, the stampede mutex is disabled exposing the database to thundering herd crashes, and updates use an unsafe dual-write pattern.
Fix the cache configuration below and click Run & verify:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Configure a safe TTL: set
defaultTtlSecondsto a value like3600(between 60 and 86400). - Activate stampede protection: set
useSingleflightMutex: true. - Prevent dual-write race conditions: set
writeStrategy: "cache-aside".
7Recap
- Cache-Aside is the gold standard for web backends: read on miss, delete key on database commit.
- Write-Through provides strong consistency at the expense of higher write latency.
- Write-Back accelerates write throughput with in-memory dirty queues, but risks data loss on power failure.
- Always set explicit TTL expiration and an eviction policy like allkeys-lru to prevent memory leaks.
- Mitigate Thundering Herd stampedes using Singleflight mutexes or probabilistic early refresh.
Ready for Chapter 5 (Load Balancing & Consistent Hashing)? Mark this chapter as complete to proceed: