Skip to content

    Frontend System Design

    Service Workers

    Learn what a service worker is, how scope, install and fetch events work, why the browser can stop one at any time, and how to use one safely, with a lab.

    By Published 17 min read

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

    What you'll learn: By the end of this lesson you will be able to explain what a service worker is and what it cannot do, say why it needs a secure context, work out which requests a worker controls from its scope, describe the install, activate and fetch events and what waitUntil() and respondWith() are for, explain why a worker's variables do not survive while Cache Storage does, and decide when a service worker is worth its cost and when it is not.

    Picture a doorman at the front of an office building. Every parcel that comes in or goes out passes his desk. Most days he waves each one through. But he can also keep copies in the lobby: when a courier asks for the same brochure for the fortieth time, he hands over the copy instead of sending someone across town, and when the road is closed he can still hand over the last copy he has. He does not work in the offices upstairs and cannot touch their desks. He works from his own desk, and the building may send him home when nothing is happening.

    A service worker is that doorman for one website. It is a script that sits between a page, the browser and the network, sees the requests the page makes, and decides how to answer each one. MDN describes service workers as acting "as proxy servers that sit between web applications, the browser, and the network".

    The running example is a shop with product pages under /shop/ and an account area under /account/. The shop wants its pages to open quickly on a poor connection and to show something useful when the connection drops. The shop, its URLs and the numbers in its lab are made up for this lesson.

    The core idea

    Hold on to three statements.

    1. A service worker is an event-driven script with no page of its own. The browser starts it to handle an event (an install, a fetch, a push), and may stop it when it has nothing to handle. It cannot keep state in its variables.
    2. Its power comes from a scope. A worker registered for a path controls the pages and requests inside that path, and nothing else. It sees every request those pages make, including images and API calls, not only the page itself.
    3. Its memory is Cache Storage. Whatever a worker must remember between starts lives in a store the browser keeps for it, which a page can also read. The worker decides what goes in and what comes out.

    Three illustrations run through the lesson: a minimal example (a worker that precaches a shell and answers cache first), a realistic example (the shop's product pages with an offline page) and a failure example (a cache-first rule that serves a stock level that is no longer true).

    What a service worker is, and what it is not

    A service worker is a type of web worker. MDN says it "takes the form of a JavaScript file that can control the web page/site that it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion". Five facts shape everything else.

    • It runs in a worker context. It has "no DOM access and run[s] on a different thread to the main JavaScript that powers your app". It cannot read or change the page directly. It talks to pages by messages.
    • It is non-blocking. APIs such as synchronous XHR and Web Storage "can't be used inside a service worker". There is no localStorage in a worker. The store it uses is the asynchronous Cache Storage API. See Browser Storage Options for the page-side stores.
    • It is event-driven and promise-based. It does nothing until an event arrives, and it uses promises to say how long an event's work takes.
    • It needs a secure context. Service workers are only available when the page is served over HTTPS, although browsers treat http://localhost as secure for development. MDN gives the reason: plain HTTP is open to a manipulator in the middle, and such an attacker would be much more dangerous if they could install a worker that sits in front of every request.
    • Dynamic import() is not available inside a service worker. Static import statements are allowed.

    That last pair of facts explains the shape of the technology. A worker is powerful (it can answer any request in its scope) and long-lived (it stays registered until it is replaced or removed), so the platform confines it: HTTPS only, no direct page access, no blocking APIs.

    Registration and scope

    A page asks the browser to install a worker by registering it with the URL of the script:

    if ("serviceWorker" in navigator) {
      navigator.serviceWorker.register("/shop/sw.js");
    }

    The check first is feature detection, as MDN's examples do. The script URL is relative to the origin, not to the page that registers it.

    The scope decides what the worker controls. MDN states that "the default scope for a service worker is the directory where the worker is located", so a script at /js/sw.js controls URLs in or under /js/ by default. A scope option can narrow it. To make it wider than the script's directory, the server must send the Service-Worker-Allowed response header with the script, and without it, a registration that asks for a broader scope fails. MDN also warns that a worker intercepts all requests in its scope, so "you should avoid using overly-broad scopes unless necessary".

    Registration can fail for these reasons that MDN lists: the page is not in a secure context, or the scope option is broader than the worker path allows.

    Figure 1. A page, its worker and the two places an answer can come from

    A request from a page in scope goes to the service worker, which answers from Cache Storage or the networkPage to Service worker (fetch event); Service worker to Cache Storage (match, put); Service worker to Network (fetch)Page: under /shop/Pageunder /shop/Service worker: fetch handlerService workerfetch handlerCache Storage: named cachesCache Storagenamed cachesNetwork: origin serverNetworkorigin serverfetch eventmatch, putfetch

    How to read this: every request from a page inside the scope reaches the worker first. The worker chooses: answer from a cache, ask the network, or combine the two. A request from outside the scope never reaches it.

    The lab's inScope is a path-prefix test. With the scope /shop/, /shop/app.js and /shop/api/stock are in scope, while /account/orders is not. /shopping is not either, because the prefix is /shop/ with its trailing slash. Whether a real browser compares paths in exactly that way for odd cases was not checked for this lesson, so keep scopes simple and end them with a slash.

    The life of a worker, in three events

    A worker's life starts with a download and then three steps: install, activate and, from then on, fetch and other functional events. The next lesson in this course, Service Worker Lifecycle and Updates, covers what happens when a new version replaces an old one. This lesson covers the first version only.

    Figure 2. The first visit

    sequenceDiagram accTitle: First visit to a page with a service worker accDescr: The page registers a worker. The browser downloads the script and fires install. The worker opens a cache and adds the shell files, holding the install open with waitUntil. When the cache is filled the worker is installed and, being the first worker, activates without waiting. After that, fetch events from controlled pages reach the worker. participant P as Page participant B as Browser participant W as Service worker participant C as Cache Storage P->>B: register("/shop/sw.js") B->>W: download and start the script B->>W: install event W->>C: addAll(shell files), held open by waitUntil C-->>W: stored W-->>B: install complete B->>W: activate event (first worker: no waiting) Note over P,W: pages that loaded earlier stay uncontrolled until they reload P->>W: fetch event (a later page load) W->>C: match(request) C-->>W: hit W-->>P: respondWith(cached response)

    How to read this: install is where a worker prepares, activate is where it takes over, and only after both do controlled pages send it fetch events.

    Install. MDN calls install "always the first" event: it is emitted once, right after registration completes, and is usually used to fill a cache. The worker passes a promise to event.waitUntil(), which "ensures that the service worker will not install until the code inside waitUntil() has successfully occurred". If the promise rejects, "the installation fails, and the worker won't do anything": the browser discards the worker and the next registration tries again. Cache.addAll() is the usual precache call, and MDN's list of its error conditions includes a response outside the 200 range. One missing file in the list therefore fails the whole install.

    Activate. After install, the first worker of a registration "receives an activate event without waiting for open pages to close". Its main use, MDN says, is cleaning up resources of previous versions. Promises passed to waitUntil() here "block other events until completion", so the first fetch event arrives after the clean-up has finished.

    Fetch. From then on, a fetch event fires "every time any resource controlled by a service worker is fetched, which includes the documents inside the specified scope, and any resources referenced in those documents". The worker calls event.respondWith() with a Response or a promise for one. That "prevents the browser's default fetch handling". If it does not call it, the browser handles the request as it normally would.

    A page that loaded before the worker existed is not controlled. MDN: "a document starts life with or without a service worker and maintains that for its lifetime", so existing documents have to be reloaded to be controlled unless the worker takes them over with clients.claim(). The lifecycle lesson covers that.

    waitUntil() and respondWith()

    These two methods are the contract between a handler and the browser, and most worker bugs are a misunderstanding of one of them.

    Method On which events What it tells the browser If you get it wrong
    event.waitUntil(promise) install, activate, and functional events Work is still going on until the promise settles: do not stop the worker Install finishes before the cache is filled, or the worker is stopped before a cache write completes
    event.respondWith(responseOrPromise) fetch I will provide the response; skip the default handling Passing something that is not a Response gives the page a network error; a second call throws InvalidStateError

    MDN adds details for respondWith(): it accepts a Response or a promise for one, otherwise "a network error is returned to Fetch". The response type must fit the request mode: for instance, a "cors" response cannot be returned when the request's mode is "same-origin". And for waitUntil(), MDN says the first call must be made within the event callback, after which it can be called multiple times, "until all the promises passed to it settle". It states no time limit, so the lesson names none.

    Caching a network response is the case in which people forget waitUntil(). MDN's example does the cache write inside event.waitUntil() "to make sure the service worker doesn't terminate before the cache is populated", and clones the response first because "request and response streams can only be read once".

    What lives where

    The worker can be stopped. The specification says a user agent "may terminate service workers at any time it has no event to handle", and the browser can stop one that misbehaves. The next event starts the script again from the top. Variables are back to their initial values. Cache Storage entries stay: MDN says a cache's contents "are kept until you clear them". That is a statement about the API as MDN documents it, and the browser still manages storage as a whole, which the lesson on Browser Storage Options covers.

    Figure 3. What survives a stop

    A stopped worker loses its variables; Cache Storage and the registration remainRunning worker to Stopped (idle); Stopped to Cache Storage (kept); Stopped to Variables (lost)Running worker: variables in memoryRunning workervariables inmemoryStopped: no events to handleStoppedno events tohandleCache Storage: staysCache StoragestaysVariables: gone, reset on startVariablesgone, reset onstartidlekeptlost

    How to read this: anything a worker needs on its next start must be in Cache Storage (or another asynchronous store), not in a module-level variable.

    A counter in a global variable looks fine in testing, because the worker stays alive while a developer clicks around, and then it resets in production. Work that must finish also needs waitUntil(), or the browser is free to stop the worker before it ends. The event loop lesson explains the page's side of the same thread model; the Web Workers lesson explains how a dedicated worker differs: it exists for one page and lives as long as it.

    What the handler decides

    Once a request is in scope, the handler is a small decision procedure. The most common shape, and the one the MDN guide builds, is: look in the cache, and if there is nothing, ask the network, and if the network fails, return something.

    Figure 4. A cache-first fetch handler

    flowchart TD accTitle: A cache-first fetch handler accDescr: A request arrives. If it is outside the scope the browser handles it. If it is in scope, the handler looks in Cache Storage. A hit is returned. A miss goes to the network. A successful answer is returned and may be stored with waitUntil. A network failure returns an offline page if one is cached, otherwise an error response. R["Request"] --> S{"In scope?"} S -->|"no"| B["Browser handles it"] S -->|"yes"| M{"In Cache Storage?"} M -->|"yes"| H["Return the cached response"] M -->|"no"| N{"Network answers?"} N -->|"yes"| W["Return it, store a copy
    (waitUntil)"] N -->|"no"| O{"Offline page
    cached?"} O -->|"yes"| F["Return the offline page"] O -->|"no"| E["Return an error response"]

    How to read this: each diamond is a place where the worker can be wrong. The first two decide what the worker sees at all; the last two decide what a user sees when things go badly.

    This is one strategy among several. HTTP Caching for the Front End explains the browser's own cache that sits underneath. The lesson Service Worker Caching Strategies compares cache first, network first and stale while revalidate. This lesson is about the machinery, not the choice.

    Build it: a model of registration, install, fetch and stop

    Goal. Run a model of a service worker through five situations: registration rules, an install that succeeds and one that fails, a fetch handler answering from a cache, the network and a fallback, and a worker being stopped.

    This is a model, not a browser. Node cannot run a real service worker, and no browser is used for this lesson. The lab follows the rules listed at the top of src/model.ts and drives every event itself. It shows the shape of the rules, not how long a real browser keeps a worker alive or in what order it delivers events.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic.

    cd examples/frontend
    pnpm install
    cd labs/service-worker-model
    pnpm test           # 19 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo, and compare it with the output below.
    2. In section 1, find the row "scope / from /shop/sw.js": it is refused. The row after it, with the header, is accepted.
    3. In section 2, the install with one missing file ends redundant, and a request after that goes to the browser, not the worker.
    4. In section 3, compare the second request for /shop/api/stock with the first.
    5. In section 5, compare what the worker's memory and the caches hold after the stop.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01):

    Service workers: scope, install, fetch and idle termination (a model, not a browser)
    
    === 1. Registration: secure context and scope
    https, script /shop/sw.js      -> {"ok":true,"scope":"/shop/"}
    plain http on a real host      -> {"ok":false,"reason":"insecure-context"}
    http://localhost               -> {"ok":true,"scope":"/shop/"}
    scope / from /shop/sw.js       -> {"ok":false,"reason":"scope-broader-than-allowed"}
    scope / with the header        -> {"ok":true,"scope":"/"}
    scope /shop/cart/ (narrower)   -> {"ok":true,"scope":"/shop/cart/"}
    default scope of /shop/sw.js: /shop/
      /shop/app.js       in scope /shop/: true
      /shop/api/stock    in scope /shop/: true
      /account/orders    in scope /shop/: false
      /shopping          in scope /shop/: false
    
    === 2. Install: the worker is only as good as its precache
    all assets present:  installed=true, state=installed, shell-v1 holds ["/shop/index.html","/shop/app.js","/shop/offline.html"]
    one asset answers 404: installed=false, state=redundant, caches=[]
    request after the failed install   handled by browser        source network  status 200  "app code v1"
    
    === 3. Fetch: cache first for the shell, and the trap of caching live data
    /shop/app.js (precached)           handled by service-worker source cache    status 200  "app code v1"
    /account/orders (out of scope)     handled by browser        source network  status 200  "your orders"
    /shop/api/stock (first time)       handled by service-worker source network  status 200  "stock: 12"
    /shop/api/stock (server says 3)    handled by service-worker source cache    status 200  "stock: 12"
    worker fetch events handled: 3
    
    === 4. Offline: the shell works, the fallback answers, everything else errors
    /shop/app.js (precached)           handled by service-worker source cache    status 200  "app code v1"
    /shop/new-page (never cached)      handled by service-worker source fallback status 200  "You are offline"
    /account/orders (out of scope)     handled by browser        source error    status 0  "network error"
    
    === 5. Idle termination: global variables go, Cache Storage stays, waitUntil matters
    before: starts=1, fetchCount in memory=2
    two network responses to store; pending with waitUntil=1
    after:  starts=2, fetchCount in memory=0
    caches: ["shell-v1","runtime-v1"]
    runtime-v1 holds ["/shop/api/stock"] (the price write was never given to waitUntil)
    shell-v1 holds ["/shop/index.html","/shop/app.js","/shop/offline.html"]

    Three things to read in it. The out-of-scope request in section 3 never reaches the worker (worker fetch events handled: 3 counts the three in-scope ones). The stale stock: 12 is what cache first does to live data. And in section 5, the write that was not given to waitUntil() is lost when the worker stops.

    What the lab does not show. No real ServiceWorkerGlobalScope, no Request or Response objects, no HTTP cache, no headers, no streaming, no timing. When a real browser stops an idle worker is its decision. Cache.addAll() here stores nothing unless every response is ok; the MDN page lists a non-2xx response as an error but does not say what a real browser keeps after a failure.

    Break it. In src/model.ts, in terminate(), remove the loop that runs the work given to waitUntil before the worker stops. The test "finishes work given to waitUntil before stopping, and drops work that was not" fails, because the stock answer is no longer stored. Put the loop back and re-run the tests.

    Trade-offs

    Choice Gain Cost
    Precache the shell at install The shell opens with no network; first paint is local A larger first install; one missing file fails it
    Cache first for static files Instant answers, works offline Stale until the cache is rebuilt
    Cache first for API data Fast and offline The data can be wrong for as long as it stays cached
    A wide scope (/) One worker for the whole site It intercepts requests you did not plan for; a bug there affects every page
    A narrow scope (/shop/) Limited blast radius Pages outside are not helped and need their own worker
    No service worker No stale-copy bugs, no lifecycle to manage No offline support, no control over caching beyond HTTP headers

    In practice: product pages that open on a poor connection

    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

    A shop's product pages live under /shop/. Many visitors browse on trains and in shops with a weak signal. Product pages are server-rendered and then hydrated, and the first visit is fine. The second visit, on a train, often shows a blank tab for several seconds and then an error. The team wants the shell of the page to open at once and a clear "you are offline" page when the network is gone. The account and checkout areas under /account/ must always be live.

    Starting architecture

    Figure 5. Starting point: every visit depends on the network

    Starting architecture: every request from the product page goes straight to the networkProduct page to Browser HTTP cache (request); Browser HTTP cache to Origin (miss or stale)Product page: under /shop/Product pageunder /shop/Browser HTTP cache: headers decideBrowser HTTPcacheheaders decideOrigin: pages, assets, APIOriginpages, assets,APIrequestmiss or stale

    How to read this: the only control the team has over reuse is the response headers. With no signal there is nothing to reuse unless the file was cached by the browser earlier.

    Options considered

    Option What it fixes What it costs Risk
    Tune HTTP caching headers only Faster repeat visits for files that are cached Small Nothing is available when the cache entry is missing or stale and the network is down
    A service worker with a wide scope (/) Offline shell for the whole site One worker to maintain It sits in front of /account/ too, so a bug can break checkout
    A service worker scoped to /shop/, precached shell, offline page, network for API and account Offline shell and a friendly offline page, with the account area untouched A worker to ship and a cache to version Stale shell files after a release, covered in the lifecycle lesson

    The decision

    Field Decision record
    Context Product pages must open without a network on repeat visits; account and checkout must not be affected.
    Decision Register /shop/sw.js (default scope /shop/). Precache the shell and an offline page in install under a versioned cache name. Answer shell files cache first. Send /shop/api/ to the network and only fall back to the offline page for navigations.
    Consequences, good Fast repeat visits, a clear offline page, and a blast radius limited to /shop/.
    Consequences, bad A second cache to version, and the team must now think about what is stale.
    Revisit when Offline needs grow beyond a shell (see offline-first sync), or the account area needs offline support too.

    Rollout and verification

    1. Ship a pass-through worker first. One that only forwards requests is a safe first release; confirm the registration before adding cache logic.
    2. Precache only what a first paint needs, and check that the list matches the files the page asks for.
    3. Verify offline by hand with the developer tools' offline switch, and in the lab, by making the model's network go down.
    4. Watch error rates for /shop/ after each release, and compare them with the pages outside the scope.

    The 2 a.m. failure

    Support reports that the stock level on a product page said "12 left" for a day after the item sold out (illustrative). The worker's rule was cache first for everything under /shop/, which included /shop/api/stock. The first answer was stored, and every later request was served from the cache. This is section 3 of the lab.

    First three checks: (1) reproduce with the developer tools: does the request show as served by the service worker? (2) read the fetch handler for the URL: does it have a rule for the API path? (3) look at the cache name and contents for the stored response. Mitigation: ship a worker that sends /shop/api/ to the network and rolls the cache name forward so old entries are not used. Follow-up: write one test per URL class (shell, API, outside scope) and one rule per class in the handler, and review any new in-scope path before release.

    Architect's notes

    • Treat a service worker as a deployable with its own release process. It is long-lived code on every user's device.
    • Choose the scope as a boundary of risk. Start narrow, and widen only when you can name what you will intercept.
    • Write down, per URL class, how it is answered. "Cache first" is a decision for static files, not a default for everything.
    • Ask whether you need one. If the goal is faster repeat visits, HTTP caching headers may be enough, and a worker adds a second cache you now own.

    Common mistakes

    • Serving live data cache first because the rule was written for static files.
    • A global variable as state, which resets when the browser stops the worker.
    • No waitUntil() around a cache write, so the write can be lost.
    • One missing file in the precache list, which fails the whole install and leaves the page with no worker.
    • A broad scope for convenience, so a bug in the worker affects pages it was never meant for.

    Key takeaways

    • A service worker is an event-driven proxy script between a page, the browser and the network. It has no DOM and no Web Storage, and it needs HTTPS (or localhost).
    • Its scope is the directory of its script by default; a wider scope needs the Service-Worker-Allowed header.
    • Install precaches under waitUntil(); a rejected promise fails the install. Fetch handlers call respondWith(). A page that loaded without a worker stays uncontrolled until it reloads or the worker claims it.
    • The browser can stop an idle worker: variables are lost, Cache Storage stays.
    • Cache first is a good rule for static files and a trap for live data.
    • Decide per URL class, start with a narrow scope, and treat the worker as software with releases.

    Practice exercises

    Exercise 1 — Starter (45 min): In the lab, add a precache entry that does not exist and read the section 2 output. Then write a test that shows the page still gets /shop/app.js from the network after the failed install.

    Exercise 2 — Intermediate (2 hours): Add a rule so that /shop/api/ goes network first and falls back to a cached copy only when the network fails. Add one test for each of the three cases: network ok, network down with a cached copy, network down without one.

    Exercise 3 — Advanced (half day): Write a short design note for a site you know: list its URL classes, pick a scope, say how each class is answered, and name two things that could go stale. Then say what you would check at 2 a.m. if a user reported an old page.

    In this course:

    Planned lessons in this module, named here as plain text: Service Worker Lifecycle and Updates, Service Worker Caching Strategies, Installable PWAs, the Manifest and Push Notifications, Offline-First Sync and Conflict Resolution, and Offline Queues and Background Sync.

    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