How to Serve Stale-While-Revalidate
Serve stale content while refreshing in the background: set stale-while-revalidate, refresh on a hit, and keep the served value correct during the window.
On this page
Introduction
The usual cache trade-off is freshness against latency: a short TTL makes callers wait for the origin, a long one serves stale data. Stale-while-revalidate breaks the trade-off by serving the stale value immediately while refreshing it in the background, so the caller is fast and the origin still gets exactly one refresh. The caller accepts a little extra staleness in exchange for not waiting, and the cache stays warm for the next caller.
This tutorial covers defining a fresh window and a stale window, triggering a coalesced refresh on a stale hit, bounding the staleness, and testing the behavior. The examples use an in-process cache, but the pattern is the same as the HTTP Cache-Control extension and the CDN behavior that follows it.
Define a fresh window and a stale window
A value has a fresh period during which it is served without any check, and a stale period during which it is served only alongside a background refresh. Beyond the stale period the value is too old to serve and the caller must wait for a load. Three ages, then: fresh, stale-but-servable, and too old. Record when the value was stored and compute the age at read time to decide which window it is in.
Choose the windows from the product’s tolerance. A product that can show data a few seconds old uses a short fresh window and a longer stale one. A product where a read must reflect the latest write uses a fresh window and no stale window, or uses validation. The stale window is a promise that the data will be at most that far behind by the time it is refreshed, so keep it honest.
interface Entry { value: unknown; storedAt: number }
const FRESH_MS = 5000; // serve without any refresh
const STALE_MS = 30000; // serve with a background refresh
function age(entry: Entry) { return Date.now() - entry.storedAt; }
function isFresh(entry: Entry) { return age(entry) < FRESH_MS; }
function isServableStale(entry: Entry) { return age(entry) >= FRESH_MS && age(entry) < STALE_MS; }
function isTooOld(entry: Entry) { return age(entry) >= STALE_MS; }
Refresh in the background on a stale hit
On a stale-but-servable hit, return the stored value immediately and start a background refresh. The caller does not wait for the origin, which is the whole point. Coalesce the refresh with a single-flight guard so many callers hitting the same stale key trigger one refresh, not one each, or the background refresh becomes its own stampede.
The refresh replaces the entry with the new value and a new storedAt, so the next caller sees a fresh value. If the refresh fails, keep serving the stale value until it is too old, and retry on the next stale hit, so a transient origin error does not turn into a user-visible failure. The stale window is the buffer that makes a failing origin invisible for its duration.
async function getStaleWhileRevalidate(key, load) {
const entry = store.peek(key);
if (entry && isFresh(entry)) return entry.value; // fast path
if (entry && isServableStale(entry)) {
// return immediately, refresh in the background (coalesced)
singleFlightRef(messages(key), () => load().then((v) => store.put(key, v))).catch(() => {});
return entry.value;
}
return store.put(key, await load()).value; // too old or absent: wait
}
Bound the staleness with a hard maximum
The stale window is finite, and beyond it the value must not be served. This hard maximum is what keeps the staleness bounded even if refreshes keep failing: once a value passes it, the caller waits for a load or the request fails, rather than serving an increasingly old value. Without the maximum, a failing origin combined with an always-servable stale value could serve data from hours ago indefinitely.
Also cap the number of times a stale value is served without a successful refresh, or tie the maximum to a wall-clock age as above. The wall-clock maximum is simpler and matches how people reason about staleness. Expose the age of served stale values as a metric, so an origin that is failing and causing old data to be served is visible before a user complains.
// never serve a value older than the hard maximum
if (entry && isTooOld(entry)) {
return store.put(key, await load()).value; // force a load; do not serve stale
}
metrics.observe('cache.stale_age_ms', age(entry)); // watch staleness in production
Combine with HTTP and CDN semantics
The HTTP Cache-Control extension stale-while-revalidate makes a shared cache and a CDN do the same thing: serve within the fresh window, serve and revalidate within the stale window, and force a fetch beyond it. A response with max-age=60, stale-while-revalidate=300 tells a client or a CDN to serve fresh for sixty seconds, serve stale for five minutes while revalidating in the background, and fetch after that. Align your server-side cache windows with the header so the layers agree.
Where the origin also emits an ETag, the revalidation can use a conditional request and a 304, so the refresh transfers only headers when nothing changed. This pairs validation with stale-while-revalidate: the stale value is served, and the background refresh is a cheap conditional request that usually returns a 304, keeping the value fresh at almost no cost.
// align the header with the server-side windows
res.setHeader('Cache-Control', 'max-age=60, stale-while-revalidate=300, stale-if-error=600');
// client/CDN: fresh 60s, serve stale up to 300s while revalidating, fetch after
Test the window and the refresh
Test that a fresh value is served without any origin call. Test that a stale value is served immediately and a single background refresh is triggered, by counting origin calls under concurrent stale hits. Test that a value past the hard maximum is not served and a load happens. Test that a failing refresh keeps the stale value until the maximum, then surfaces the failure.
# hit a stale key with many concurrent requests: all get a fast stale response,
# but the origin is refreshed exactly once
seq 1 100 | xargs -P 100 -I{} curl -s -o /dev/null http://localhost:3000/cached
grep -c 'origin refresh' server.log # expect 1
Common pitfalls
No hard maximum so a stale value is served indefinitely when refresh fails, a non-coalesced refresh so the background refresh stampedes, serving stale for reads that must reflect the latest write, ignoring the age of served stale values so drift is invisible, and window values misaligned with the HTTP header are the recurring mistakes. Fresh and stale windows with a hard maximum, a coalesced refresh, correct applicability, staleness metrics, and header alignment address them.
Conclusion
Stale-while-revalidate trades a little staleness for much better latency. Define a fresh window, a stale window, and a hard maximum, serve stale immediately while refreshing in the background with coalescing, and align the windows with the HTTP header for consistency across layers. Self-check by asserting a stale hit returns immediately with exactly one background refresh and that a value past the maximum is not served. Then callers are fast and correctness stays bounded.
Sources: RFC 5861: HTTP Cache-Control extensions (stale-while-revalidate), MDN: Cache-Control, web.dev: stale-while-revalidate.
FAQ
- What is the difference between a short TTL and stale-while-revalidate?
- A short TTL forces every caller after expiry to wait for the origin. Stale-while-revalidate returns the old value immediately and refreshes in the background, so callers are fast and the origin still gets one refresh. It trades a small extra staleness for much better latency.
- Can stale-while-revalidate serve incorrect data?
- It can serve data that is out of date by up to the stale window. If a read must always reflect the latest write, do not serve stale for it; use validation or a short fresh period instead. The stale window is a product decision about acceptable staleness.
Report a problem with this articleOpens a pre-filled issue on GitHub.