HTTP caching headers
Cache-Control
The origin tells every cache what to do with the Cache-Control response header:
| Directive | Meaning |
|---|---|
max-age=600 |
Fresh for 600 seconds in any cache |
s-maxage=3600 |
Overrides max-age for shared caches (CDNs, proxies) only |
public |
Any cache may store it, even for authenticated requests |
private |
Only the user's browser may store it; CDNs must not |
no-cache |
May be stored, but must be revalidated before every use |
no-store |
Must not be stored anywhere (sensitive data) |
immutable |
Will never change during its lifetime; don't even revalidate on reload |
stale-while-revalidate=60 |
Serve the stale copy for up to 60 s while fetching a fresh one in the background |
stale-if-error=86400 |
Serve a stale copy for up to a day if the origin errors |
no-cache does not mean "don't cache" — that is no-store. Mixing the two up is a classic interview trap.
Typical settings:
# fingerprinted assets: app.3f9a2c.js
Cache-Control: public, max-age=31536000, immutable
# HTML pages
Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=300
# account pages and API responses with user data
Cache-Control: private, no-store
Validation and 304 Not Modified
When a cached copy goes stale, the cache can ask the origin whether it changed instead of downloading it again:
- The origin sends an
ETag(a version identifier, often a hash) orLast-Modifieddate with the response. - Later the cache sends
If-None-Match: "<etag>"orIf-Modified-Since: <date>. - If nothing changed, the origin answers
304 Not Modifiedwith no body, and the cache marks its copy fresh again.
Revalidation saves bandwidth but still costs a round trip. Behind a load balancer, make sure every instance generates the same ETag for the same content (Nginx bases it on file modification time and size, which can differ between servers and builds).
Cache keys and Vary
A cache stores each response under a cache key, by default the method, host and path (and on CDNs, whatever query strings, headers and cookies you configure). Two requests with the same key get the same response.
- Too little in the key serves the wrong response: language versions mixed up, or one user's page shown to another.
- Too much in the key destroys the hit ratio: including every cookie or a tracking query string (
?utm_source=…) makes almost every request unique. - The
Varyresponse header tells caches which request headers change the response, for exampleVary: Accept-Encodingfor gzip versus Brotli.Vary: CookieorVary: User-Agenteffectively disables shared caching.