Full answer
The idea. A fast screen matters more than perfect freshness in most cases. Stale-while-revalidate (SWR) returns cached data right away (stale), starts a request in the background (revalidate), and replaces the data when the response arrives.
Client layer (SWR, TanStack Query, RTK Query):
- A cache keyed by the request (
['course', id]). - Deduplication. Ten components asking for the same key share one request.
- Status flags separate the first load (
isLoading) from background refreshes (isFetching). - Revalidation triggers: on mount, on window focus, on reconnect, on an interval, and after mutations through invalidation.
- Staleness settings: TanStack Query's
staleTime(how long data counts as fresh, default 0) andgcTime(how long unused data stays in memory). SWR revalidates on mount and focus by default and has options to adjust that. - Optimistic updates and rollback for mutations.
HTTP layer. Browsers and CDNs cache by headers. Cache-Control: max-age defines freshness, ETag and If-None-Match allow conditional requests (304 with no body), and the stale-while-revalidate directive lets a cache serve stale responses while it refreshes in the background. The client library cache sits above this: when it revalidates, the request may be answered from the browser or CDN cache.
Server layer. Server Components, Next.js caching and framework data functions add a server-side cache and revalidation (time-based or on demand). Different layers can hold the same data, so define who owns freshness: choose short client staleness with CDN caching for public data, and no-store for private and user-specific data.
Pitfalls: showing stale data for critical values (balances, stock) without indicating freshness, caching private responses on shared caches, unstable query keys that defeat the cache, and forgetting invalidation after a mutation.
The example is a minimal cache with deduplication and background revalidation, to show the mechanics. In real projects use a library.
const cache = new Map();
const inflight = new Map();
let requests = 0;
async function fakeApi(key) {
requests += 1;
await new Promise((resolve) => setTimeout(resolve, 20));
return key + ' v' + requests;
}
function revalidate(key) {
if (!inflight.has(key)) {
inflight.set(key, fakeApi(key).then((data) => {
cache.set(key, data);
inflight.delete(key);
return data;
}));
}
return inflight.get(key);
}
async function get(key) {
const stale = cache.get(key);
const fresh = revalidate(key);
if (stale !== undefined) {
console.log('served stale: ' + stale);
fresh.then((data) => console.log('background update arrived: ' + data));
return stale;
}
console.log('no cache yet, waiting');
return fresh;
}
console.log('first call returned: ' + (await get('course-7')));
console.log('second call returned: ' + (await get('course-7')));
await new Promise((resolve) => setTimeout(resolve, 50));
console.log('cache now holds: ' + cache.get('course-7') + ', requests made: ' + requests);This is a plain script with a toy cache and not a real library. The second call returned instantly with stale data while one background request refreshed it. Output of the run: no cache yet, waiting first call returned: course-7 v1 served stale: course-7 v1 second call returned: course-7 v1 background update arrived: course-7 v2 cache now holds: course-7 v2, requests made: 2
Key points
- Stale-while-revalidate returns cached data first, then refreshes in the background.
- Client libraries add keyed caching, request deduplication, revalidation triggers and mutation invalidation.
- HTTP caching (Cache-Control, ETag, CDN) works under the client cache, and the layers must be tuned together.
- Distinguish isLoading (no data yet) from isFetching (refreshing).
- Never cache private data on shared layers, and always plan invalidation.
Common mistakes
- Treating stale data as correct for balances, inventory or permissions.
- Using unstable query keys such as inline objects that change identity.
- Caching private responses on shared CDN caches.
- Forgetting to invalidate related queries after a mutation.
- Confusing isLoading with isFetching in the UI.
Follow-ups
- What do staleTime and gcTime control in TanStack Query?
- How does the stale-while-revalidate Cache-Control directive differ from the client pattern?
- How would you implement an optimistic update with rollback?
Tips
- Define the pattern in one sentence and then place it in each layer.
- Mention deduplication and invalidation.
- Name one data type where staleness is unacceptable.