Chapter 11: Caching — Strategies, Invalidation, CDNs

Cache Layers

Client ──► CDN (static assets, edge cache) ──► API Gateway cache (response cache) ──► Application cache (Redis/Memcached) ──► Database cache (query cache, buffer pool) ──► OS cache (page cache) ──► Hardware cache (CPU L1/L2/L3) Each layer catches requests before they hit the next (slower) layer.

Caching Strategies

StrategyReadWriteConsistency
Cache-AsideCheck cache → miss → read DB → fill cacheWrite DB, invalidate cacheEventual (stale until invalidated)
Read-ThroughCache handles DB read on missWrite DB, invalidate cacheEventual
Write-ThroughAlways from cacheWrite cache + DB synchronouslyStrong
Write-BehindAlways from cacheWrite cache, async flush to DBEventual (risk of data loss)

CDN (Content Delivery Network)

Without CDN: User (Tokyo) ──── 200ms RTT ────► Origin Server (Stockholm) With CDN: User (Tokyo) ── 5ms ──► CDN Edge (Tokyo) ── cache hit ──► response │ cache miss ▼ Origin Server (Stockholm)

Cache at CDN: static files (images, CSS, JS), API responses (with short TTL), video chunks

Cache Invalidation

"There are only two hard things in computer science: cache invalidation and naming things." — Phil Karlton

Cache Eviction Policies

Key Takeaways