PerformanceServers

HTTP caching, from the headers up

Cache-Control, ETags and stale-while-revalidate: what each header promises, who honours it, and the three settings that cover most sites.

Alex Rivera

· 8 min read

Wooden shelves filled with rows of books

Two caches, one header

Every response can be stored twice on its way to the user: once in a shared cache (a CDN or a proxy) and once in the browser. Cache-Control speaks to both, and most caching bugs come from forgetting that the same header is read by two very different readers.

max-age tells the browser how long a copy stays fresh. s-maxage overrides it for shared caches only. private keeps a response out of shared caches entirely, which is what you want for anything that depends on a cookie.

Three settings that cover most sites

ts
const caching = {  // Fingerprinted assets: the URL changes when the file does.  asset: "public, max-age=31536000, immutable",  // HTML: always ask, but let the CDN answer quickly.  page: "public, max-age=0, s-maxage=60, stale-while-revalidate=600",  // Anything behind a login.  account: "private, no-store",};

The first line is safe only because the file name carries a hash of its contents. The second keeps pages fresh for users while the CDN serves a copy up to ten minutes old and refreshes it in the background.

Validation with ETags

When a copy goes stale, the cache doesn't have to download it again. It sends the ETag it has in If-None-Match, and the server answers 304 Not Modified with an empty body if nothing changed.

bash
curl -I https://example.com/feed.xml# etag: "5f2b-18c"curl -I -H 'If-None-Match: "5f2b-18c"' https://example.com/feed.xml# HTTP/2 304

A short checklist

  • Hash asset file names, then cache them for a year.
  • Send private with anything that reads a cookie.
  • Use stale-while-revalidate for pages, not max-age alone.
  • Check the headers your CDN actually sends, not the ones you set.

Keep reading