brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: stale-while-revalidate serves the old copy while the cache fetches a new one

Cache
~/tips/tip-stale-while-revalidate-header

Cache-Control: max-age=60, stale-while-revalidate=600

Visitors get a fast answer even right after the content expires.

A short cache time keeps content fresh, but now and then somebody has to wait while it is fetched again. One extra directive moves that wait into the background.

Send this:

Cache-Control: max-age=60, stale-while-revalidate=600

For the first 60 seconds the stored response is fresh. During the 600 seconds after that, a cache that supports the directive may answer straight away with the old copy and revalidate it at the same time, so the next request gets the new one. Later than that, it has to wait for the server like usual.

In nginx it is one line:

add_header Cache-Control "max-age=60, stale-while-revalidate=600";

I find it a good fit for a news list, a menu or a small JSON feed, where showing something a minute old once does no harm.

Do not use it for prices, stock levels or anything where one outdated answer is a problem. The first visitor after a quiet period sees the old version, which can look like your update failed. Support differs between browsers and CDNs, and a cache that does not know the directive just ignores it.

Further reading: MDN: Cache-Control

Going deeper: Guide: your Unraid cache is full and Docker stopped, how to find out why and fix it

More Cache tips fincore /var/lib/example/data.db npm cache verify fc-cache -f -v ~/.local/share/fonts proxy_cache app; Cache-Control: no-cache All Cache tips (24) All topics

Link