← Back to JavaScript, page 10

javascript-0185 · Hard senior

How would you design a client-side data cache with freshness, request deduplication, and invalidation?

Key entries by a stable request key, store data with a fetched time, serve fresh entries without a request, serve stale ones immediately while revalidating in the background, share one in-flight promise per key, bound the size, and invalidate by key or prefix after writes. Handle errors by keeping the last good data. This is the model behind libraries such as TanStack Query and SWR.

Full answer

Start with requirements: what data, how stale is acceptable, how often it changes, whether users share a device, and memory limits.

Design pieces:

  1. Keys: a stable, serializable key such as ['user', id] turned into a string. Include every input that changes the response (filters, language, auth user), so one user never sees another's data.
  2. Entry shape: { data, error, fetchedAt, promise }. Two time settings: staleTime (how long data counts as fresh, no request) and gcTime (how long an unused entry stays in memory).
  3. Read path: fresh entry returns at once. Stale entry returns the old data right away and starts a background refetch (stale-while-revalidate). Missing entry fetches and waits.
  4. Deduplication: store the in-flight promise per key, so ten components asking at once cause one request. Remove it in finally.
  5. Errors: keep the last good data when a refetch fails, expose the error, retry with backoff for network errors, and do not cache errors for long.
  6. Invalidation: after a mutation, mark related keys stale (by exact key or prefix) and refetch the active ones. Optimistic updates write the expected data first and roll back on failure.
  7. Memory: a size limit with LRU eviction, and garbage collection of entries with no subscribers.
  8. Subscriptions: components subscribe to a key and are notified on change, so the UI updates when a refetch finishes. Notify only when data actually changed.
  9. Triggers for refetching: window focus, network reconnect, and an optional interval.
  10. Persistence: optionally save to localStorage or IndexedDB with a version and a maximum age. Clear it on logout, and never persist sensitive data on shared devices.
  11. HTTP cooperation: respect ETag and Cache-Control, use conditional requests, and remember that the browser also has an HTTP cache.
  12. Testing: inject the clock and the fetcher.

Trade-offs: longer staleTime means fewer requests and more stale screens, and shared caches are fast but need careful keys and invalidation. Invalidation is the hard part, so keep rules simple: writes invalidate by prefix.

javascript
function createCache({ now, staleTime = 1000, maxEntries = 3 }) {
  const entries = new Map();
  const listeners = new Map();
  const stats = { fetches: 0, hits: 0, staleServed: 0, deduped: 0 };

  const notify = (key) => (listeners.get(key) ?? []).forEach((fn) => fn(entries.get(key)?.data));
  const touch = (key, entry) => {
    entries.delete(key);
    entries.set(key, entry);
    while (entries.size > maxEntries) entries.delete(entries.keys().next().value);
  };

  function refetch(key, fetcher) {
    const entry = entries.get(key) ?? {};
    if (entry.promise) {
      stats.deduped++;
      return entry.promise;
    }
    stats.fetches++;
    const promise = fetcher()
      .then((data) => {
        touch(key, { data, fetchedAt: now(), promise: null });
        notify(key);
        return data;
      })
      .catch((error) => {
        touch(key, { ...entries.get(key), error, promise: null });
        if (entries.get(key)?.data === undefined) throw error;
        return entries.get(key).data;
      });
    touch(key, { ...entry, promise });
    return promise;
  }

  return {
    stats,
    get(key, fetcher) {
      const entry = entries.get(key);
      if (entry && entry.data !== undefined) {
        if (now() - entry.fetchedAt < staleTime) {
          stats.hits++;
          return Promise.resolve(entry.data);
        }
        stats.staleServed++;
        refetch(key, fetcher);
        return Promise.resolve(entry.data);
      }
      return refetch(key, fetcher);
    },
    invalidate(prefix) {
      for (const [key, entry] of entries) if (key.startsWith(prefix)) entries.set(key, { ...entry, fetchedAt: -Infinity });
    },
    subscribe(key, fn) {
      listeners.set(key, [...(listeners.get(key) ?? []), fn]);
    },
    keys: () => [...entries.keys()],
  };
}

let clock = 0;
let version = 1;
let failNext = false;
const server = () => new Promise((resolve, reject) => setImmediate(() => (failNext ? reject(new Error('network')) : resolve({ name: 'Asha', version }))));
const settle = () => new Promise((resolve) => setImmediate(() => setImmediate(resolve)));

(async () => {
  const cache = createCache({ now: () => clock });
  cache.subscribe('user:1', (data) => console.log('  subscriber saw', JSON.stringify(data)));

  const [a, b, c] = await Promise.all([cache.get('user:1', server), cache.get('user:1', server), cache.get('user:1', server)]);
  console.log('three readers, one fetch:', cache.stats, a === b && b === c);

  clock = 500;
  await cache.get('user:1', server);
  console.log('fresh read:', cache.stats.hits, 'hit, fetches', cache.stats.fetches);

  clock = 2000;
  version = 2;
  console.log('stale read returns old data first:', JSON.stringify(await cache.get('user:1', server)));
  await settle();
  console.log('next read has new data:', JSON.stringify(await cache.get('user:1', server)));

  version = 3;
  cache.invalidate('user:');
  console.log('after invalidate, old data returned:', (await cache.get('user:1', server)).version);
  await settle();

  failNext = true;
  clock = 9000;
  console.log('refetch fails, last good data kept:', (await cache.get('user:1', server)).version);
  await settle();
  failNext = false;

  for (const id of [2, 3, 4]) await cache.get('user:' + id, server);
  console.log('size limit keeps the newest:', cache.keys());
})();

Run with Node.js v24.22.1 as js-185.js; two runs gave identical output. Output: subscriber saw {"name":"Asha","version":1} three readers, one fetch: { fetches: 1, hits: 0, staleServed: 0, deduped: 2 } true fresh read: 1 hit, fetches 1 stale read returns old data first: {"name":"Asha","version":1} subscriber saw {"name":"Asha","version":2} next read has new data: {"name":"Asha","version":2} after invalidate, old data returned: 2 subscriber saw {"name":"Asha","version":3} refetch fails, last good data kept: 3 size limit keeps the newest: [ 'user:2', 'user:3', 'user:4' ]

Key points

  • Stable keys that include every input; store data with fetchedAt.
  • Fresh returns directly; stale returns and revalidates; missing waits.
  • One in-flight promise per key prevents duplicate requests.
  • Keep the last good data on errors; invalidate by key or prefix after writes.
  • Bound memory, notify subscribers, persist carefully, and test with injected clock and fetcher.

Common mistakes

  • Using a cache key that misses an input such as the user or a filter.
  • Starting a new request for every reader instead of sharing the promise.
  • Dropping good data when a refetch fails.
  • Invalidating too broadly or not at all after writes.

Follow-ups

  • How would you add optimistic updates with rollback?
  • What would you persist, and what never?
  • How does this relate to HTTP caching headers?

Tips

  • Describe fresh, stale, and missing as three read paths.
  • Mention deduplication and invalidation as the real difficulty.
  • Mention security: keys must include the user, and clear on logout.