Part 4 of 8 · 2 min read
What to cache, and how to say so
Static and dynamic content, the Cache-Control header, and checking a copy with an ETag.
Think of a sign on a tin of food: "best before 12 March". The shop knows how long it may keep the tin on the shelf.
An origin tells caches how long a reply may be reused, using HTTP headers.
| Header | Meaning |
|---|---|
Cache-Control: max-age=86400 |
Any cache may reuse this reply for 86,400 seconds (1 day) |
Cache-Control: public |
Shared caches such as a CDN may store it |
Cache-Control: private |
Only the user's own browser may store it |
Cache-Control: no-store |
Do not keep it at all |
ETag: "a91f" |
A label for this exact version of the file |
Static and dynamic content
Static content is the same for every user until someone changes the file: images, scripts, style sheets, videos, downloads. Dynamic content is built per request or per user: a cart, a feed, a search result.
Example: the shop's logo is static. The page that says "Hello, Asha, you have 3 items" is dynamic.
Static content is the natural fit. The book says CDNs focus on static content. Caching whole dynamic pages is possible when the page depends only on the path, query string and a few headers, but it needs care. Pages that show one user's private data must never be shared.
A worked example of conditional requests. A file of 500 kilobytes has an ETag. After the TTL runs out, the edge does not have to download the file again.
- The edge asks the origin: "send the file only if it no longer matches ETag
a91f". - If the file has not changed, the origin answers
304 Not Modified, with no body. That is perhaps 200 bytes. - The edge keeps its copy and starts a new TTL.
So an expired copy costs 200 bytes instead of 500,000, which is 2,500 times less. A changed file gets a normal 200 with the new body.
Choosing a TTL is a trade-off, which the book states: not too long, or the content may be stale, and not too short, or the edge keeps reloading from the origin.
| File | Sensible rule |
|---|---|
| Image with a version in its name | public, max-age=31536000 (1 year) |
| Script or style sheet with a version in its name | One year |
| Home page HTML | Seconds to minutes, or no-cache with an ETag |
| User's account page | private or no-store |
| Video segments | Long, since each segment never changes |
Common mistake
Sending public on a reply that holds a user's private data. A shared cache may then show one user's page to another. Mark personal replies private or no-store.
Check yourself:
- What does a
304reply tell the cache, and why is it cheap? - Which header would you put on a page that shows a user's bank balance?