How stale-while-revalidate works
Use Cache-Control to set how long a cache may serve a stale response while refreshing it in the background.
Your API response carries Cache-Control: max-age=60, and the first request after the minute is up waits for the full server time. You want that request to get the old copy at once and let the refresh happen out of sight.
stale-while-revalidate does that. The directive comes from RFC 5861. With Cache-Control: max-age=60, stale-while-revalidate=600, a supporting cache uses the response’s calculated age to decide what to do.
- Under 60 seconds, the copy is fresh. The cache can serve it without contacting the origin.
- Once stale, the cache may serve the copy for another 600 seconds. A request during that window can trigger background validation.
- Beyond that window, this directive no longer permits stale reuse. The cache typically waits for the origin and can validate its existing copy if it has a validator.
diagram
What the client gets in each window
Watch it in a browser
I did not want to wait ten minutes, so I ran the same header with max-age=2, stale-while-revalidate=5. This server counts its hits and answers after 300 ms, which makes a cache answer and a real fetch easy to tell apart.
import { createServer } from 'node:http'
let hits = 0
createServer((req, res) => {
if (req.url !== '/data') {
res.writeHead(200, { 'content-type': 'text/html', 'cache-control': 'no-store' })
return res.end('<!doctype html><title>swr</title>')
}
const hit = ++hits
console.log('server hit', hit)
setTimeout(() => {
res.writeHead(200, {
'content-type': 'application/json',
'cache-control': 'max-age=2, stale-while-revalidate=5',
})
res.end(JSON.stringify({ hit }))
}, 300)
}).listen(4131, '127.0.0.1')Run node server.mjs and open http://127.0.0.1:4131/ in Chrome with DevTools’ Disable cache checkbox off. Paste this into the console to fetch /data five times with pauses between them.
const sleep = (s) => new Promise((r) => setTimeout(r, s * 1000))
for (const wait of [0, 1, 2, 0.8, 8]) {
await sleep(wait)
const t0 = performance.now()
const { hit } = await (await fetch('/data')).json()
console.log(`${Math.round(performance.now() - t0)} ms, body hit=${hit}`)
}The console prints one line per fetch, and the Node terminal prints three server hit lines. I ran it in Chromium twice and got this each time, give or take a few milliseconds:
- Fetch 1, empty cache: 308 ms,
hit=1. The server answered. - Fetch 2, 1 second old: 4 ms,
hit=1. Fresh, so no request. - Fetch 3, 3 seconds old: 4 ms,
hit=1. Stale, so the old body came back at once and the server logged hit 2 in the background. - Fetch 4, 0.8 seconds later: 6 ms,
hit=2. The background refresh had replaced the copy. - Fetch 5, 8 seconds later: 312 ms,
hit=3. The copy was past 2 + 5 seconds, so the fetch waited for the server.
Requests during the refresh can still get the old copy. A later request can use the refreshed response after it arrives.
Pick the numbers
Use max-age for the freshness lifetime and stale-while-revalidate for the extra time a supporting cache may serve an older copy. Those values apply to cached responses. They do not update a page that someone has left open.
This directive starts no timer to refresh a quiet URL. If no request arrives during the stale window, the next request may have to wait for validation.