Dev.Lib
arrow_backBack to Blogs
LEVEL_055.2June 27, 20261 min read

Stale-while-revalidate

Caching & Networking

Serve stale cache immediately while fetching fresh in background — great UX for non-critical data.

Summary

Serve stale cache immediately while fetching fresh in background — great UX for non-critical data. User may briefly see outdated content — acceptable for feeds, not balances. HTTP Cache-Control: stale-while-revalidate and client libraries (SWR, TanStack Query staleTime). Tune staleTime vs gcTime consciously.

Code example

async function fetchWithSWR(key, fetcher, maxAgeMs = 60_000) {
  const cached = store.get(key);
  const isStale = !cached || Date.now() - cached.fetchedAt > maxAgeMs;

  if (cached) {
    if (isStale) fetcher(key).then((data) => store.set(key, { data, fetchedAt: Date.now() }));
    return cached.data;
  }

  const data = await fetcher(key);
  store.set(key, { data, fetchedAt: Date.now() });
  return data;
}

Key points

  • Serve stale cache immediately while fetching fresh in background — great UX for non-critical data.
  • User may briefly see outdated content — acceptable for feeds, not balances.
  • HTTP Cache-Control: stale-while-revalidate and client libraries (SWR, TanStack Query staleTime).
  • Tune staleTime vs gcTime consciously.

Further reading

Related concepts