Cache headers, CDNs, and stale-while-revalidate
One header turns a cold cache into an instant page for roughly a third of visits, and it costs nothing to ship. What it does, and where it quietly breaks.
stale-while-revalidate is the rare performance change with no trade-off worth arguing about: the visitor gets the cached response immediately, and the cache refreshes itself in the background for whoever comes next.
The header
Cache-Control: public, max-age=60, stale-while-revalidate=86400
For sixty seconds the response is fresh. For the next day it is served instantly while a background request fetches a new copy. After that the cache goes back to blocking.
Where it breaks
Personalised responses are not cacheable
The second failure is subtler. A long stale window means a bad deploy stays live for a day even after you have rolled it back, because the CDN is still handing out the stale copy while it revalidates. Keep the window long for assets and short for HTML.
Key takeaways
- Long stale windows for hashed assets, short ones for HTML.
- Anything personalised needs a Vary header or it does not belong in a shared cache.
- Know how to purge before you need to purge.