Module 4: Caching & CDN
Caching Deep Dive
Application, database, and CDN caching layers — cache-aside vs write-through, what to cache, TTLs, stampedes, and how caching cuts latency and load.
Caching stores expensive results closer to the consumer. Done well, it drops p99 and shields the database. Stacked carelessly, you debug ghosts — stale reads, stampedes, and mystery misses.
What you will learn
- Place browser, CDN, app, and DB cache layers on a diagram
- Describe cache-aside, write-through, and write-behind at interview depth
- Pick cache candidates from access patterns and staleness tolerance
- Design key names, TTLs, and eviction awareness
- Call out stampede risk and when not to cache
Why cache?
- A cache trades freshness for speed and cheaper load. Name both sides in the interview.
- Cut latency — memory/edge reads beat disk and cross-region DB RTT
- Cut origin load — repeated hot keys stop hammering SQL
- Absorb spikes — short bursts hit cache while backends catch up
- Cost — extra infra, invalidation complexity, possible stale reads
- Caching is not a substitute for correct indexes or a sane data model
Cache layers on the path
- Draw layers from user toward disk. Each layer has a different hit rate and staleness story.
- Browser cache — private assets and Cache-Control for repeat visits
- CDN / edge — static files and some public HTTP responses near users
- Application cache (Redis/Memcached) — hot keys, sessions, fragments, computed results
- Local in-process cache — tiny ultra-hot lookups; careful with multi-instance inconsistency
- Database buffer pool — engine page cache; you influence it less directly
What to cache (and what not to)
- Good candidates are read-heavy, expensive to compute, and tolerant of bounded staleness.
- Good: product pages, user profiles, permissions snapshots, feed fragments, config
- Good: CDN for JS/CSS/images/videos with fingerprinted URLs
- Risky: balances, inventory counts, anything legally/financially exact without care
- Poor: rarely read keys — memory waste; write-heavy keys — constant churn
- Personalization may need private cache keys or no shared CDN cache
Cache-aside (lazy loading)
- The most common application-cache pattern in interviews. The app owns the logic.
- Read: check cache → on miss load DB → populate cache → return
- Write: update DB, then delete or update the cache key
- Pros: simple, cache failures can fall back to DB
- Cons: first request after miss is slow; easy to forget invalidation on some writes
- Default mental model for Redis in system design
Write-through & write-behind
- These couple the cache more tightly to the write path.
- Write-through — write hits cache and store together; reads often find warm data
- Write-behind (write-back) — write to cache first, flush to DB asynchronously; fast writes, durability risk
- Write-through raises write latency; write-behind risks data loss on cache crash
- Use write-behind only with clear durability story (WAL, replicas, acknowledgements)
- Many teams stick to cache-aside + explicit delete for correctness clarity
Keys, TTL, and eviction
- Operational details separate a hand-wavy “add Redis” from a real design.
- Key design: namespace:id:field — predictable and easy to purge
- TTL: bound staleness; shorter for volatile data, longer for static
- Eviction (LRU/LFU/TTL): memory is finite; expect cold keys to disappear
- Negative caching: briefly cache “not found” to stop repeated DB misses
- Serialization cost (JSON vs binary) matters at high QPS
Stampede & thundering herd
- When a hot key expires, thousands of requests can miss together and crush the DB.
- Symptoms: expiry → miss spike → DB CPU spike → timeouts
- Mitigations: single-flight/lock around rebuild, soft TTL + background refresh
- Probabilistic early expiry, staggered TTLs, or pre-warm after deploy
- Serve stale briefly while one worker refreshes (stale-while-revalidate idea)
- CDN and app caches can both stampede — protect the origin
CDN vs application cache
- Both are caches; they sit in different places and solve different problems.
- CDN — geo distribution for static/public content; huge win for bytes and TTFB
- App cache — fine-grained keys, per-user data, computed query results
- CDN purge can be slower/global; app cache delete is usually instant per cluster
- Authenticated HTML/API responses are often not CDN-cached (or are privately cached)
- Stack them: CDN for assets, Redis for hot API objects
Consistency & invalidation (preview)
- Freshness policy is part of the design. Deep strategies continue in the next lesson.
- TTL — simple bounded staleness
- Explicit invalidate on write — fresher; must hit every layer that stores the key
- Versioned keys — bump version so readers naturally miss old entries
- Multi-layer systems fail when one layer is forgotten
- Pick stricter invalidation for profile/settings; TTL for feeds/counters
Common mistakes
- These designs look fast on the whiteboard and fail in production.
- Caching everything without a staleness budget
- No key naming convention — cannot purge reliably
- Forgetting delete-on-write in cache-aside
- Giant values that thrash memory and network
- Using cache as the only source of truth with no DB rebuild path
Interview framing
- Use this order when latency or DB load shows up.
- Point to the hot read on your request-path diagram
- Choose the layer (CDN vs Redis) that matches the data
- State pattern (usually cache-aside), key, and TTL
- Describe write-path delete/update and stampede defense
- Say what must never be served stale
Quick revision checklist
- State TTL defaults and why.
- Name key formats explicitly.
- Call out stampede on hot key expiry.
- Prefer cache-aside unless you need tighter write coupling.
- Separate CDN (static/public) from Redis (app objects).
- Say what you will not cache.
FAQs
Should everything be cached?
No. Rarely read or strongly consistent sensitive data may bypass cache. Wrong cache = wrong product.
Cache-aside vs write-through?
Cache-aside loads the cache on read miss and usually deletes/updates on write. Write-through updates cache and store together on write so reads stay warm, at higher write latency.
Is Redis a database or a cache?
It can be either. In this lesson treat it as a cache in front of a system of record unless you explicitly design durability and ownership around Redis.
Why do I still need indexes if I have a cache?
Cache misses, cold starts, and uncached queries still hit the DB. Indexes keep the miss path fast; cache reduces how often you take that path.
How do I choose TTL?
From the product’s staleness budget and change rate. Profiles might allow minutes; stock tickers might allow seconds or none; fingerprinted static assets can live days.
What is a cache stampede?
Many concurrent requests miss the same expired hot key and rebuild from the DB together. Use locking, single-flight, or stale-while-revalidate style refresh to prevent it.
Learner’s Task
- Practice out loud for 8–10 minutes. Add caching to a read-heavy API without hand-waving.
- Pick a hot read (product page or user profile) and draw CDN + Redis + DB on the request path.
- Choose cache-aside; write the read miss path and the write invalidate path step by step.
- Define key name, TTL, and one field you refuse to cache.
- Describe how you prevent a stampede when that key expires at peak QPS.
- Write a 4-sentence closing: layer choice, pattern, freshness policy, and load/latency win.