4. Caching
One-liner. Trade freshness and memory for latency and database load.
Memorize
- Cache-aside (lazy): read cache → miss → DB → fill. Standard, tolerant of cache loss.
- Write-through: write cache and DB together — consistent, slower writes.
- Write-behind: write cache, flush later — fast, risks data loss.
- TTL + eviction (LRU/LFU) define staleness; negative caching protects against misses on missing keys.
- Stampede: many misses on one key → lock/single-flight, jittered TTL, or stale-while-revalidate.
- Layers: browser → CDN → API cache → app cache (Redis) → DB buffer pool.
Trap. Caching personalized responses in a shared layer — one user sees another's data. Do this. State the invalidation story before adding the cache.
Check
A product page cache expires, and 50k concurrent requests hit the database at once. Which fix addresses the root cause?
Why
A stampede is concurrency on the same key; coordinating one rebuild fixes it. TTL tuning only changes the timing.