HTTP Caching, End to EndPhase 1 of 22 min read

Cache-Control, Decoded

max-age, no-cache vs no-store, private vs public, and s-maxage for CDNs.


The fastest request is the one that never leaves the browser. Cache-Control is the response header that tells every cache along the way what it may do with a response.

Freshness: max-age

Cache-Control: max-age=3600

The response is fresh for 3600 seconds after it was generated. While fresh, a cache can reuse it without contacting the server at all. Once it goes stale, the cache must check with the server before reusing it (more on that in the next phase).

no-cache is not no-store

These two get mixed up constantly.

  • no-store: do not store this response anywhere. Use it for genuinely sensitive data, like a page showing a bank balance.
  • no-cache: you may store it, but you must revalidate with the server before every reuse. The cache keeps the bytes, and the server can answer with a tiny "still good" response.

So no-cache is often exactly what you want for HTML: always up to date, but cheap when nothing changed.

Who may cache: private and public

Between the user and your server there can be shared caches: CDNs and proxies that serve many users.

  • private: only the user's own browser may store it. Use it for responses that contain per-user data.
  • public: shared caches may store it too, even in some cases where they otherwise wouldn't (like responses to requests with an Authorization header).

s-maxage: a separate clock for CDNs

Cache-Control: public, max-age=60, s-maxage=86400

Browsers keep this for 60 seconds. Shared caches like a CDN use s-maxage instead and keep it for a day. This is a common pattern: a short browser lifetime so users see updates soon, and a long CDN lifetime that you clear by purging the CDN when you deploy.

Immutable assets

Build tools put a content hash in asset filenames (app.3f9a1c.js). The URL changes whenever the content changes, so the old URL can be cached essentially forever:

Cache-Control: public, max-age=31536000, immutable

Check your understanding

Quiz

4 questions. Score 70% or more to complete this phase.

Question 1

Question 1

What does `Cache-Control: no-cache` mean?

Question 2

Question 2

A response shows a user's private dashboard. Which directive keeps it out of CDNs?

Question 3

Question 3

`public, max-age=60, s-maxage=86400`: how long may a CDN treat it as fresh?

Question 4

Question 4

Why can a file like `app.3f9a1c.js` be cached for a year?

Results won't be saved unless you log in.