Fieldnotes
Back to the notebook
The web4 min read

Caching is a promise.

A cache is easy to add and surprisingly easy to misunderstand. Start with what is allowed to stay the same.

Caching begins with a small agreement: this response can be reused for a while. The useful question is not simply how long to keep it. It is what would happen if someone saw the old version.

A stylesheet with a content hash in its filename and a page showing account details make very different promises. Giving them the same policy makes a simple system harder to reason about.

Let the filename do some work

For a public asset, a filename such as site.8f2c1a.css can identify a particular version. When its contents change, the filename changes too. The old file can stay in a cache without preventing the new file from being requested.

That makes a long cache lifetime practical for versioned, public assets:

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

The important condition is that the URL really does change when the file changes. A long lifetime on a repeatedly overwritten site.css can leave readers looking at yesterday’s design.

Keep the entry point fresh

An HTML document is often the entry point that tells the browser which assets to request. It usually needs a shorter lifetime or revalidation before reuse. One deliberately conservative policy is:

Cache-Control: no-cache

The name is slightly misleading: a response may still be stored. Before reusing it, a cache must validate it with the server. An ETag or Last-Modified value can make that check inexpensive when nothing has changed.

Draw a boundary around private content

Personalized or sensitive responses deserve their own policy. private prevents storage by shared caches but still allows a browser cache. no-store tells caches not to store the response. Neither directive replaces authentication or access control.

Choose freshness according to the cost of being out of date.

Keep the first version understandable. Separate public assets, public documents, and private responses. Then inspect the actual response headers in a browser and check a second request. A policy is useful only when the server sends what you intended.