← Back to Frontend, page 3

frontend-0059 · Hard senior

How would you build a small client-side data cache that shares in-flight requests and uses stale-while-revalidate, as data-fetching libraries do?

Keep a map from a request key to an entry that holds the data, the time it was fetched and any promise in flight. A get returns fresh data without a request, returns stale data at once while a background refetch runs, and lets concurrent callers for the same key share one promise.

Full answer

Data-fetching libraries such as TanStack Query and SWR are built on a small set of ideas, and a candidate should be able to describe them and sketch the core.

State per key:

  • data and the time it was stored (fetchedAt).
  • promise when a request is in flight.
  • an error, if the last attempt failed.

Rules:

  1. Fresh. If the data is younger than staleMs, return it. No request.
  2. Stale. If the data is older, return it immediately so that the screen is not blank, and start a background refetch. When it finishes, the entry is updated and subscribers are told.
  3. Missing. Start a request and wait for it.
  4. In-flight deduplication. If a request for the same key is already running, return the same promise. Ten components that need the same user profile cause one request.
  5. Key design. The key must contain every input that changes the answer: path, query values, user id. Serialise it in a stable way.
  6. Errors. Do not cache a failure as data. Keep stale data visible and show an error state, and retry with backoff.
  7. Invalidation. After a mutation, mark related keys as stale, or refetch them. Without it, the screen can show old data after a save.
  8. Memory. Remove entries that nobody uses after some time (garbage collection), and set a limit.

Extra features to name: refetch on window focus or reconnection, retries, pagination and infinite queries, request cancellation, and persistence to storage for fast restarts.

Risks: a long stale time shows old information, and a very short one loses the benefit. The right values depend on how fast the data changes and how bad a stale view is.

The script has a fake clock and a counter for the fetcher. Two concurrent calls make one fetch. A call within the fresh window makes none. A call after the window gets the old value at once, and the new value after the refetch.

javascript
function createCache(now) {
  const entries = new Map();
  return function get(key, fetcher, staleMs) {
    let e = entries.get(key);
    if (!e) { e = {}; entries.set(key, e); }
    const refetch = () => {
      if (!e.promise) {
        e.promise = fetcher().then((data) => { e.data = data; e.at = now(); }).finally(() => { e.promise = null; });
      }
      return e.promise;
    };
    if ('data' in e) {
      if (now() - e.at >= staleMs) refetch();        // stale: answer now, refresh behind
      return Promise.resolve(e.data);
    }
    return refetch().then(() => e.data);              // missing: wait, share the promise
  };
}

let clock = 0, calls = 0;
const get = createCache(() => clock);
const fetcher = async () => { calls += 1; return 'profile v' + calls; };

const [a, b] = await Promise.all([get('user:1', fetcher, 1000), get('user:1', fetcher, 1000)]);
console.log('two callers:', a, b, 'fetch calls:', calls);
clock = 500;
console.log('fresh:', await get('user:1', fetcher, 1000), 'fetch calls:', calls);
clock = 1500;
console.log('stale:', await get('user:1', fetcher, 1000), 'fetch calls:', calls);
await new Promise((r) => setTimeout(r, 10));
console.log('after refetch:', await get('user:1', fetcher, 1000));

Run with Node 24.22.1. The output matched the text in the answer in two runs.

Key points

  • Store data, fetch time and in-flight promise per key.
  • Fresh returns data. Stale returns data and refetches. Missing waits.
  • Concurrent callers share one in-flight promise.
  • Keys must include every input, and mutations must invalidate.
  • Plan for errors, memory limits and refetch triggers.

Common mistakes

  • Caching by URL while ignoring user id or locale.
  • Caching failed responses as if they were data.
  • Forgetting to invalidate after a mutation.
  • Starting a duplicate request for every component that mounts.

Follow-ups

  • How would you add subscribers so that the UI updates after a background refetch?
  • How does this change for infinite scrolling?
  • What would you persist across page loads?

Tips

  • List the per-key state, then the five rules.
  • Say how invalidation works, since many answers forget it.