Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

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.

JavaScript
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'));
Text
v1
v1
v1
v2

The 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.

Taggednode 24
Share

More snippets

Async

Sleep for a number of milliseconds

Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.

1 min read
Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.