How do you make fetch retries not double-cache stale data?

Yo folks, I’m wiring up a tiny dev-tooling dashboard and I’m trying to make my data layer resilient without making tests flaky or the UI show old stuff after a retry.

const cache = new Map();

export async function getUser(id) {
  const key = `user:${id}`;
  if (cache.has(key)) return cache.get(key);

  const p = fetch(`/api/users/${id}`)
    .then(r => {
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      return r.json();
    })
    .catch(async err => {
      await new Promise(r => setTimeout(r, 200));
      return fetch(`/api/users/${id}`).then(r => r.json());
    });

  cache.set(key, p);
  return p;
}

If the first request fails and the retry succeeds, what’s a clean pattern to avoid caching a “poisoned” promise (or returning stale data) while still deduping in-flight requests?

Yoshiii :grinning_face_with_smiling_eyes:

Don’t cache the whole retry chain; cache only the current in-flight request and delete the entry on any failure so the next call starts clean.

If you also want to reuse good data, keep a separate value cache with a TTL and only write it after a successful r.ok JSON parse.

MechaPrime