Caching
Caching is keeping a copy of something expensive so you do not have to recompute or refetch it. It is everywhere, and it is subtle.
A cache is a fast store of copies. Reading from it beats recomputing a result or crossing the network again. The idea is simple; getting it right — knowing when a copy is stale — is the famously hard part.
Where caching happens on the web
A single page load may be cached in several places at once:
- The browser caches files it already downloaded.
- A CDN caches copies close to users geographically.
- A reverse proxy caches responses in front of the app.
- The application caches query results (often in Redis).
- The database caches pages in memory.
Controlling the browser cache
Servers steer caching with HTTP headers:
Cache-Control: max-age=31536000, immutable # keep for a year
Cache-Control: no-cache # always revalidate first
Cache-Control: no-store # never cache at all
ETag: "a1b2c3" # a fingerprint of the content
With an ETag, the browser can ask “has it changed since a1b2c3?” and the server can answer 304 Not Modified — no body re-sent.
Cache invalidation
The hard problem: when the underlying thing changes, old copies must not linger. Common strategies:
- TTL — copies simply expire after a set time.
- Versioned URLs — include a content hash in the filename (
app.9f3a1.js). Change the content, change the name; the old URL is never requested again. This is why you can cache such files for a year safely. - Explicit purge — tell the CDN to drop a specific URL now.
The classic gotcha: “it works for me but not for you” is very often a stale cache somewhere in that stack — browser, CDN, or proxy — serving an old copy. A hard refresh or a versioned filename is the usual cure.