Notes from the studio

HTTP caching for people who have better things to do

Two questions, three headers and one rule that makes most caching decisions for you.

6 min readNesterenko Studio

Caching advice tends to arrive with a diagram of four boxes and arrows going both ways. In practice, a browser asks two questions about every response: am I allowed to store this? and for how long is it still fresh? Answer those and you have a caching policy.

The two questions

Storage. Cache-Control: no-store means never keep it. private means only the browser may. public means a shared cache — a CDN, a corporate proxy — may keep a copy too.

Freshness. max-age=600 says the response may be reused for ten minutes without asking the server. After that the cache has to check whether the thing changed.

Checking is where validators come in. An ETag or a Last-Modified date lets the cache ask "still the same?" and get back a 304 Not Modified — a response with no body, which is nearly free.

One rule that settles most cases

Name a file by its content and you can cache it forever. Name it by its meaning and you must revalidate.

A stylesheet called app.css can change at any time, so it needs a check. A stylesheet called app.657df69b.css — the hash of its contents — can never change without getting a new name, so nobody ever needs to ask:

# Fingerprinted assets: never ask again.
location /assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
}

HTML is the opposite case. It has a stable name and changing content, so the right policy is "always store, always check":

add_header Cache-Control "no-cache";
etag on;

A visitor gets a 304 on almost every page view: one round trip, a few hundred bytes, no re-download.

The two headers worth knowing beyond that

stale-while-revalidate lets a cache serve a slightly old copy while it fetches a fresh one in the background. It is the closest thing to a free lunch for APIs that change a few times an hour.

Cache-Control: public, max-age=60, stale-while-revalidate=600

Vary tells a shared cache which request headers change the response. Leave it out and a compressed version may be served to a browser that cannot read it; add too many and your hit rate collapses.

A checklist that fits on a postcard

  • Fingerprinted assets: public, max-age=31536000, immutable.
  • HTML: no-cache plus an ETag.
  • Anything with personal data: private, or no-store if it must not touch disk.
  • APIs that change slowly: a short max-age with stale-while-revalidate.
  • Look at the response headers in the browser's network panel once a quarter. Headers added by a framework update have a way of disagreeing with the ones you set.

That is the whole subject, for most websites. The rest is detail you can look up when a cache misbehaves — and it will.