Skip to the code

Stale-while-revalidate in a service worker

MediumCaching

The tea shop's reviews and stock levels change during the day, but a copy from a few minutes ago is fine to show at once. Write staleWhileRevalidate(event, options), which the service worker's fetch handler calls for those requests. It must call event.respondWith() before it returns.

Look for the request in the options.cacheName cache ("tea-shop-api" when it isn't given), and start fetching it at the same time, so that on a miss the request is already on its way. If the cache has a copy, answer with it straight away, without waiting for the network. When the network's response arrives, store a copy if it's ok, replacing the old one, so the next request gets it. If the cache has nothing, answer with the network's response, and store it too if it's ok. Make one network request per event, never two.

A refresh that fails, offline or with a response that isn't ok, leaves the cached copy as it was, and doesn't fail anything: the page already has its answer, so every promise you give the event should fulfill. With nothing cached, a failed fetch fails the answer with its error. Keep the worker alive with event.waitUntil() until the refresh is stored, and call it before your first await, since later it only works while an earlier promise is still pending.

This is Workbox's StaleWhileRevalidate strategy. It takes its name from HTTP's stale-while-revalidate directive (RFC 5861), but it has no time window: every request answers from the cache and refreshes it. The JavaScript problem Stale-while-revalidate cache (stale-while-revalidate) builds the idea around a function's results in memory; this one works on requests and Cache Storage, within a service worker event's lifetime.

self.addEventListener("fetch", (event) => {
  if (new URL(event.request.url).pathname.startsWith("/api/reviews")) staleWhileRevalidate(event);
});
// First visit: nothing stored, so the reviews come from the network, and a copy is stored.
// Every visit after: the stored reviews show at once, and the network's newer ones replace them for next time.

What the tests check

  1. answers with the cached copy at once, without waiting for the network
    useFakeTimers();
    useCaches();
    await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
    useFetch(() => ({ body: "13 reviews", delay: 5000 }));
    const event = fetchEvent("/api/reviews");
    staleWhileRevalidate(event);
    let answer = "no answer yet";
    event.response().then((response) => (answer = response), (error) => (answer = error));
    for (let turn = 0; turn < 20 && answer === "no answer yet"; turn++) await flush();
    expect(await answer.text()).toBe("12 reviews");
    
  2. refreshes the cached copy in the background, for the next request
    const clock = useFakeTimers();
    useCaches();
    await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
    useFetch(() => ({ body: "13 reviews", delay: 1000 }));
    const first = fetchEvent("/api/reviews");
    staleWhileRevalidate(first);
    expect(await (await first.response()).text()).toBe("12 reviews");
    await clock.tickAsync(1000);
    await first.settled();
    const second = fetchEvent("/api/reviews");
    staleWhileRevalidate(second);
    expect(await (await second.response()).text()).toBe("13 reviews");
    
  3. starts the network request at once, alongside the cache lookup
    useCaches();
    await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
    const network = useFetch(() => ({ body: "13 reviews" }));
    const event = fetchEvent("/api/reviews");
    staleWhileRevalidate(event);
    expect(network.calls.map((call) => call.url)).toEqual(["https://example.test/api/reviews"]);
    await event.settled();
    
  4. on a miss, answers from the network with one request, and stores the response
    useCaches();
    const network = useFetch(() => ({ body: "3 oolongs left" }));
    const event = fetchEvent("/api/stock/oolong");
    staleWhileRevalidate(event);
    expect(await (await event.response()).text()).toBe("3 oolongs left");
    await event.settled();
    expect(network.calls).toHaveLength(1);
    expect(await (await caches.match("/api/stock/oolong")).text()).toBe("3 oolongs left");
    
  5. a failed refresh keeps the cached copy, and every promise given to the event fulfills
    useCaches();
    await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
    useFetch(() => {
      throw new TypeError("Failed to fetch");
    });
    const event = fetchEvent("/api/reviews");
    staleWhileRevalidate(event);
    expect(await (await event.response()).text()).toBe("12 reviews");
    const outcomes = await event.settled();
    expect(outcomes.map((outcome) => outcome.status).filter((status) => status !== "fulfilled")).toEqual([]);
    expect(await (await caches.match("/api/reviews")).text()).toBe("12 reviews");
    
  6. a refresh that isn't ok doesn't replace the cached copy
    useCaches();
    await (await caches.open("tea-shop-api")).put("/api/reviews", new Response("12 reviews"));
    useFetch(() => ({ status: 503, body: "Back soon" }));
    const event = fetchEvent("/api/reviews");
    staleWhileRevalidate(event);
    expect(await (await event.response()).text()).toBe("12 reviews");
    await event.settled();
    expect(await (await caches.match("/api/reviews")).text()).toBe("12 reviews");
    
  7. with nothing cached, a failed fetch fails the answer
    useCaches();
    useFetch(() => {
      throw new TypeError("Failed to fetch");
    });
    const event = fetchEvent("/api/reviews");
    staleWhileRevalidate(event);
    await expect(event.response()).rejects.toThrow("Failed to fetch");
    
  8. with nothing cached, a response that isn't ok is the answer, and isn't stored
    useCaches();
    useFetch(() => ({ status: 404, body: "No such tea" }));
    const event = fetchEvent("/api/stock/rooibos");
    staleWhileRevalidate(event);
    expect((await event.response()).status).toBe(404);
    await event.settled();
    expect(await caches.match("/api/stock/rooibos")).toBe(undefined);
    
  9. takes another cache name
    const clock = useFakeTimers();
    const cacheStorage = useCaches();
    await (await caches.open("tea-shop-stock-v1")).put("/api/stock/mint", new Response("9 left"));
    useFetch(() => ({ body: "8 left", delay: 100 }));
    const event = fetchEvent("/api/stock/mint");
    staleWhileRevalidate(event, { cacheName: "tea-shop-stock-v1" });
    expect(await (await event.response()).text()).toBe("9 left");
    await clock.tickAsync(100);
    await event.settled();
    expect(cacheStorage.contents()).toEqual({ "tea-shop-stock-v1": ["https://example.test/api/stock/mint"] });
    expect(await (await caches.match("/api/stock/mint")).text()).toBe("8 left");
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).