Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Caching Strategies

Stale-While-Revalidate

Learn stale-while-revalidate for PWAs: answer instantly from cache, refresh in the background, notify the page, with code, comparisons and the other cache strategies.

Cache first is fast but can be stale. Network first is fresh but can be slow. Stale-while-revalidate (SWR) tries to give you both: it answers immediately from the cache (the "stale" part), and at the same time asks the network for a new copy and stores it (the "revalidate" part). The next visit sees the updated version. The user never waits for the network when a cached copy exists, and the content is at most one visit behind.

sequenceDiagram
  participant Page
  participant SW as Service worker
  participant Cache
  participant Net as Network
  Page->>SW: request
  SW->>Cache: match
  Cache-->>SW: cached (maybe old)
  SW-->>Page: respond immediately
  SW->>Net: fetch in background
  Net-->>SW: fresh response
  SW->>Cache: put(fresh)

The page gets a fast answer; the cache is refreshed behind its back for the next time.

The code

JavaScript
async function staleWhileRevalidate(event) {
  const cache = await caches.open('swr-v1');
  const cached = await cache.match(event.request);

  const networkUpdate = fetch(event.request)
    .then((response) => {
      if (response.ok) cache.put(event.request, response.clone());
      return response;
    })
    .catch(() => null);

  event.waitUntil(networkUpdate);          // keep the worker alive until the update finishes
  return cached || (await networkUpdate) || Response.error();
}

self.addEventListener('fetch', (event) => {
  if (event.request.method !== 'GET') return;
  event.respondWith(staleWhileRevalidate(event));
});

Important details:

  • The network request starts even if there is a cache hit. That is the revalidation.
  • On a hit we return the cached response without waiting.
  • On a miss we wait for the network (it is the first visit, nothing to show yet).
  • event.waitUntil(networkUpdate) is essential. Without it the browser may stop the worker right after responding, killing the background fetch.
  • Errors in the background fetch are swallowed with .catch(() => null): offline users still get the cached copy.

Where it shines

SWR is great for content where "a little old is fine" but speed matters:

  • Avatars and profile images.
  • CSS and JS files with non-fingerprinted names (/app.js): the user gets the cached file right now, and the new file is ready next load.
  • API data such as article lists, weather summaries, social feeds.
  • Anything that changes occasionally but not every second.

It is not ideal for data that must be exactly right (payments, stock levels, anything involving security) or for one-time data. For HTML documents it is often a good compromise when combined with a visible update prompt, because users see the previous version first.

Let the page know about the fresh copy

With plain SWR the user sees old data now and fresh data on the next visit. You can improve this by telling the page when new data arrives, and letting it re-render. The worker posts a message to all clients after updating the cache:

JavaScript
async function notifyClients(url) {
  const clients = await self.clients.matchAll({ type: 'window' });
  for (const client of clients) {
    client.postMessage({ type: 'CACHE_UPDATED', url });
  }
}

And in the page:

JavaScript
navigator.serviceWorker.addEventListener('message', (event) => {
  if (event.data.type === 'CACHE_UPDATED' && event.data.url.endsWith('/api/news')) {
    refreshNews();     // re-fetch (now from the fresh cache) and re-render
  }
});

You should only notify when the content actually changed, to avoid needless re-renders. Compare an ETag or Last-Modified header, or a hash of the body (Workbox's BroadcastUpdatePlugin does this).

A runnable SWR

This stand-in lets you watch the stale response arrive first and the cache update afterward. Run it and follow the three requests: first (a miss), second (stale, updated in the background) and third (now showing the update).

JS Stand-in: stale-while-revalidate over time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the timings: the stale answers come back in about 0 ms, while only the first miss pays for the network.

Comparing the strategies

Strategy Order Speed Freshness Offline Typical use
Cache only cache Fastest Frozen Yes Precached shell files
Cache first cache, then network Fast Stale risk Yes Fingerprinted assets, fonts
Network first network, then cache Network speed Fresh Fallback HTML, critical data
Stale-while-revalidate cache and network Fast One step behind Yes Avatars, feeds, unversioned assets
Network only network Network speed Fresh No Payments, analytics beacons

Plus the cache, then network pattern, where the page shows cached data and then swaps in fresh data as soon as it arrives (like SWR but driven from page code), and network race, where cache and network race and the first answer wins.

Strategy picker

Choosing is easier with a few questions. This runnable stand-in encodes a reasonable decision tree; extend it with your own rules.

JS Stand-in: pick a strategy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

SWR pitfalls

  • Double traffic: every request hits the network even on a hit. For very frequent requests (autocomplete), use another strategy or throttle.
  • Forgetting waitUntil: the background update is silently cut off.
  • Cache growth: combine with entry limits and an expiration.
  • Inconsistent UI: showing old data and then swapping can surprise users; make updates visible and gentle.
  • Mixed versions: with unfingerprinted JS and CSS, SWR can serve a new app.js that does not match an old cached HTML page. Prefer fingerprinted assets with cache first and keep SWR for data and images.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does stale-while-revalidate do on a cache hit?

    It answers immediately from the cache and updates the cache for next time.
  2. 2. Why is event.waitUntil() important in SWR?

    Without waitUntil the browser may terminate the idle worker and abort the revalidation.
  3. 3. Which resource is a good SWR candidate?

    Avatars can be slightly old; nobody notices, and the speed is a gain.
  4. 4. How can the page learn that SWR fetched new data?

    postMessage from the worker to its clients lets the page re-render with fresh data.

Summary

  • SWR answers from the cache immediately and refreshes the cache from the network in the background.
  • Use event.waitUntil for the background update; swallow network errors so offline still works.
  • It fits avatars, feeds, and tolerant data; avoid it for exact or sensitive data.
  • Notify the page with postMessage if you want to show fresh content right away.
  • Pick strategies per resource type: cache first, network first, SWR, cache only, network only.

Next: Precaching and Cache Versioning