HTTP caching explained: Cache-Control, ETags and why users see stale pages
Caching makes websites fast, and it's also behind countless "I deployed but users still see the old version" mysteries. HTTP headers control most of it.
Where caching happens
- The browser cache
- CDNs and proxies between users and your server
- Your own application caches (outside HTTP's control)
Cache-Control, the main header
max-age=3600: the response can be reused for an hour without asking the server.no-cache: store it, but check with the server before reusing.no-store: don't store it at all (for sensitive data).public/private: whether shared caches like CDNs may store it.s-maxage: a separate lifetime for shared caches.immutable: tells the browser the file will never change at this URL.stale-while-revalidate: serve the old copy briefly while fetching a fresh one.
Revalidation: ETags and Last-Modified
The server sends an ETag (a version identifier). Later, the browser asks "has this changed since ETag X?" If not, the server replies 304 Not Modified with no body, saving bandwidth.
A common, reliable strategy
- Static assets with hashed filenames (
app.3f9a1c.js): cache for a long time withimmutable. New deployments produce new filenames. - HTML pages: short cache or
no-cacheso users quickly get references to the new assets. - API responses: decide per endpoint; personalized data should be
privateorno-store.
Why users see stale pages
Long-cached HTML, CDN caches not purged on deploy, or service workers serving old files.
What caching bug has cost you the most time? How do you handle CDN invalidation on deploy?
Comments · 3
As a beginner this finally made it click. So if the file name includes a hash, like app.3f2a.js, you can cache it for a year without worry?
Rule of thumb: long cache with immutable for hashed assets, no-cache with ETag for the HTML page itself.
The "works in incognito but not in my normal browser" mystery finally makes sense now. Thanks for laying out where each cache lives.