HTTP Caching Explained: Cache-Control, ETags, and stale-while-revalidate
How browsers and CDNs decide whether to reuse a response, revalidate it or fetch it again, with a runnable Node. js example and production-safe Cache-Control defaults.

HTTP caching is one of the cheapest performance wins available to a web application, and one of the easiest to get subtly wrong. A well-chosen Cache-Control header can remove most repeat downloads, cut origin load and make return visits feel instant. A badly chosen one can pin users to an old JavaScript bundle for a year, or let a CDN hand one person's account page to somebody else.
This explainer walks through how caches actually decide what to do, based on the current HTTP caching standard (RFC 9111), the conditional-request rules in RFC 9110, and the stale-while-revalidate extensions in RFC 5861. It ends with a small runnable Node. js server and a set of defaults that hold up in production.
Two questions every cache asks
Whether it is a browser, a corporate proxy or a CDN edge, a cache handles a stored response by answering two separate questions. First: is this stored copy still fresh? If it is, the cache can serve it without contacting the origin at all. Second: if it is stale, can it be validated cheaply? Instead of downloading the whole body again, the cache can ask the origin whether its copy is still current and receive a tiny 304 Not Modified reply.
Keeping these two ideas apart explains almost every Cache-Control directive. Some directives control freshness (how long a copy may be reused without asking), some control validation (when asking is mandatory), and some control storage (whether the response may be kept at all, and by which kind of cache).
Freshness: how long a copy can be reused
RFC 9111 computes a response's freshness lifetime from the first rule that applies: a shared cache uses s-maxage if present; otherwise any cache uses max-age; otherwise it uses the Expires header minus the Date header. If none of these exist, a cache is allowed to invent a heuristic lifetime, and the specification suggests a fraction of the time since Last-Modified, with 10% given as a typical value.
That last rule surprises people. A response with no Cache-Control header at all is not "uncached". A file last modified 30 days ago could be treated as fresh for roughly three days by a cache using that 10% heuristic. The practical lesson is to send an explicit Cache-Control header on every response, so caches never have to guess.
A response is fresh while its current age is lower than its freshness lifetime. Age is not simply the time since the browser received it: a shared cache adds an Age header when it serves a stored copy, and downstream caches add that value plus network delay to their own calculation. A CDN that has held a response for 500 seconds and serves it with Age: 500 under max-age=600 leaves the browser only about 100 seconds of freshness, not 600.
Validation: ETag, Last-Modified and 304
When a stored response goes stale, it is not thrown away. If it carried a validator, the cache sends a conditional request. With an ETag, the cache sends If-None-Match containing the stored tag; with Last-Modified, it sends If-Modified-Since containing the stored date. If the resource has not changed, the server replies 304 Not Modified with no body, and the cache refreshes its copy's freshness from the new headers.
A few rules from RFC 9110 matter when implementing this yourself:
- If-None-Match takes priority. A server must ignore If-Modified-Since when the request also contains If-None-Match.
- If-None-Match uses weak comparison, so a weak tag such as W/"v7" matches the strong tag "v7". The header can also hold a comma-separated list of tags, or a single asterisk.
- A 304 response carries no body but should include the headers a 200 would have sent, such as Cache-Control, ETag, Expires and Vary, because the cache uses them to update its stored copy.
- Last-Modified has one-second resolution, so a resource that changes twice within the same second cannot be distinguished by date alone. A content hash or revision number as an ETag avoids that limitation.
MDN recommends sending both ETag and Last-Modified on cacheable responses: the ETag gives precise validation, while Last-Modified is still used by crawlers and other tooling.
The directives, grouped by what they control
Storage: no-store, private and public
no-store tells every cache not to keep any part of the request or response. It is the right choice for genuinely sensitive data, but it is often overused: it also prevents cheap revalidation, and MDN notes it can cost you back/forward cache benefits in browsers. private allows the browser to store the response but forbids shared caches such as CDNs and proxies from storing it. public explicitly allows storage even in cases that would otherwise be prohibited, most notably responses to requests that carry an Authorization header.
A common misconception is that cookies make a response private automatically. They do not. Personalised responses need Cache-Control: private set explicitly, and MDN advises against using Vary: Cookie as a substitute.
Validation: no-cache and must-revalidate
Despite its name, no-cache does not mean "do not cache". It means a stored copy must not be reused without first being validated with the origin. Combined with an ETag, that gives you always-current content at the cost of a small round trip, while still avoiding the full download when nothing changed. must-revalidate is different: the copy may be served freely while fresh, but once stale it must be validated, and a cache that cannot reach the origin must return an error (RFC 9111 suggests 504) rather than serve the stale copy.
Freshness tuning: s-maxage, immutable and the stale extensions
- s-maxage sets a separate lifetime for shared caches, overriding max-age and Expires there. It lets a CDN hold a page for minutes while browsers keep a much shorter lifetime.
- immutable (RFC 8246) promises the resource will not change while fresh, so clients should not send conditional requests for it, even on a normal reload. A force reload still overrides it, and clients should ignore it for content not served over HTTPS.
- stale-while-revalidate=N allows a cache to serve a stale copy for up to N seconds after it expires while it revalidates in the background, so the user never waits for the round trip.
- stale-if-error=N allows a stale copy to be served for up to N extra seconds when the origin returns a 500, 502, 503 or 504 error, turning an outage into slightly old content instead of an error page.
A worked timeline
RFC 5861 illustrates the stale extensions with headers like the following. Consider a response sent with this header:
Cache-Control: max-age=600, stale-while-revalidate=30, stale-if-error=1200- From 0 to 600 seconds of age, the response is fresh and is served straight from the cache.
- From 600 to 630 seconds, it is stale but inside the stale-while-revalidate window. A request in this window gets the cached copy immediately, and the cache revalidates in the background.
- After 630 seconds, if nothing has refreshed it, the next request waits for revalidation as normal.
- If revalidation fails with a server error, stale-if-error lets the cache keep serving the stored copy until it is 1,800 seconds old (600 fresh plus 1,200). Beyond that, the error is passed through to the client.
One subtlety from the RFC: background revalidation is only triggered by a request that arrives inside the window. On a low-traffic URL, the window can pass without any request, and the next visitor simply pays the normal revalidation cost.
Vary: what goes into the cache key
By default, a cache keys a stored response mainly on its URL. Vary adds request headers to that key: with Vary: Accept-Language, a stored English response is not reused for a request asking for French without validation. RFC 9111 also defines Vary: * as a value that never matches, which effectively disables reuse. Choose Vary headers with low cardinality. MDN specifically warns against Vary: User-Agent, because the number of distinct user-agent strings is large enough to make cache hits rare.
A runnable example: hashed assets plus validated HTML
The most robust pattern for a typical site combines two policies. Static assets get a content hash in their file name and are cached for a year with immutable; a new build simply references new URLs. HTML, whose URL cannot change, is served with no-cache and an ETag, so every navigation checks for a new version but usually receives a tiny 304. The server below implements both with only Node. js built-ins:
// server.mjs -- run with: node server.mjs, then use the curl commands below
import http from "node:http";
import crypto from "node:crypto";
const js = 'console.log("app loaded");';
const html = `<!doctype html>
<html>
<head><script src="/app.3f9a1c.js"></script></head>
<body><h1>Hello, cache</h1></body>
</html>`;
// A strong ETag derived from the exact bytes we send
const etagOf = (body) =>
`"${crypto.createHash("sha256").update(body).digest("base64url").slice(0, 16)}"`;
const htmlEtag = etagOf(html);
// If-None-Match may hold a list of tags, "*", or weak W/"..." tags;
// RFC 9110 says to compare them with the weak comparison function.
function matches(header, etag) {
if (!header) return false;
if (header.trim() === "*") return true;
const bare = (tag) => tag.trim().replace(/^W\//, "");
return header.split(",").some((tag) => bare(tag) === bare(etag));
}
http.createServer((req, res) => {
if (req.url === "/app.3f9a1c.js") {
// Content-hashed URL: a new build ships a new URL, so cache it for a year
res.writeHead(200, {
"Content-Type": "text/javascript",
"Cache-Control": "max-age=31536000, immutable",
});
return res.end(js);
}
if (req.url === "/") {
const headers = {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-cache",
ETag: htmlEtag,
};
if (matches(req.headers["if-none-match"], htmlEtag)) {
res.writeHead(304, headers); // same headers, no body
return res.end();
}
res.writeHead(200, headers);
return res.end(html);
}
res.writeHead(404, { "Cache-Control": "no-store" });
res.end("not found");
}).listen(8080, () => console.log("listening on http://localhost:8080"));With the server running, these commands show the full response, a successful revalidation that returns 304, and the long-lived policy on the hashed asset:
# 1. First request: full 200 response with an ETag
curl -si http://localhost:8080/ | head -n 5
# 2. Revalidate with the ETag we were given: expect 304 and no body
ETAG=$(curl -sI http://localhost:8080/ | grep -i '^etag:' | cut -d' ' -f2 | tr -d '\r')
curl -s -o /dev/null -w '%{http_code}\n' -H "If-None-Match: $ETAG" http://localhost:8080/
# 3. The hashed asset is cacheable for a year
curl -sI http://localhost:8080/app.3f9a1c.js | grep -i '^cache-control'A production framework or CDN will usually generate ETags and evaluate conditional requests for you, but the moving parts are the same: a validator derived from the content, a match check that respects lists and weak tags, and a 304 that repeats the caching headers.
Pitfalls that show up in production
- Long max-age on unversioned URLs. If /app. js is cached for a year and its contents change, browsers that already hold it keep running the old code. Only use long lifetimes on URLs that change when content changes.
- Kitchen-sink headers. Strings like no-store, no-cache, max-age=0, must-revalidate, proxy-revalidate were workarounds for old proxies. MDN suggests no-cache, private when you need to be conservative with intermediaries.
- Assuming you can purge. A server cannot delete copies held in browsers or third-party proxies. If content must be withdrawn quickly, keep lifetimes short or route it through a managed cache, such as a CDN or service worker, that supports purging.
- Shared caching of personalised pages. Anything that differs per user needs private, or must be excluded from the CDN, regardless of how short its max-age is. MDN also notes that shared caches may collapse simultaneous identical requests, which is another reason to mark per-user responses private.
- Forgetting history navigation. no-cache does not guarantee revalidation when a user presses Back, because the browser may restore a page snapshot from its back/forward cache.
A sensible set of defaults
- Send an explicit Cache-Control header on every response so caches never fall back to heuristics.
- Use max-age=31536000, immutable for content-hashed static assets.
- Use no-cache with an ETag for HTML and other fixed URLs that must always be current, and add private when the content is personalised.
- Use s-maxage to give your CDN a longer lifetime than browsers when you control purging at the CDN.
- Add stale-while-revalidate and stale-if-error where serving slightly old content is acceptable, such as listings, feeds and public API responses.
- Reserve no-store for responses that genuinely must never be written to disk.
Caching works best when it is designed rather than accumulated. Decide, per type of response, how long a copy may be reused without asking, how it gets revalidated, and which caches are allowed to hold it. Those three decisions map directly onto the headers above.
Enjoyed this?
Get the next deep dive in your inbox. No spam — just the stories worth reading.
Subscribe to the newsletter