Workbench / Volume 2 Companion: The Web Frontend
V2·29
PWAs, Workers and WebAssembly
Companion to Volume 2, chapter 29: how service workers, offline storage, workers and WebAssembly connect; new angles (a service worker as a receptionist with a filing cabinet, an outbox as a waiter's order pad, transferables as handing over a box instead of photocopying it); what the chapter simplifies, measured on the build's stage 29: register() refused under Trusted Types until a policy is named, navigator.onLine saying true for a server that was down, and storage that the browser wouldn't make persistent; the theory behind replaying writes; how Workbox's background-sync queue replays requests, and the line it draws that TiffinBox draws differently; four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 29 has three strands. Progressive web apps: what a PWA is, service workers and their lifecycle, caching strategies, background sync, push, IndexedDB and the manifest. Workers: messaging and transferable objects. WebAssembly: the module and its text format, compiling C, C++, Rust, Zig and Go to it, the JS/Wasm boundary, and when it pays.
The links worth remembering:
- All three exist because the page has one main thread and one network it doesn't control. A service worker handles the network's absence, a worker handles work too long for the main thread, and WebAssembly handles work too slow (or already written) in another language. Each is a separate execution context that talks by messages.
- Offline is a data problem before it's a caching problem. Caching the page is the easy half; what happens to a write made offline (where it's kept, in what order it's sent, what if it arrived already) is the hard half, and it rests on idempotency (chapter 19, stage 19).
- The boundary is the cost. Messages to a worker are copied unless transferred; calls into Wasm copy strings and arrays across; a service worker's cache is a copy that can go stale. Every gain here is paid for at a boundary, and the chapter's lab measures several.
Explain it differently
1. A service worker is a receptionist with a filing cabinet. Every request from the office goes through the receptionist. When the phone line is down, the receptionist answers from the cabinet (yesterday's copy of the menu board) and says so. The receptionist isn't in the room with the staff: they talk through a hatch (postMessage), and the receptionist can be replaced overnight while the staff are still working from yesterday's instructions (the lifecycle).
2. Caching strategies are how fresh you need the newspaper. Network first: go to the shop, and read yesterday's copy only if the shop is closed (the kitchen display). Stale-while-revalidate: read yesterday's copy now and fetch today's for tomorrow (scripts and styles). Cache first: the encyclopedia, which never changes (hashed assets in stage 31). Network only: the live scoreboard (the stream). A slow shop is the hidden cost of network first: you stand at the door waiting.
3. An outbox is a waiter's order pad when the kitchen printer is down. The waiter writes each order on the pad in sequence and hands the pad over when the printer is back. Each slip has a number; if the kitchen already has slip 14, a second slip 14 is thrown away (the Idempotency-Key). And the waiter never hands over slip 15 before slip 14.
4. navigator.onLine is the "Wi-Fi connected" icon, not proof the internet works. The icon says the tablet has a network; it doesn't say the router has internet, or that the server is up (Gaps 2).
5. A worker is a second cook with their own station. They can't touch your chopping board (the DOM). You pass them ingredients through the hatch. Passing a photocopy of a recipe is slow for a big book; handing the book itself over (a transfer) is instant, but then you no longer have it.
6. WebAssembly is a sealed kitchen appliance. It does one job fast and safely, with its own sealed memory. Food goes in and comes out through a fixed opening (the boundary), and if the job is mostly carrying food back and forth, the appliance doesn't help.
7. Persistent storage is a reserved table. Without a reservation, the restaurant may clear your table when it's busy (eviction under storage pressure). The browser decides who gets reservations (Gaps 3).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from Chromium 153 headless and the build's stage 29 (exp/29), unless stated.
1. Registering a service worker is a script-URL sink. The chapter shows navigator.serviceWorker.register('/sw.js') as a one-liner. Under stage 28's Trusted Types policy it fails; with a policy that isn't allowed by the CSP, the policy can't even be created:
trusted-types 'none': {'string': "TypeError: Failed to execute 'register' on 'ServiceWorkerContainer': This document requires 'TrustedScriptURL' assignment", 'policy': 'TypeError: Failed to execute \'createPolicy\' on \'TrustedTypePolicyFactory\': Policy "sw" disallowed.', 'other': 'TypeError'}
trusted-types sw: {'string': "TypeError: Failed to execute 'register' on 'ServiceWorkerContainer': This document requires 'TrustedScriptURL' assignment", 'policy': 'registered', 'other': 'TypeError'}
A plain string is refused either way; only a value from the policy named in the CSP works, and a second policy (other) is still refused. The same applies to new Worker(url) and importScripts, so a site that adopts Trusted Types must list a policy for each kind of worker it starts, and keep each policy narrow: stage 29's accepts exactly /sw.js. Adopt Trusted Types first and workers later, and the error tells you; the other way round, and turning Trusted Types on breaks offline support with an error in a code path that only runs once per install.
2. navigator.onLine doesn't mean the server is reachable. The chapter's offline examples switch the browser offline, which sets navigator.onLine to false. Stage 29 stopped the server instead and left the network up, then tapped Accept:
navigator.onLine: True
71 ms waiting 0 min
95 ms Retrying (network error), attempt 2…
235 ms Retrying (network error), attempt 3…
375 ms Saved on this tablet: sends when the connection is back
server back: the outbox was empty 5539 ms later; live line 'Live'; order status: Accepted
The browser said it was online throughout. The only way to know the server was unreachable was to try (three tries in 375 ms), and the only reliable sign it was back was a request succeeding: the live stream reconnecting (its back-off explains the 5.5 s) triggered the flush, not the online event, which never fired because the network never went away. A dead router, a captive portal, DNS failure and a server deploy all look like this. So onLine === false is useful (skip the retries, queue at once), and true means nothing.
3. Offline storage is best effort unless the browser says otherwise. The chapter treats IndexedDB as the place for offline data. In the same headless Chromium:
{'quotaGB': 2, 'usageKB': 78, 'persisted': False, 'persist': False, 'sync': True, 'periodicSync': True, 'version': 'Chrome/153.0.8010.12'}
navigator.storage.persist() returned false: Chromium grants persistence from its own signals (an installed app, engagement, a bookmark), and a fresh profile has none. Without it, the origin's IndexedDB, Cache Storage and the service worker can all be evicted together under storage pressure, and users can clear them. So a queue of unsent taps must be drained as soon as possible, its loss must be survivable (the cook sees the order wasn't accepted), and stage 32 reports queue lengths so losses become visible. Background Sync is present (sync: True), but only in Chromium-based browsers, which is why stage 29 flushes from the page, while the cook can see it.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Registering a service worker is one line." | Under Trusted Types it needs a policy the CSP names. | Gaps 1 |
"navigator.onLine tells you if requests will work." |
It stayed true with the server down. |
Gaps 2 |
| "IndexedDB is permanent." | Without persistence it can be evicted; persist() was refused. |
Gaps 3 |
| "A queued request can just be sent again." | Only if the server makes it idempotent, and only in order. | Code walkthrough; drill D2 |
"fetch rejects on an error response." |
It rejects only when there's no response; a 404 resolves. | Code walkthrough |
| "Cache the whole site and it works offline." | Pages with per-response secrets (nonces) must never be stored. | Drill D4 |
| "WebAssembly is faster than JavaScript." | Only for compute-bound work that doesn't cross the boundary much. | The chapter's lab, Experiment 4 |
Theoretical gaps: the ideas behind the chapter
1. Store-and-forward. Email, SMS and message queues all accept a message while the next hop is down, keep it durably, and forward it later. An outbox is store-and-forward inside the client. Its guarantees are the classic ones: at-least-once delivery (resend until acknowledged), made effectively-once by deduplication at the receiver.
2. Idempotency and sequence. An operation is idempotent if applying it twice equals applying it once; a key turns any command into one by remembering results. Order is a separate property: idempotency doesn't make "ready" before "accept" valid. Queues that guarantee order per key (per order id) and not globally are the usual compromise; one tablet's FIFO queue is the simplest case of it.
3. Offline-first and local-first. Offline-first treats the network as an enhancement: the local copy is read first and synchronised later. Local-first goes further: the user's device holds the primary copy, and replicas merge (often with CRDTs). TiffinBox's kitchen is deliberately neither: the server is the authority, and the tablet only queues requests for it to decide.
4. The CAP view of a tablet. Offline is a network partition. A kitchen tablet that keeps accepting taps chooses availability; the server's 409 for a tap that conflicts is how consistency is restored afterwards, with a person resolving it.
5. Amdahl's law, for workers and Wasm. Speeding up a part of the work by moving it to a worker or Wasm helps only by that part's share of the total; the boundary's copying is serial work added back. That's why the chapter's lab finds Wasm slower for small inputs.
Applying it
Code walkthrough
TiffinBox's outbox does what Workbox's background-sync module does: keep failed requests in IndexedDB and replay them later. Reading Workbox shows the same problem solved for any site, and one decision made differently. Excerpts from workbox-background-sync 7.3.0, Queue.js, installed from npm.
Replaying the queue
async replayRequests() {
let entry;
while ((entry = await this.shiftRequest())) {
try {
await fetch(entry.request.clone());
// (development-only logging removed)
}
catch (error) {
await this.unshiftRequest(entry);
// (development-only logging removed)
throw new WorkboxError('queue-replay-failed', { name: this._name });
}
}
}
Each entry is taken off the front of the queue first (shiftRequest), then sent; if fetch throws, it's put back at the front (unshiftRequest) and the replay stops, so order is kept, as in stage 29's drain. Two differences. First, if the browser stops the service worker between the shift and the unshift, that entry is gone; stage 29 removes a command only after the server answered, so the worst case is a repeat, which the key absorbs. Second, look at what counts as failure: only fetch throwing. And fetch throws only when there's no response at all:
server up : resolved: 404 no such order
offline : rejected: TypeError: Failed to fetch
So for Workbox's default replay, a 500 or a 409 is "replayed successfully" and leaves the queue. Workbox lets you pass your own onSync to decide; stage 29's drain makes the decision explicit: 5xx, 408 and 429 wait and keep their place; other 4xx are dropped and reported to the cook.
Asking the browser to call back later
async registerSync() {
// See https://github.com/GoogleChrome/workbox/issues/2393
if ('sync' in self.registration && !this._forceSyncFallback) {
try {
await self.registration.sync.register(`${TAG_PREFIX}:${this._name}`);
}
catch (err) {
// This means the registration failed for some reason, possibly due to
// the user disabling it.
}
}
}
With Background Sync, the browser fires a sync event in the service worker when it believes there's connectivity, even after the page is closed, and retries a failed sync with back-off (event.lastChance marks the last try). Without it (Firefox, Safari), Workbox falls back to replaying when the service worker starts. Stage 29 does neither: the page flushes on the stream reconnecting, on online, every 30 s and at start, because a cook needs to see the result on the card, and a kitchen tablet's display is always open.
What gets stored with the request
async _addRequest({ request, metadata, timestamp = Date.now() }, operation) {
const storableRequest = await StorableRequest.fromRequest(request.clone());
const entry = {
requestData: storableRequest.toObject(),
timestamp,
};
The whole request (URL, method, headers, body) is stored, so an Idempotency-Key header set by the page survives into the replay; a key generated by the service worker at replay time would be new every time and protect nothing. The timestamp drives maxRetentionTime (7 days by default): older entries are discarded, not sent. Stage 29 keeps at but doesn't expire yet (the table in stage 29's lens gives it to Volume 3).
Debugging drills
D1. Offline reload shows the browser's error page
The worker is registered (dataset.sw says so), but the first offline reload of the kitchen display fails with ERR_INTERNET_DISCONNECTED. The second time it works.
D2. Back online, one order ends up "Not done"
Offline, a cook accepted order o1, and a minute later tapped Ready on a second tablet that had been online all along. Back online, the first tablet reports "a tap made offline was not done: order o1 is Accepted". In another version of the code, a single tablet that tapped Accept offline and Ready after the network came back got the same message for Ready.
D3. "ServiceWorker script evaluation failed"
register() rejects with Failed to register a ServiceWorker … ServiceWorker script evaluation failed. The file is served with the right type and loads fine in the Network panel.
D4. A security review flags the cache
A reviewer finds /kitchen/k7?view=angular in Cache Storage on one tablet, from an earlier version of the worker that stored every kitchen page.
Career-oriented
Interview prep
Mid-level 1: which caching strategy for what?
Question. "Your web app should work offline. Which caching strategy do you use for the HTML, the JS and CSS, the API data, and images?"
How to get there. Go resource by resource: how fresh must it be, and what happens if it's stale? Then mention slow networks and how versions change.
Mid-level 2: what happens when you deploy a new service worker?
Question. "You deploy a new sw.js. When do users get it, and what can go wrong?"
How to get there. Walk the lifecycle: the update check, install, waiting, activate. Then the two shortcuts and their risk.
Senior 1: design the offline queue
Question. "Field staff use a web app on tablets with patchy connectivity. Design how their actions are kept and sent."
How to get there. Start with what must be true (nothing lost, nothing doubled, order kept), then storage, keys, ordering, failure handling, and what the user sees.
Senior 2: workers or WebAssembly?
Question. "A feature freezes the page for 800 ms while it processes a 20 MB file. A colleague proposes rewriting it in Rust and compiling to WebAssembly. What do you do?"
How to get there. Separate the two problems: the page freezing (where the work runs) and the work being slow (how fast it is). Measure before choosing.
Staff 1: PWA or native for a fleet of devices
Question. "Your company has 2,000 shared tablets in restaurants. Product wants offline support and push. Should the app stay a PWA or become native?"
How to get there. Talk about who manages the devices, what the platform guarantees, and what each option costs over years.
Staff 2: an offline data policy across teams
Question. "Several teams now cache data in browsers for offline use. What standards do you set?"
How to get there. Security, privacy, correctness and operability, each with a concrete rule.