Implement stale while revalidate in JavaScript
Implement stale while revalidate in JavaScript: return the cached value at once and refresh it in the background. Node.js 24, no library.
Stale-while-revalidate returns the old value immediately and fetches a new one in the background, so the caller never waits after the first load.
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
function swr(load, ttl, now = Date.now) {
const entries = new Map();
return async (key) => {
const entry = entries.get(key);
const refresh = () =>
load(key).then((value) => {
entries.set(key, { value, at: now() });
return value;
});
if (!entry) return refresh();
if (now() - entry.at > ttl) refresh().catch(() => {});
return entry.value;
};
}
let clock = 0;
let version = 0;
const get = swr(async () => `v${++version}`, 1000, () => clock);
console.log(await get('a'));
clock = 500;
console.log(await get('a'));
clock = 2000;
console.log(await get('a'));
await delay(0);
console.log(await get('a'));v1
v1
v1
v2The first call has nothing cached, so it waits for v1. At 500 ms the entry is fresh and nothing loads. At 2000 ms it is stale: the call returns v1 straight away and starts a refresh, and the next call sees v2. The name comes from the HTTP cache directive in RFC 5861, which describes the same idea.
If two stale reads arrive together, both start a refresh. Store the in-flight promise per key, as in running a function at most once at a time, to prevent that.