CDN caching
How to use Cache-Control, validators, cache keys and purging so that a CDN serves as much as possible without ever serving the wrong thing to the wrong person.
The problem
A news site runs from one region. An article goes viral and one URL receives 30,000 requests a second. Every response is the same 80 KB of HTML, which is about 19 Gbit/s of identical bytes. The origin’s twenty servers cannot render or even transmit that, and readers on other continents wait hundreds of milliseconds on each round trip regardless.
A CDN should fix both problems, since its edge servers sit close to readers and can each keep a copy. The site already has one, but it only caches images, because some CDNs do not cache HTML by default. So the team adds a “cache everything” rule. Load drops. An hour later a reader reports seeing a stranger’s name in the page header, because a logged-in page was stored and served to everyone.
The CDN was not at fault in either case. HTTP caching is a contract, and the origin writes it in response headers: who may store this, for how long, and what distinguishes one response from another. With the headers missing or wrong, a cache either does nothing useful or does something harmful. For how CDNs route and place content, see CDNs. This lesson is about the contract.
Freshness: Cache-Control
A cached response is fresh for a period and stale after it. The Cache-Control response header sets that period and the rules around it. The current standard is RFC 9111.
| Directive | Meaning |
|---|---|
max-age=N |
Fresh for N seconds in any cache |
s-maxage=N |
Overrides max-age in shared caches (CDNs, proxies) |
no-cache |
May be stored, but must be revalidated before every reuse |
no-store |
Must not be stored anywhere |
private |
Only the user’s own browser may store it |
public |
Any cache may store it, even where the default would be not to |
immutable |
Will not change while fresh, so do not revalidate on reload |
stale-while-revalidate=N |
May be served stale for N seconds while a refresh runs |
stale-if-error=N |
May be served stale for N seconds if the origin is failing |
Two points trip people up. no-cache does not mean “do not cache”. That is no-store. And a response with no freshness information is not uncacheable: caches may apply a heuristic, commonly 10% of the time since Last-Modified. Always send an explicit header.
Validation: ETag and conditional requests
A stale copy is not useless. If the origin attached a validator, the cache can ask whether its copy is still good.
- The origin sends
ETag: "v7", an opaque version identifier. Later the cache sendsIf-None-Match: "v7". - If nothing changed, the origin replies
304 Not Modifiedwith no body, and the cache marks its copy fresh again. Last-ModifiedandIf-Modified-Sincework the same way with a timestamp, at one-second resolution.
Validation saves bandwidth, not the round trip, and it saves origin work only if computing the validator is cheaper than building the response. Derive ETags from content or a version number, so that every origin server produces the same one.
Step 1 of 9
A browser asks for a product page. The request goes to the nearest CDN edge. The edge has no copy, so this is a miss, and the edge forwards the request to the origin.
Read the steps as text
- A browser asks for a product page. The request goes to the nearest CDN edge. The edge has no copy, so this is a miss, and the edge forwards the request to the origin.
- The origin answers with the page and three instructions. Browsers may keep it for 60 seconds, shared caches may keep it for 300 seconds, and its version tag is v7. The edge stores a copy and passes the response on.
- A minute later another visitor in the same region asks for the page. The edge answers from its copy. The origin does not see this request at all.
- The first visitor follows a link back to the page within 60 seconds. Their browser still holds a fresh copy and uses it without sending anything over the network.
- After 300 seconds the copy at the edge is stale. The edge does not throw it away. On the next request it asks the origin a cheaper question, which is whether version v7 has changed.
- Nothing has changed, so the origin replies 304 Not Modified with no body. The edge marks its copy fresh for another 300 seconds and serves it.
- Then the price changes. Waiting up to 300 seconds is too long, so the origin application tells the CDN to purge everything tagged product-7. The edge drops its copy.
- The next request misses, and the edge fetches the new page with a new version tag. A purge cannot reach copies that are already inside browsers, which is why the browser lifetime was kept short.
- Three tools work together. A time to live sets how stale a copy may get by default, validation makes refreshing an unchanged copy cheap, and purging removes a changed copy at once.
The cache key and Vary
A cache stores responses under a cache key, typically the host, path and query string. Two requests with the same key get the same stored response. Vary extends this: Vary: Accept-Encoding tells a cache to keep separate variants per value of that request header.
Keys go wrong in two directions.
Too broad, and users get the wrong content. The response depends on something that is not in the key: a language header, a cookie, the visitor’s country. One variant is stored and served to everyone.
Too narrow, and the hit ratio collapses. The key includes things that do not change the response. Tracking parameters such as utm_source, parameters in a different order, or Vary: User-Agent with its thousands of values each create a separate copy. Vary: Cookie gives every user their own.
The rule is that everything that changes the response goes in the key, and nothing else does. In practice that means normalising at the edge: strip tracking parameters, sort the rest, and reduce high-cardinality inputs to a few buckets, such as mobile or desktop.
Fingerprinted assets
For static files, avoid invalidation altogether. Put a hash of the content in the file name, such as app.3f9a1c.js, and serve it with
Cache-Control: public, max-age=31536000, immutable
The content at that URL can never change, so every cache may keep it for a year. A deploy produces new file names, and the HTML that references them is served with no-cache or a short lifetime. Keep the previous build’s files available for a while, because pages loaded before the deploy still ask for them. This is the versioned key idea applied to HTTP.
Purging and surrogate keys
HTML pages and API URLs cannot be renamed on every change. For these, give the CDN a long lifetime and purge when the content changes.
- By URL removes one object.
- By surrogate key (also called a cache tag) removes a group. The origin labels each response with the things it was built from, for example
Surrogate-Key: product-7 category-12on Fastly or aCache-Tagheader on Cloudflare. When product 7 changes, one call purges every page that carried that tag. - Purge everything empties the cache and sends full traffic to the origin, so treat it as a last resort. Cache stampede and thundering herd explains why.
A purge spreads across edge locations asynchronously. It is fast on modern CDNs, but it is not instant, and the delay varies by provider.
One asymmetry shapes the whole design: you can purge the CDN, but you cannot purge browsers. So for URLs that do not change, keep the browser lifetime short and the CDN lifetime long, for example max-age=60, s-maxage=86400. Headers aimed only at the CDN, such as CDN-Cache-Control (RFC 9213) or Surrogate-Control, make the split explicit.
Personalised and API responses
The incident in the opening is the main risk of CDN caching. Some rules keep you safe.
- The origin decides, explicitly. Any response that depends on who is asking carries
Cache-Control: privateorno-store. Do not rely on CDN rules that guess from the URL. An attack known as web cache deception requests a private page under a path that looks static, such as/account/x.css, and relies on the CDN caching by file extension. - Know the default for credentials. By the standard, a shared cache must not store the response to a request with an
Authorizationheader unless the response explicitly allows it, for example withpublicors-maxage. - Split the page. Cache the shell that is the same for everyone and fetch the personal fragment (name, basket count) with a separate, uncached request.
- Segment instead of personalising. If the page differs by country or by logged-in state, add that small set of values to the key. Never put a user id or session token in a cache key.
Public GET API responses are good candidates for short lifetimes. At 1,000 requests a second for one URL, s-maxage=10 means each edge location asks the origin about once every ten seconds. Add stale-while-revalidate so that the refresh happens in the background, and stale-if-error so that a brief origin outage is invisible.
When to use it and when not to
Choose CDN caching for static assets, public pages and public read APIs with repeated requests. Do not choose it for per-user data, for values that must be current at the moment of use such as stock at checkout, or for responses to non-idempotent methods such as POST. Expect little from long-tail URLs that are each requested rarely, since every edge location warms its own cache and most requests will miss.
In the interview
Bring CDN caching up when the design serves static files, media or public pages to users far from the origin. State the headers, not only “put a CDN in front”. For example: fingerprinted assets with a one-year max-age and immutable. HTML with a short max-age and a longer s-maxage, purged by surrogate key on publish. Anything per-user marked private.
Then cover the two risks without being asked. Say what is in the cache key and why a logged-in response can never be served to someone else. And say how a change reaches users: new URL, purge, or waiting out a TTL. An interviewer who hears both knows you have operated one.
Key takeaways
- HTTP caching is a contract set by the origin through response headers. The CDN and the browser each follow it separately.
- max-age applies to every cache, s-maxage overrides it for shared caches, no-cache means "store but revalidate" and no-store means "do not keep".
- A stale copy with an ETag can be revalidated with a conditional request, and a 304 response refreshes it without sending the body again.
- Everything that changes the response must be in the cache key or in Vary, and nothing else should be, or you get either wrong content or a collapsed hit ratio.
- Fingerprinted asset URLs can be cached for a year and never purged. HTML and API URLs need short browser lifetimes plus purging at the CDN.
- You can purge a CDN but not a browser, so keep browser lifetimes short for anything whose URL does not change.
- Per-user responses are marked private or no-store by the origin. Cache the shared shell and fetch the personal part separately.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
max-age versus s-maxage.
max-age sets the freshness lifetime for all caches. s-maxage overrides it for shared caches (CDNs and proxies) only, so browsers and the CDN can have different lifetimes.
no-cache versus no-store.
no-cache means the response may be stored but must be revalidated with the origin before each reuse. no-store means it must not be stored at all.
How does revalidation with an ETag work?
The cache sends If-None-Match with the stored ETag. If the resource is unchanged the origin replies 304 Not Modified with no body, and the cache reuses its copy.
What is the role of the Vary header?
It lists request headers that change the response. A cache stores a separate variant per distinct value of those headers, in addition to its normal cache key.
What caching headers suit a fingerprinted asset such as app.3f9a1c.js?
Cache-Control: public, max-age=31536000, immutable. The content at that URL never changes, so it can be kept for a year and never needs purging.
How do you cache a page that is mostly shared but shows the user's name?
Cache the shared shell at the CDN and load the personal part with a separate request marked private or no-store. Or key on a small segment, never on the user id.