Skip to content

    Frontend System Design

    Service Worker Caching Strategies

    Compare the five service worker caching strategies with a pure model that shows what each one serves online, offline and when the origin returns an error.

    By Published 13 min read

    • frontend-system-design
    • service-workers
    • caching
    • offline
    • pwa
    Share

    Standard lessonintermediateTypeScript labFrontend System Design

    Before this: Service Workers

    What you'll learn: By the end of this lesson you will be able to name the five standard service worker caching strategies, say for each one what it serves on a hit, on a miss and offline, choose one per kind of request (static asset, page, API data), explain why an entry in the Cache API never expires by itself, avoid storing error responses, version and delete caches when a worker updates, and read a pure model of the strategies that is tested without a browser.

    Think of a corner shop with a storeroom. Cache first serves from the shelf and visits the supplier only when the shelf is empty. Network first phones the supplier every time and uses the shelf only when the line is dead. Stale while revalidate hands over what is on the shelf while a runner fetches fresh stock for the next customer. None is "the best": each trades speed against freshness and against what happens when the supplier cannot be reached.

    A service worker is the person behind the counter for a whole origin. It can answer any request the page makes, and the strategy is the rule it follows. The running example is the product page of a grocery marketplace (the front end of the ShopStream marketplace used in this course): a shell, fingerprinted scripts and styles, a product list from /api/products.json, and a cart.

    This lesson assumes you know what a service worker is: a script between the page and the network that handles fetch events (its own lessons, on the basics and on the lifecycle, are separate). The wider map of caches is in Caching Across the Stack, and one layer in depth is in HTTP Caching for the Front End.

    The core idea

    1. A strategy is an order of two sources. The two sources are the Cache API and the network. A strategy says which one to ask first, what to do on failure and whether to refresh the stored copy afterwards.
    2. The Cache API has no lifetime. MDN says items in a Cache "do not get updated unless explicitly requested; they don't expire unless deleted", and that you are responsible for purging entries. Every strategy that stores something needs a way for that something to become fresh again.
    3. You pick per kind of request, not once for the whole site. Fingerprinted assets, HTML and mutable API data want different answers.

    Figure 1. Where the strategy runs

    A fetch event handler choosing between Cache Storage and the networkPage to Service worker (request); Service worker to Cache Storage (match / put); Service worker to Network (fetch); Network to Service worker (offline: fetch rejects)Page: requests a URLPagerequests a URLService worker: fetch event, strategyService workerfetch event,strategyCache Storage: named cachesCache Storagenamed cachesNetwork: origin or CDNNetworkorigin or CDNrequestmatch / putfetchoffline: fetch rejects

    How to read this: every request from a controlled page passes the accent box, which may answer from Cache Storage, from the network or from both. The red edge is the case the strategies differ on most: the network is not there.

    The five strategies

    The Workbox documentation (a library for service workers, from the Chrome team) names the set. This lesson uses the plain browser APIs and the same names.

    Strategy On a cache hit On a miss Offline Freshness
    Network only Cache not used Network Fails Always current
    Cache only Served Cannot be served Works for stored URLs Never updated until the worker is
    Cache first Served, no request Network, then store Works for stored URLs Stays as stored
    Network first Used only if the network fails Network, then store Last stored copy Current while online
    Stale while revalidate Served at once, refreshed in the background Network, then store Last stored copy One request behind

    The Workbox overview says cache first "offers a speed boost for immutable assets by side-stepping any content freshness checks". Network first suits HTML or API requests when you want "offline access to the most recent available version". Network only "will never work when the user is offline". With cache only, matching requests "will only ever go to the cache", so assets are stored when the worker installs and "will never be updated in the cache until the service worker is updated". Stale while revalidate fits things that are "sort of important to keep up to date", such as avatars.

    Illustration 1: the minimal example

    A stale-while-revalidate handler for one URL. This code is shown, not run: it needs a browser with a registered service worker, and this lesson uses no browser automation.

    const CACHE = "shop-api-v1";
    
    self.addEventListener("fetch", (event) => {
      const url = new URL(event.request.url);
      if (event.request.method !== "GET" || url.pathname !== "/api/products.json") return;
      event.respondWith(staleWhileRevalidate(event));
    });
    
    async function staleWhileRevalidate(event) {
      const cache = await caches.open(CACHE);
      const cached = await cache.match(event.request);
      const refresh = fetch(event.request).then(async (response) => {
        if (response.ok) await cache.put(event.request, response.clone());
        return response;
      });
      if (cached) {
        event.waitUntil(refresh.catch(() => {}));
        return cached;
      }
      return refresh;
    }

    Four platform rules sit behind these lines, each from MDN:

    • respondWith() "prevents the browser's default fetch handling" and takes a Response or a promise for one; anything else becomes a network error. A handler that returns without calling it (the early return above) leaves the request to the browser. It can be called only once per event.
    • A Response body is a one-use stream, so putting it in the cache and returning it needs clone(). MDN's service worker guide says: "The original gets returned to the browser and the clone gets sent to the cache. They are each read once." clone() throws a TypeError if the body was already used, so clone before reading.
    • waitUntil() tells the browser the work is ongoing, "and it shouldn't terminate the service worker if it wants that work to complete." Here the background refresh is passed to it.
    • Only response.ok responses are stored, because a stored error is served as long as the entry lives (see below).

    Choosing per request

    Figure 2. Picking a strategy

    flowchart TD accTitle: Choosing a caching strategy for a request accDescr: A decision tree. If the response must never be stale, such as a cart or checkout, use network only or network first. If the URL changes whenever the content changes, as with fingerprinted files, use cache first. If the copy may be slightly old and speed matters, use stale while revalidate. If the page must work offline with the latest copy that was seen, use network first with a fallback to the cache. Q1{"Can a stale copy
    do harm?"} Q1 -->|"yes"| N["Network only
    (or network first
    with a short timeout)"] Q1 -->|"no"| Q2{"Does the URL change
    when the content changes?"} Q2 -->|"yes (fingerprinted)"| C["Cache first"] Q2 -->|"no"| Q3{"Is one request of
    staleness acceptable?"} Q3 -->|"yes"| S["Stale while revalidate"] Q3 -->|"no, but offline
    must still work"| F["Network first,
    fall back to cache"]

    How to read this: the first question is about harm, not speed. Speed only decides between the safe options. A fingerprinted URL (a hash in the file name) is the one case where "never refreshed" is correct, because new content arrives under a new URL.

    What the strategies do, from a model

    The lab for this lesson is a model: five pure functions over a fake network, a fake cache and a fake clock. It is not a browser, there is no fetch event and no real Cache Storage, so it shows the decision each strategy makes, not browser timing, quotas or eviction. One choice in it is its own, not a claim about any library: a response is stored only when its status is 200 to 299. Responses are plain values, so there is no body to clone.

    Illustration 2: the realistic example, online and offline

    Scenario 1 asks for /api/products.json three times on a cold cache, and the origin changes from v1 to v2 before the second request. Three of the five strategies:

    Expected output, captured from a real run (the node demo of the lab, scenario 1, strategies three to five):

    -- cache first
    request 1: from network, status 200, body "v1"  [cache miss > fetch > put (200)]
    request 2: from cache, status 200, body "v1"  [cache hit]
    request 3: from cache, status 200, body "v1"  [cache hit]
       cache now holds: v1, network requests made: 1
    -- network first
    request 1: from network, status 200, body "v1"  [fetch > put (200)]
    request 2: from network, status 200, body "v2"  [fetch > put (200)]
    request 3: from network, status 200, body "v2"  [fetch > put (200)]
       cache now holds: v2, network requests made: 3
    -- stale while revalidate
    request 1: from network, status 200, body "v1"  [cache miss > fetch > put (200)]
    request 2: from cache, status 200, body "v1"  [cache hit: answer now, refresh in background > fetch > put (200)]
    request 3: from cache, status 200, body "v2"  [cache hit: answer now, refresh in background > fetch > put (200)]
       cache now holds: v2, network requests made: 3

    Cache first answers v1 forever with one request in total. Network first always shows the current value and always pays for a request. Stale while revalidate shows v1 on the second request, one behind the origin, and v2 on the third. It requests on every hit, as Workbox documents: it "will always make a revalidation request, regardless of the age of the cached response".

    Figure 3. Stale while revalidate, request by request

    sequenceDiagram accTitle: Stale while revalidate over three requests accDescr: The page asks for the product list. On the first request the cache is empty, so the worker waits for the network and stores version one. The origin changes to version two. On the second request the worker answers from the cache with version one and fetches version two in the background, storing it. On the third request the cache answers with version two. participant P as Page participant W as Service worker participant C as Cache participant N as Network P->>W: request 1 W->>C: match (miss) W->>N: fetch N-->>W: v1 W->>C: put v1 W-->>P: v1 Note over N: origin changes to v2 P->>W: request 2 W->>C: match (hit) W-->>P: v1 (now) W->>N: fetch (background) N-->>W: v2 W->>C: put v2 P->>W: request 3 W-->>P: v2 (from cache)

    How to read this: the page never waits for the network once the cache has an entry. The price is that every answer shows the previous fetch, not the current origin.

    Scenario 2 repeats the experiment offline, with only /api/products.json stored (as v1) and a second URL never stored:

    Expected output, captured from a real run (scenario 2, strategies three to five):

    -- cache first
    /api/products.json: from cache, status 200, body "v1"  [cache hit]
    /api/about.json: page gets a network error  [cache miss > fetch > network failed]
    -- network first
    /api/products.json: from cache, status 200, body "v1"  [fetch > network failed > cache hit]
    /api/about.json: page gets a network error  [fetch > network failed > cache miss]
    -- stale while revalidate
    /api/products.json: from cache, status 200, body "v1"  [cache hit: answer now, refresh in background > fetch > background refresh failed: old entry kept]
    /api/about.json: page gets a network error  [cache miss > fetch > network failed]

    Offline, a URL that was never stored fails under every strategy; the strategy only matters for a URL that was. Network first costs a failed attempt before it falls back. A failed background refresh keeps the old entry. Reasoning about offline behaviour starts with "what was stored, and when".

    The failure case: caching what should not be cached

    An HTTP error status is not a network error: MDN says fetch() does not reject for statuses such as 404 or 504, so a handler that stores every resolved response stores the error too. With cache first, nothing asks the network again.

    Illustration 3: a stored 500

    Scenario 4 in the lab: the origin answers 500 once, then recovers, with and without storing errors.

    Expected output, captured from a real run (scenario 4):

    -- storeErrors = false
    request 1: from network, status 500, body "internal error"  [cache miss > fetch > not stored (500)]
    request 2 (origin healthy again): from network, status 200, body "v1"  [cache miss > fetch > put (200)]
    -- storeErrors = true
    request 1: from network, status 500, body "internal error"  [cache miss > fetch > put (500)]
    request 2 (origin healthy again): from cache, status 500, body "internal error"  [cache hit]

    With errors stored, the visitor keeps seeing the 500 after the origin has recovered, and no network request is made to find out. The remedy is in the handler: store only responses you would be happy to serve later (the example above checks response.ok). The Workbox documentation lists the status codes cached by default for stale while revalidate and network first as 200 and opaque responses (cross-origin responses without CORS). Opaque responses have a cost of their own: web.dev notes they "don't expose their actual size in the storage API, affecting quotas".

    Keeping caches current

    Entries never expire, so freshness is something your code adds. Three usual tools:

    • Change the URL. Fingerprinted assets need no refresh: a new build means new URLs, and the old entries become unused.
    • Refresh on use. Stale while revalidate and network first re-fetch on requests, so the entry follows the origin.
    • Version the cache name and delete the old ones. MDN's service worker guide keeps the previous cache while pages controlled by the previous worker still need it, and removes it in activate, where a promise passed to waitUntil() blocks other events until the clean-up has finished. The lab's version of that step, scenario 5:

    Expected output, captured from a real run (scenario 5):

    before: shell-v1, shell-v2, images-v1, api-v1
    deleted: shell-v1, api-v1
    after:  shell-v2, images-v1

    The browser may also delete caches by itself. MDN says it "may delete the Cache storage for an origin" when managing disk space, and that it will generally delete all of the data for an origin or none of it. Treat the cache as an optimisation that may be empty, never as the only copy of anything (see Browser Storage Options and IndexedDB and Storage Quotas).

    Trade-offs

    Choice Gain Cost
    Cache first for fingerprinted assets No request, works offline Wrong for any URL whose content can change
    Network first Current when online, last copy offline A failed attempt before the fallback; slow networks feel slow
    Stale while revalidate Instant answers, entry stays close to the origin One request behind; a request on every hit
    Cache only No network at all Only what was stored at install; fails for the rest

    Build it

    The lab is examples/frontend/labs/sw-caching-strategies: the five strategies and a cache-name clean-up as pure functions, 22 tests, and a demo of five scenarios. It runs in Node with Vitest; no browser is involved.

    cd examples/frontend/labs/sw-caching-strategies
    ../../node_modules/.bin/vitest run
    node src/demo.ts

    Verified. The 22 tests passed (Node 26.13.1, Vitest 5.1.0), and the demo output above is a verbatim excerpt of examples/frontend/golden/sw-caching-strategies.txt. That proves the model does what this lesson says it does. It does not prove how a browser orders cache and network work inside a real fetch event, how fast either is, or what a quota does. The handler in Illustration 1 was not run.

    In practice: the product page

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The product page has a shell, fingerprinted scripts and styles, a product list (/api/products.json), prices and a cart. Returning visitors on slow connections wait for the list on every visit, and the team wants it instant and usable through a short loss of signal.

    Starting architecture

    Figure 4. One strategy for every request

    Starting architecture: one cache-first rule for everythingProduct page to Service worker; Service worker to Cache Storage (hit: answer); Service worker to Orders and product API (miss only)Product page: shell, list, cartProduct pageshell, list, cartService worker: cache first, all GETsService workercache first, allGETsCache Storage: never expiresCache Storagenever expiresOrders and product API: mutable dataOrders andproduct APImutable datahit: answermiss only

    How to read this: the warning boxes are where one rule is applied to data with different lifetimes. After the first visit the API is asked only when something is missing.

    Options considered

    Option What it fixes What it costs Risk
    Cache first for everything Fast, offline Nothing ever refreshes Old prices and old data shapes
    A strategy per kind of request Right answer per kind Routing code to maintain A route table that drifts from the real URLs
    Rely on HTTP cache headers only No worker to run No offline use A repeat visit may still wait on the network

    The decision

    Field Decision record
    Context Assets never change under a given URL; the list can be slightly old; prices and the cart cannot.
    Decision Cache first for fingerprinted assets, stale while revalidate for the product list, network first with a timeout for prices, network only for the cart and checkout, a versioned cache name and clean-up on activate, and store only ok responses.
    Consequences, good Instant repeat visits and a usable list offline; the cart never serves a cached price.
    Consequences, bad Four rules to keep in step with the URLs; the list is one request behind.
    Revisit when The list becomes personalised, or the response shape changes often.

    Rollout and verification

    1. Ship the route table behind a flag for a small share of visitors.
    2. Test each rule with the pure model first, then confirm in a real browser, in CI or by hand, that each URL gets its rule.
    3. Check the offline cases: a stored URL, a never stored URL, and an API that answers 503; after a 503, confirm the next request reaches the network.

    The 2 a.m. failure

    A release changes the shape of the product list. Returning visitors load new scripts (new fingerprints) but, under stale while revalidate, the first request after the deploy is answered with the old-shape JSON from the cache. The new code reads a field that is not there and the page shows a blank list until the next load.

    First three checks: (1) compare the JSON a failing visitor received with what the API returns now; (2) check whether the cache name changed with the release; (3) see which requests were answered by the worker. Mitigation: ship a worker with a new cache name so activation deletes the old entries, or make the API contract tolerate the old shape for one release. Follow-up: put the data version in the cache name or the URL, so scripts and data change together.

    Architect's notes

    • The strategy is a data-lifetime decision: write down how stale each kind of data may be first.
    • Fingerprint what you can, so "never refresh" is safe.
    • Store only what you would serve again, and decide what to do with opaque responses.
    • Version and clean up. Without a version key a cache goes stale; without clean-up it grows.

    Common mistakes

    • Cache first for mutable data. The entry never changes by itself.
    • Storing every resolved response. An HTTP 500 resolves too.
    • Caching a body already read. Clone first.
    • Forgetting waitUntil() on a background write.
    • No clean-up of old caches on activation.
    • Treating the cache as durable. The browser may delete it.

    Key takeaways

    • Five strategies: network only, cache only, cache first, network first, stale while revalidate. They differ in order, offline behaviour and freshness.
    • Cache API entries do not expire or update unless your code makes them.
    • Cache first suits fingerprinted assets; stale while revalidate suits data that may be one request old; network first suits data that must be current but should work offline; network only suits data that must never be stale.
    • Do not store error responses; clone before caching; use waitUntil() for background work.
    • Version cache names and delete old caches in activate.
    • The model in this lesson shows decisions, not browser behaviour.

    Practice exercises

    Exercise 1: Starter (30 min). Predict the three bodies each strategy serves in scenario 1 of the demo, then run node src/demo.ts and compare.

    Exercise 2: Intermediate (2 hours). Add a rule to the model that stores a response only for status 200 and test that a 204 and a 404 are not stored.

    Exercise 3: Advanced (half day). Write the route table for your own product page: URL pattern, strategy, allowed staleness and offline behaviour. Which rule breaks if the API changes shape?

    In this course:

    Next in this module, in plain text: the lessons on service workers, the service worker lifecycle and updates, and installable PWAs.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments