Caching and CDNs¶
What you'll be able to do¶
- Choose between cache-aside, write-through and write-behind for a given workload.
- Estimate what a cache hit ratio does to average latency.
- Explain where a CDN fits and what a "cache stampede" is.
Why cache at all¶
Reading from memory takes microseconds to a millisecond. A database query over the network takes several milliseconds or more, and the database is the hardest tier to scale. A cache keeps the answers to popular, repeated questions close to the caller so most requests never reach the database.
The payoff is easy to compute:
average latency = hit_ratio × cache_time + (1 − hit_ratio) × database_time
95% hits, 1 ms cache, 20 ms database:
0.95 × 1 + 0.05 × 20 = 1.95 ms (vs 20 ms with no cache)
A 95% hit ratio also means the database sees only 5% of the read traffic. Often that, not latency, is the real win.
The layers where caches live¶
Closer to the user means faster and cheaper, but harder to invalidate.
Patterns for reading and writing¶
| Pattern | How it works | Good for | Watch out |
|---|---|---|---|
| Cache-aside | App checks cache; on miss, reads DB and fills the cache | Most read-heavy apps (default choice) | Stale data until TTL or invalidation; first request is slow |
| Read-through | Cache itself loads from the DB on a miss | Simplifies app code | Needs a cache that supports it |
| Write-through | Write goes to cache and DB together | Data that must be fresh on read | Slower writes; caches data that may never be read |
| Write-behind | Write to cache, flush to DB later | Write-heavy, loss-tolerant data | Data loss if the cache dies before flushing |
The hard part: invalidation¶
The saying "there are only two hard things in computer science" has a reason. Your options:
- TTL (time to live): entries expire after N seconds. Simple, and tolerates staleness of up to N seconds. Pick N from how stale the business can accept.
- Explicit invalidation: delete or update the cache entry when the data changes. Fresher, but you must find every code path that writes.
- Versioned keys: put a version in the key (
user:42:v7); changing the version makes old entries unreachable.
Eviction is a separate question: when the cache is full, what goes? LRU (least recently used) is the common default.
Failure modes to know¶
- Cache stampede (thundering herd): a hot key expires and thousands of requests all miss at once and hit the database. Mitigate with request coalescing (one request refills, the others wait), jittered TTLs (so keys don't all expire together) and refreshing hot keys before they expire.
- Cache penetration: requests for keys that don't exist always miss. Cache the "not found" result briefly.
- Hot key: one key gets so much traffic that one cache node is overwhelmed. Replicate it or add a small local cache in front.
- Cold start: an empty cache sends everything to the database. Warm it before sending full traffic.
CDNs: caching at the edge of the internet¶
A CDN keeps copies of content on servers spread around the world, so the user fetches from a nearby edge instead of your distant origin.
- Best for static files (images, JS, video), and increasingly for cacheable API responses.
- You control it through headers such as
Cache-Control: max-age=…, and through the cache key (which parts of the URL, headers, cookies make two requests "the same"). - An origin shield (a middle cache tier) keeps many edges from all hitting your origin on a miss.
- Pull CDNs fetch from the origin on the first request. Push CDNs have you upload content ahead of time, which suits large files you know will be popular.
Interview angle
When you add a cache, say three things: what the key is, how it gets invalidated or expires, and what happens on a miss or when the cache is down. The last one is the one candidates skip.
For AI engineers¶
For AI engineers
An embedding cache avoids recomputing a vector for the same input, while a prompt/response cache avoids repeating an inference call. An exact-match cache reuses a result only when its key matches; a semantic cache may reuse a result for a different but similar request. That broader match can return an answer that is plausible yet wrong for the new request, so evaluate its error rate against your task before using it.
Your cache key is part of the model's behavior. Include the model version, prompt or template version, and generation parameters that affect the result, as well as the normalized input. Otherwise a deployment can silently serve an answer made by an older model or prompt. If a response depends on identity, permissions, or private data, keep those outputs isolated by user and authorization context, or do not cache them. A shared key based only on prompt text can leak one user's answer to another.
Feature caches have the same freshness problem as database caches: a training or serving pipeline can read yesterday's value after the source changes. Model-artifact caches on local disk speed up repeated starts, but need a size limit and a versioned path so an old file is not mistaken for the new model. For a demo app, a CDN can cache static JavaScript and images; give changed assets new names or invalidate them when you deploy. In every case, track hit ratio and misses alongside latency, because a seemingly healthy cache can still send too much work to the expensive tier.
Common mistakes¶
- No capacity limit: a process cache can keep growing until the worker runs out of memory. Set a maximum size and choose an eviction policy such as LRU.
- Incomplete keys: omitting a model version, generation parameter, or user scope can return an answer produced under different rules or expose another user's data. Define the key from every input that changes the answer.
- Caching every failure: a transient timeout or server error should not become a long-lived cached result. Cache a genuine "not found" briefly only when that absence is safe to reuse.
- Ignoring simultaneous misses: when a popular key expires, many requests can all call the slow loader. Coalesce requests for the same key and consider jittered TTLs across related keys.
- Using a cache as the only copy: eviction, expiration, or process restart can erase entries. Keep durable data in its source of truth and make a miss able to recover it.
- No hit-rate metric: a cache can respond correctly while most reads bypass it. Measure hits, misses, and the load placed on the source, especially after a deploy.
Check yourself¶
A product page is read 1,000× more than it is written, and being a few seconds stale is acceptable. Which pattern and invalidation approach would you choose?
Cache-aside with a short TTL (a few seconds to a minute), optionally plus explicit invalidation when the product is edited. Reads are served from the cache and the database sees mostly writes plus occasional misses.
Your 99% hit ratio drops to 90% after a deploy. The cache still works. What changed for the database?
Misses went from 1% to 10%, so database read traffic rose about 10×, even though hit ratio only "fell 9 points". This is why small hit-ratio drops can take a database down. Look for changed key formats, shorter TTLs, or a cold cache after the restart.
A viral post's cached entry expires and the database spikes. What happened and how do you stop it?
A cache stampede: many concurrent requests missed the same expired key. Use request coalescing, refresh before expiry, and add jitter to TTLs.
Lab¶
Build a small in-process cache toolkit in code/caching-cdn/. Start with bounded LRU eviction and hit/miss counts, then add expiration using an injected clock. Make cache-aside callers share one in-flight load for the same key. Finish with TTL jitter and the hit-ratio latency calculation from this lesson. Run: cd code/caching-cdn && PYTHONPATH=starter python -m pytest tests -q
Real systems that use this¶
The Atlas cases linked below show these ideas at real scale: Netflix's Open Connect cache appliances serving video close to users, Shopify's edge tier absorbing flash sales, a fraud-detection system using Redis in the request path, and CloudFront in front of a multi-region API.
Go deeper¶
- Interactive: Designed to Scale – caching, CDN
- Your handbook: Software Engineering Handbook, ch. 9 "Caching và CDN"
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.

Netflix Open Connect: luồng một request phát video (6 bước)

Netflix Open Connect: hai mô hình triển khai OCA tại IX site

Shopify: edge tier Nginx + Lua (OpenResty) chịu flash sale

Phát Hiện Gian Lận Thời Gian Thực với Redis Enterprise Cloud
