The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S29 · V2·29

Keep Working Offline

Volume 2, chapter 29. A kitchen tablet loses Wi-Fi in the middle of lunch; until now the display went blank on reload and a tap failed with "check the connection". This stage adds a service worker that reopens the kitchen display from its last good copy (and never stores the Angular page, whose nonce must not be reused), an outbox in IndexedDB that keeps taps made offline with the Idempotency-Key they were first sent with, and a sender that replays them in order, once each, when the network or the live stream comes back. Registering a service worker under stage 28's Trusted Types needs one named policy, and the measured cases include a server that's down while navigator.onLine still says true.

6 parts · ~6 min to read
Updated Suggest a correction

Stage 29: keep working offline

The brief

What you'll build.

  • web-src/kitchen/outbox.ts: a queue of commands (URL, body, Idempotency-Key, order id, time) behind a three-method store: IndexedDB in the browser, a Map in tests; and drain(), which sends oldest first, stops at the first command that still can't get through, and drops (and reports) one the server refuses;
  • web-src/kitchen/sender.ts: send() posts as before when it can; when the server is unreachable, the browser knows it's offline, or taps are already waiting, the tap joins the queue; flush() drains, one run at a time;
  • web-src/kitchen/page-sender.ts: one sender per page for whichever view is on it; flushes on online, when the live stream reconnects, every 30 s while anything waits, and at start; shows "2 taps waiting to send";
  • web-src/sw/sw.ts → web/sw.js: network first for kitchen pages with the last good copy as fallback, stale-while-revalidate for scripts and styles, nothing else touched; the Angular page never stored;
  • web-src/kitchen/offline.ts: registration through a Trusted Types policy named sw that allows exactly /sw.js; the CSP's trusted-types 'none' becomes trusted-types sw;
  • tests: outbox.test.mjs (6) and suite/test_offline.py (4).

Why a real company needs this. A kitchen tablet sits next to a steel shelf and a microwave; Wi-Fi drops. If a tap fails, the cook taps again later (maybe twice), or forgets, and the customer's order sits "Placed" while it's being cooked. Software used where work happens has to keep working through short outages and catch up correctly afterwards, without doubling anything.

Why now. Chapter 29 is PWAs, service workers, offline storage, background sync, workers and WebAssembly. Stage 19 gave every tap an Idempotency-Key and stage 24 made the stream resumable, which is exactly what safe replay needs; stage 28 locked script URLs, which a service worker registration is.

What you'll have at the end.

  • a display that reopens offline and says it's reconnecting;
  • taps that are never lost and never applied twice;
  • ADR-0031: offline behaviour, and what TiffinBox deliberately does not do offline.

Theory to own

  1. The service worker lifecycle. What are install, activate and fetch, when does a new version take over, and what do skipWaiting and clients.claim change? (The chapter, "Service workers in depth"; Companion, Gaps 1.)
  2. Caching strategies. Which strategy for which resource, and what does each cost when the network is slow rather than absent? (The chapter, "Offline caching strategies"; Companion, Explain it differently 2.)
  3. Replaying writes. What makes a write safe to send again, and in what order? (Stage 19; Companion, Code walkthrough.)
  4. Knowing you're offline. What does navigator.onLine tell you, and what doesn't it? (Companion, Gaps 2.)
  5. Storage that lasts. When can the browser delete IndexedDB and Cache Storage? (Companion, Gaps 3.)

Build it

Step 1: the outbox, pure enough to test

Write outbox.ts: the Command type, the OutboxStore interface, memoryStore(), idbStore() (one object store, auto-increment key, so getAll() is in tap order; resolve writes on the transaction's complete, not the request's success), unreachable(e) (a TypeError from fetch or our own TimeoutError) and drain(). Write the tests against a fake server that applies each key once and refuses an event the order's state doesn't allow.

Checkpoint. Taps queued offline arrive in order; a 503 stops the drain and keeps the rest; a 409 is dropped and reported and the next one still goes; a key sent twice is applied once.

Step 2: one sender for every view

Write sender.ts and page-sender.ts. In send(): if the browser says it's offline, or the queue isn't empty, queue the tap and start a flush; otherwise call postCommand with a new key, and queue on unreachable. Replace postCommand in the plain view's click handler, React's Ticket and Angular's Ticket with pageSender(store, say).send(...); create the sender when each app starts, not on first tap. Show "Saved on this tablet: sends when the connection is back" on the card. On a successful flush, apply each returned order to the store.

Checkpoint. With the server stopped, a tap ends as "Saved on this tablet"; with it started, the order is accepted without another tap.

Step 3: the service worker, and Trusted Types

Write sw.ts with its own tsconfig.json (lib: ["ES2023", "WebWorker"], no DOM) and add it to check-js.sh. It must be a classic script: no import or export. Write offline.ts: create the sw policy, register /sw.js with updateViaCache: 'none', then post the page's own URL and its same-origin scripts and styles to the worker so the first, uncontrolled visit is stored too. Change the CSP to trusted-types sw.

Checkpoint. document.documentElement.dataset.sw is registered on all three views; a second load is controlled.

Step 4: what the worker stores, and the browser tests

Decide what's storable: /kitchen/kN (plain or React view) and same-origin .js/.css, never /sw.js, never ?view=angular, never the stream or POSTs. Write test_offline.py: each view reopens offline with its cards and a reconnecting line; the Angular page isn't stored; two taps offline are in IndexedDB in order and reach the server once each when the network is back.

Checkpoint. 4 passed; the whole suite still passes.

Senior and architect lens

1. Decide what works offline, and say what doesn't. The kitchen's taps queue; the customer's checkout doesn't. Placing an order commits money at a price that's confirmed by the server, and an order sent hours later would reach a kitchen that may be closed; the review form already carries its own key (stage 13), so trying again after a failure can't double an order. Stage 25's promise of a client-side checkout is closed this way, on purpose.

2. ADR-0031: offline behaviour. Write it with these points:

  • Offline: the kitchen display opens from its last copy and says it's reconnecting; taps queue in IndexedDB with their keys and replay in order; refused ones are reported.
  • Not offline: checkout, the Angular page (nonce), live data; nothing is shown as current that isn't.
  • Worker: one classic script, one cache per version, network first for pages, stale-while-revalidate for assets until stage 31; registered through the sw Trusted Types policy only.
  • Detection: a failed request, not navigator.onLine; flush on stream reconnect, online, a 30 s timer and start.
  • Limits: storage isn't persistent (persist() was refused in testing); a tablet cleared of site data loses its queue; Background Sync isn't used (Chromium only) — the page flushes while open, which is when a cook can see the result.

3. Replay safety is designed in the server, not the client. The outbox works because stage 19 made every event idempotent by key. A client queue in front of a server without idempotency would double every tap that was received but not acknowledged.

4. An offline queue changes what "now" means. A tap made at 12:05 and sent at 12:20 is recorded at 12:20. The command carries at; Volume 3 decides whether the server records the tap's time, the arrival time, or both (it should be both).

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
assets change on deploy stale-while-revalidate serves one old version per visit; old pages may meet new scripts stage 31 (hashed, immutable assets; atomic deploys)
two tablets in one kitchen, one offline its queued "accept" is refused because the other accepted; the cook sees a report here (drop and report); Volume 3 (conflict rules per event)
the queue's age a tap from yesterday replays this morning Volume 3 (server rejects events older than an order's state allows; client expiry)
storage cleared or evicted queued taps lost silently stage 32 (RUM reports queue length and losses)
no login a stored kitchen page is readable by anyone with the tablet Volume 3 (staff sessions; clear storage at logout)

Evidence

  • check-js.sh passes with outbox.test.mjs (37 JS tests); the worker compiles with worker types only.
  • test_offline.py passes (4 tests) and the whole suite passes (39 passed, 3 deselected).
  • The performance budgets: in this run React's update_long_tasks had a median of 1 against a budget of 0, and it was the same with stage 28's bundles on the same machine ([1, 1, 1] twice), so it's the machine, not this stage; the budget isn't raised (stage 27's rule), and stage 32 replaces a zero-tolerance count with a percentile from real devices.
  • The Trusted Types and server-down measurements are in the README.
  • 34 server tests pass with trusted-types sw in PagesTest.
  • ADR-0031 is committed.

Carry forward

  • sw.js is replaced in stage 31 by a worker that precaches hashed assets from the build's manifest.
  • The outbox reports its length to stage 32's RUM beacon.
  • pageSender is the one way any kitchen view sends a command.
  • The sw policy is the only Trusted Types policy; adding another needs a CSP change and a review.