Most caching bugs come from mixing up two questions: how long a cache may reuse a response, and how it cheaply checks once that time is up. Here is how Cache-Control, ETag, Vary and 304 Not Modified actually fit together.
Most HTTP caching bugs come from treating two separate questions as one: how long a cache may reuse a response without asking anyone (freshness), and how it checks cheaply once that time is up (validation). Cache-Control answers the first, ETag and Last-Modified answer the second, and almost every "why is my user seeing stale data" or "why does every page load hit the origin" ticket is one of those two answered wrong.
The single most common symptom: someone sets Cache-Control: no-cache expecting nothing to be stored, and is surprised to find the response sitting in a browser or CDN cache. no-cache never meant "don't cache". It means "store it, but revalidate before every reuse". The directive that means "don't store" is no-store. Once you see freshness and validation as two separate dials, that naming stops being a trap.
When a browser, CDN or reverse proxy holds a stored response and a new request comes in for the same URL, RFC 9111 has it work through roughly this:
Cache-Control: max-age (or s-maxage for shared caches), falling back to Expires, falling back to a heuristic. If the response's age is under that lifetime, serve it. No network, no origin.ETag or Last-Modified), send a conditional request. If the origin answers 304 Not Modified, the cache refreshes its metadata and serves the body it already had.Step 1 saves a round trip. Step 2 saves bandwidth but still costs a round trip. Good caching policy is mostly deciding, per kind of resource, how much of each you want.
Here are the directives worth knowing, and the one-line meaning that usually gets lost:
| Directive | What it actually means | Typical use |
|---|---|---|
max-age=N | Fresh for N seconds from when the response was generated | Almost everything cacheable |
s-maxage=N | Overrides max-age for shared caches (CDNs, proxies) only | HTML that a CDN can hold longer than browsers |
no-cache | May store, must revalidate with the origin before each reuse | HTML shells, API responses you want to be always current |
no-store | Must not store at all | Banking pages, one-time tokens, anything sensitive |
private | Only the end user's browser may store it, not shared caches | Per-user responses |
public | Shared caches may store it even when they otherwise would not (for example, a response to a request with Authorization) | Rarely needed; max-age alone already allows shared caching |
must-revalidate | Once stale, never serve it without a successful revalidation | Data where stale is worse than an error |
immutable | The body will never change while fresh, so skip revalidation even on reload | Fingerprinted static assets |
stale-while-revalidate=N | For N seconds after going stale, serve stale and revalidate in the background | Content where slightly old is fine and latency matters |
stale-if-error=N | For N seconds after going stale, serve stale if the origin errors | Resilience during origin outages |
immutable is defined in RFC 8246, and the two stale-* extensions come from RFC 5861. Browser support for the stale-* pair is uneven, but most major CDNs honor them, which is where they earn their keep.
If a response has no Cache-Control freshness directive and no Expires, caches are still allowed to guess. RFC 9111 suggests a common approach: take a fraction (10% is the typical figure) of the time since Last-Modified. A file last modified 30 days ago can be treated as fresh for about three days with no instruction from you at all.
This is how teams end up with a JavaScript bundle that "won't update" despite never configuring caching. The fix is not to avoid caching, it is to always send an explicit Cache-Control so nothing is left to heuristics.
max-age beats ExpiresExpires is an absolute date, which means it depends on clocks agreeing. When both are present, max-age wins. There is no reason to send Expires in new code except to satisfy ancient HTTP/1.0 caches, and the same goes for Pragma: no-cache.
When a stored response goes stale, validation lets the cache ask "has this changed?" instead of re-downloading it. There are two validators, defined in RFC 9110:
Last-Modified is a timestamp with one-second resolution. The cache sends it back as If-Modified-Since. It is cheap but coarse: two writes inside the same second look identical, and a regenerated-but-identical file looks changed.ETag is an opaque string the server chooses, usually a content hash or a version number. The cache sends it back as If-None-Match. If it still matches, the server answers 304 Not Modified with no body.When a request carries both, the server must evaluate If-None-Match and ignore If-Modified-Since. ETags are the more precise tool; Last-Modified is the fallback.
The flow below shows both halves working together for a CDN in front of an origin. The first request is served from a fresh cache entry; later, after the entry goes stale, the CDN revalidates and the origin sends headers only.
An ETag is either strong ("v42") or weak (W/"v42"). A strong ETag promises byte-for-byte identity; a weak one promises only that the two representations are semantically equivalent. For If-None-Match, servers use weak comparison, so W/"v42" and "v42" match. Strong comparison matters for byte-range requests and for If-Match on writes.
This distinction bites in practice. nginx, for example, downgrades a strong ETag to weak when it gzips a response on the fly, because the compressed bytes differ from the original. That is correct behavior, but it surprises people who compare ETags with string equality in their own code. Strip the W/ prefix before comparing for cache validation.
Here is a minimal Node handler for a JSON endpoint. It hashes the serialized body into an ETag, compares it against If-None-Match, and returns a bodyless 304 on a match:
import { createHash } from 'node:crypto'
function sendJson(req, res, data) {
const body = JSON.stringify(data)
const etag = '"' + createHash('sha256').update(body).digest('base64url').slice(0, 22) + '"'
res.setHeader('ETag', etag)
res.setHeader('Cache-Control', 'private, no-cache')
res.setHeader('Vary', 'Authorization')
const inm = req.headers['if-none-match']
if (inm) {
const tags = inm.split(',').map((t) => t.trim().replace(/^W\//, ''))
if (tags.includes('*') || tags.includes(etag)) {
res.statusCode = 304
return res.end()
}
}
res.setHeader('Content-Type', 'application/json')
res.end(body)
}
Note what this does and does not save. The server still runs the query and serializes the result to compute the hash, so origin CPU is unchanged; the saving is bandwidth and client parse time. If you want to skip the work too, derive the ETag from something cheaper than the body, such as a row's updated_at plus its ID, or a version counter you bump on write. If you want a quick content-hash ETag to paste into a test response, the HTTP header builder generates strong or weak values and explains Cache-Control and Vary combinations alongside.
By default a cache keys stored responses on method and URL. Vary tells it to add request headers to that key. Vary: Accept-Encoding means gzip and Brotli responses are stored separately, which is what you want. Vary: Authorization means each user's response is stored under its own key.
Two failure modes come up repeatedly:
Vary. An endpoint returns different content by Accept-Language or by cookie but does not say so. The first user's response is cached and served to everyone. This is how one customer sees another's dashboard through a CDN.Vary. Vary: User-Agent or Vary: Cookie on a public page fragments the cache into thousands of near-identical entries, and the hit rate collapses. Many CDNs treat these as effectively uncacheable.For anything per-user, Cache-Control: private is the more robust guard: it keeps the response out of shared caches entirely, rather than trusting every cache in the chain to key correctly.
Most applications need only a handful of policies:
| Resource | Cache-Control | Validator | Why |
|---|---|---|---|
Fingerprinted assets (app.3f9a1c.js) | public, max-age=31536000, immutable | Optional | A new build gets a new URL, so the old one can live forever |
| HTML pages and app shells | no-cache | ETag | Always check, but a 304 makes the check cheap |
| Public API reads (catalog, docs) | max-age=60, stale-while-revalidate=300 | ETag | Short freshness, fast responses while refreshing |
| Per-user API reads | private, no-cache plus Vary: Authorization | ETag | Never in a shared cache, still revalidates cheaply |
| Secrets, tokens, payment pages | no-store | None | Nothing should be written to disk anywhere |
The first two rows work as a pair. Long-lived fingerprinted assets are only safe because the HTML that references them is revalidated on every load; get the HTML policy wrong and users are stuck on an old shell that points at old bundles.
This whole toolkit is one of the quieter arguments in the REST vs RPC tradeoff: GET requests to stable URLs inherit every cache between client and server for free, while RPC-style POST endpoints get none of it unless you build your own.
ETags are not only for reads. Sending If-Match: "v42" on a PUT or PATCH tells the server to apply the change only if the resource is still at version "v42". If someone else wrote in between, the server answers 412 Precondition Failed instead of silently overwriting their change.
This is optimistic concurrency control built into HTTP, and it pairs naturally with partial updates; it is the piece most JSON Patch and JSON Merge Patch implementations forget. Here strong comparison applies, so weak ETags cannot satisfy If-Match.
no-cache used where no-store was meant, or the reverse: no-store on HTML that could have been revalidated cheaply with a 304.Cache-Control leaves freshness to heuristics. Say what you mean explicitly.404 or even 5xx responses for a default period. Set explicit, short policies on error paths, and use stale-if-error so an origin outage serves old content rather than cached errors. During those outages, clients retrying against a struggling origin is the other half of the problem, covered in retries with exponential backoff, jitter and Retry-After.Cache-Control from the origin for some content types, or apply their own defaults, until configured otherwise. Check the actual response headers (Age, Cache-Status, or vendor-specific hit/miss headers) at the edge, not just what the origin sends.For every resource, answer two questions separately. How long may a cache reuse this without asking (max-age, s-maxage, immutable, or no-cache for "zero")? And once it is stale, how does it check cheaply (ETag, ideally derived from a version rather than the full body)? Add private or Vary wherever the response depends on who is asking, reserve no-store for things that must never touch disk, and verify the headers at the edge rather than trusting what you configured. Most caching bugs disappear once each response answers both questions explicitly.
Free, in your browser, no sign-up.
One email when a new post goes up. No other mail; unsubscribe in one click.
We store your email only to send new posts. See the privacy policy.