Volume 2 Exercises: The Web FrontendPractice for Volume 2
0 / 0

Workbench / Volume 2 Exercises: The Web Frontend

V2·29

PWAs, Workers and WebAssembly

Exercises for Volume 2, chapter 29: what a progressive web app is; service workers in depth (lifecycle, updates, fetch handling); offline caching strategies; background sync; push notifications; IndexedDB for offline data; installability and the web app manifest; Web Workers, worker messaging and transferable objects; and WebAssembly: what it is, the text format and module structure, compiling C, C++, Rust, Zig and Go, the JS/Wasm boundary, and when to use it. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.

32 exercises · ~15 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

Same four sets and the same locking. The measured exercises use Chromium 153 through Playwright, against a local server that can change sw.js, slow down or break the API, and go offline. WebAssembly runs in Node 22, with modules compiled from the text format by wabt. Every quoted output is real. Four are worth knowing before you start:

  • P1: reloading the only open tab did not activate a waiting service worker.
  • P2: a "network-first" strategy passed a server's 500 straight through and then cached it, so it served that 500 again offline.
  • P6: after memory.grow, an existing Uint8Array view of Wasm memory became 0 bytes long, and writes to it were silently lost.
  • P5: an uncaught error inside a worker left the worker running, and the caller's promise never settled.

The chapter's lab ran a service worker through three visits (offline worked on the third), kept 60 fps with a worker (against 11 fps on the main thread), transferred 100 MB in 1.8 ms (against 659 ms to copy it), and found Wasm no faster than JavaScript for a floating-point loop but much faster for 64-bit hashing. The exercises build on those.

TiffinBox's partner portal runs on kitchen tablets with unreliable Wi-Fi. It's the running example for offline work.

Coverage map.

Chapter component Exercises
what a PWA is T1
service workers in depth: lifecycle, updates T2, P1
offline caching strategies T3, P2
background sync T4, P3
push notifications T4, P4
IndexedDB for offline data; storage quota T5, P3
installability and the manifest T1, P4
worker messaging T6, P5
transferable objects T6
what WebAssembly is; text format and module structure T7, P6
compiling C, C++, Rust, Zig, Go T8, P7
the JS/Wasm boundary T8, P6
when to use WebAssembly T9, P7

Theory

T1. What a PWA is

  1. Define a progressive web app: a website that uses service workers, a web app manifest and HTTPS to be installable, work offline or on poor networks, and integrate with the device (notifications, badges, share, file handling), while remaining a normal website. Which of these does the lab's experiment 1 show?
  2. Compare a PWA, a native app and a "wrapped" web app (Trusted Web Activity on Android, Capacitor) for TiffinBox's customers and for kitchen tablets: distribution, updates, offline, device APIs, iOS limitations, storage eviction, and cost.
  3. What makes a site installable in Chromium (manifest with name, icons, start_url, display; HTTPS; no longer a fetch-handler requirement), what does iOS/iPadOS support (Add to Home Screen, web push for installed apps since 16.4), and what manifest fields matter (id, scope, shortcuts, screenshots, share_target, display_override)?

T2. Service worker lifecycle and updates

  1. Walk through register → install → waiting → activate → controlling, and explain skipWaiting() and clients.claim(). The lab noted the first page wasn't controlled until clients.claim().
  2. P1 deployed v2 of sw.js (served with Cache-Control: max-age=86400) while a tab was open: registration.update() fetched it anyway, installed v2 (waiting: installed, caches shell-v1 and shell-v2), and reloading the only tab did not activate it; sending skipWaiting made it activate and fired controllerchange. Explain each observation, including why a reload doesn't help.
  3. Design the update UX for TiffinBox: detect a waiting worker, show "A new version is available", activate on the user's click, reload once after controllerchange, and avoid breaking an in-progress checkout. What can go wrong with unconditional skipWaiting()?

T3. Offline caching strategies

  1. Describe cache-first, network-first, stale-while-revalidate, network-only and cache-only, and assign one to each TiffinBox resource: the app shell, hashed JS/CSS, dish images, the menu API, order status, checkout POSTs, and the offline fallback page.
  2. P2 measured the strategies with the menu at v2 and the network 800 ms slow: cache-first answered in 3 ms with v1 both times (stale forever); network-first took 808 ms with v2; stale-while-revalidate answered in 4 ms with v1, then in 5 ms with v2 on the next request. When the server returned 500, network-first passed the 500 through (5 ms, status 500) and the cache inspection showed it had cached the 500, so offline it served the 500 again; cache-first and SWR served cached 200s. Explain the bugs and the fixes.
  3. How do cache versioning, expiration (max entries, max age), opaque responses (no-cors, which count heavily against quota), navigation preload, and Workbox help?

T4. Background sync and push notifications

  1. P3 found sync, periodicSync, pushManager and setAppBadge available in Chromium. Explain the Background Sync API (a one-off sync event when connectivity returns), Periodic Background Sync (installed apps, engagement-based), their browser support (Chromium only), and the fallback for Safari and Firefox (retry on the next app open or online event).
  2. Explain web push: the Push API (subscription with VAPID keys, the push service, encrypted payloads), the push event in the service worker, showNotification, permission UX (never prompt on page load: P3's headless permission was denied by default), and userVisibleOnly. Where does push fit for TiffinBox (order status updates, new-order alerts on kitchen tablets), and when is SSE enough?
  3. Design reliable "accept order" actions on a kitchen tablet that goes offline: queue in IndexedDB with idempotency keys, replay with background sync or on reconnect, and resolve conflicts (chapter 25's C2).

T5. IndexedDB and storage

  1. Why IndexedDB for offline data (structured, large, asynchronous, transactional, indexed) rather than localStorage (synchronous, string-only, ~5 MB) or the Cache API (HTTP responses)? Design the stores for the kitchen tablet: orders (by id, index on status and placed time), outbox, menu, and metadata (last sync time).
  2. P3's storage check in Chromium: usage 3 KB, quota 2.1 GB, persisted: false, and navigator.storage.persist() returned false. Explain quota, eviction (best-effort vs persistent), what makes browsers grant persistence (installed PWA, engagement, notifications permission), and Safari's limits on script-writable storage.
  3. How do you handle IndexedDB schema migrations (onupgradeneeded with versions), multiple tabs (versionchange/blocked), and the awkward raw API (wrappers like idb, Dexie)?

T6. Workers, messaging and transferables

  1. Compare dedicated workers, shared workers, service workers and worklets: lifetime, scope, use cases, and support.
  2. P5 measured: a classic worker took 7.6–10.7 ms from new Worker() to its first message; a module worker 13.4 ms; 10,000 concurrent request/response messages with id correlation completed in 82 ms; 1,000 sequential awaited round trips took 46 ms (about 46 µs each). An uncaught TypeError inside the worker's handler raised an error event on the main thread, the worker stayed alive, and the caller's request never got a reply. Explain how to design a worker RPC layer (ids, error replies, timeouts, cancellation, pools sized to hardwareConcurrency, which was 2 here).
  3. The lab: copying 100 MB took 659 ms; transferring 1.8 ms, leaving the sender's buffer detached (0 bytes). Chapter 27's P6 found that sending 300,000 objects blocked the main thread for 90 ms. Give rules for what to send to workers and how.

T7. What WebAssembly is, and its module structure

  1. Define WebAssembly: a portable, sandboxed, stack-based binary instruction format with linear memory, value types i32, i64, f32, f64, v128 (SIMD) and reference types; compiled by the browser ahead of execution; same security sandbox as JavaScript. What it isn't: a replacement for JavaScript or a way to access the DOM directly.
  2. P6 wrote a module in the text format (WAT) with an exported memory of 1 page (64 KiB), grow, sum and len functions; wabt compiled it to 146 bytes. Explain the module structure (types, imports, functions, memory, exports, data, start) and instantiation (WebAssembly.instantiateStreaming, compile caching).
  3. P6: after memory.grow(1) (which returned the old page count, 1), the old Uint8Array view had byteLength 0; writing through it had no effect (Wasm still saw the old sum, 6); re-creating the view made the write visible (sum 14). Why does growing memory detach views, and how do bindings (wasm-bindgen, Emscripten) cope?

T8. Compiling to Wasm and the JS/Wasm boundary

  1. Compare toolchains: C/C++ with Emscripten (libc, POSIX shims, generated JS glue) or clang --target=wasm32 without a runtime; Rust with wasm32-unknown-unknown + wasm-bindgen/wasm-pack; Zig (-target wasm32-freestanding); Go (GOOS=js GOARCH=wasm, large runtime, or TinyGo for small output); AssemblyScript (TypeScript-like). What affects output size (runtime, allocator, standard library, panics/formatting) and how to shrink it (-Os, wasm-opt -Oz, panic=abort, avoiding formatting)?
  2. P6 passed 100,000 short strings to a Wasm strlen: encoding each into memory and calling per string took 37.5 ms; encoding all at once and calling per string 11.3 ms. The lab: 10 million calls of add() from JS to Wasm took 28 ms vs 5 ms JS-to-JS. Explain boundary costs (calls, string encoding, copying, no inlining) and how to design a coarse interface.
  3. What is WASI and the Component Model (interfaces, wit files, strings and records crossing boundaries without hand-written glue), and why do they matter more for servers and plugins than for browsers today?

T9. When to use WebAssembly

  1. The lab: JS and Wasm tied on a floating-point Mandelbrot (149 vs 148 ms), Wasm beat clean BigInt JavaScript ~16× on 64-bit FNV-1a hashing and beat hand-optimised JS (13 ms vs 9 ms). List the situations where Wasm wins (64-bit integer math, SIMD, predictable performance, porting native libraries, CPU-heavy codecs) and where it doesn't (DOM-heavy UI, chatty calls, code V8 already optimises well).
  2. Evaluate Wasm for these TiffinBox features: client-side image compression before upload (kitchen photos), a PDF invoice generator, fuzzy search over 5,000 dishes, a route-time estimator for riders, and a spreadsheet-like menu planner.
  3. What are the costs of adopting Wasm (toolchain, build complexity, debugging, bundle size, team skills, CSP 'wasm-unsafe-eval'), and how do you decide?

Programming exercises

P1. Service worker updates, observed

Register a service worker that precaches the shell into shell-v1, deletes old shell-* caches on activate, and calls clients.claim(). Serve sw.js with Cache-Control: max-age=86400. Deploy v2 while a tab is open, call registration.update(), inspect the registration (active, waiting, installing) and cache names, reload the tab, then send skipWaiting from the page and listen for controllerchange. Build the "update available" banner.

P2. Compare caching strategies under bad networks

Implement cache-first, network-first and stale-while-revalidate for /api/menu in a service worker. Warm the caches, publish menu v2, make the network 800 ms slow, and record latency and version for two consecutive requests per strategy. Then make the server return 500 and go offline, and inspect what each strategy returns and what it left in the cache. Fix the bugs you find.

P3. Offline orders with IndexedDB, persistence and background sync

Build the kitchen tablet's offline store with idb (orders, outbox, meta), check navigator.storage.estimate() and persist(), and implement an outbox flushed by Background Sync where available and by online/app-open events elsewhere. Test with Playwright: go offline, accept three orders, come back online, and verify each operation was applied exactly once on the server. Record feature availability.

P4. Make the partner portal installable with push

Write the manifest (id, scope, start_url, display, icons including maskable, shortcuts for "Today's orders", screenshots, share_target for photos), check installability in DevTools (or via CDP's Page.getInstallabilityErrors), and implement web push for new orders: VAPID keys, subscription after a user action, a server sending with web-push, push and notificationclick handlers, and badging for the count of new orders.

P5. A worker RPC layer that handles errors

Measure worker start-up (classic and module), 10,000 pipelined messages, and 1,000 awaited round trips. Make the worker throw on one request and observe what happens to the worker and the caller. Then build an RPC layer with ids, error replies, timeouts, cancellation and a pool, or use Comlink, and test it.

P6. Wasm memory: growth, views and strings

Write a WAT module with an exported memory, a grow function, sum(ptr, len) and a null-terminated len(ptr). Compile it with wabt (or wat2wasm), instantiate it in Node or the browser, write bytes through a Uint8Array view, grow memory, and check the old view. Then pass 100,000 strings to len per string and in one batch, and compare.

P7. Is Wasm worth it for image compression?

Compress a 4000×3000 kitchen photo to a 1600 px wide WebP or AVIF in the browser before upload, three ways: canvas toBlob (browser encoder), a JavaScript encoder, and a Wasm codec (@jsquash/avif or @jsquash/webp, Squoosh's codecs) in a worker with OffscreenCanvas. Measure time on a throttled mid-range profile, output size and quality, main-thread blocking, and bundle cost. Decide.

P8. A Workbox-based service worker for the customer app

Replace a hand-written service worker with Workbox: precache the build's shell assets (injectManifest with revision hashes), StaleWhileRevalidate for the menu API with a broadcast update plugin, CacheFirst with ExpirationPlugin for images (max 200 entries, 7 days), NetworkFirst with a 3 s timeout for navigations plus an offline fallback page, NetworkOnly + BackgroundSyncPlugin for "add review" POSTs, and the update flow from P1. Write Playwright tests for offline navigation, stale menu updates and the update banner.

P9. Measure and shrink a Wasm module

Build the lab's FNV-1a 64-bit hash (or another integer kernel) in Rust with wasm-pack (or Zig/C), measure the .wasm size before and after opt-level = "z", lto = true, panic = "abort", wasm-opt -Oz, and compression; compare speed with the JavaScript BigInt and 16-bit-limb versions; and expose it through a worker with a coarse hash(buffer) API.

Cumulative projects (chapters so far: Volume 1, and Volume 2's 00, 12–29)

C1. An offline-first kitchen tablet app

Turn the partner portal's orders board into an installable, offline-first PWA for kitchen tablets: precached shell with a correct update flow (P1), caching strategies per resource (P2/P8), IndexedDB replica of orders updated by SSE (chapter 19), outbox with idempotent operations and conflict handling (P3, chapter 25's C2), push notifications for new orders when in the background (P4), persistent storage, a worker for CSV exports (P5), memory and leak checks for all-day sessions (chapter 27's P8), and accessibility of connection status and alerts (chapter 20). Test with network chaos for a simulated lunch rush.

Combines: browser storage (ch 17), real-time transports (ch 19), accessibility (ch 20), Angular or React (ch 22, 23), state and local-first (ch 25), testing (ch 26), performance and leaks (ch 27), security of service workers and push (ch 28) and this chapter.

C2. A PWA version of the customer app with safe caching

Make the customer site a PWA without breaking anything: manifest and install prompt (deferred beforeinstallprompt UX), a service worker that never caches personalised HTML or API responses in shared ways, cache-busting consistent with the HTTP cache and CDN (chapter 19's C1 and chapter 24's caching), offline fallback pages, Clear-Site-Data on logout (chapter 28), push for order status with permission asked in context, and RUM tracking of service-worker-served loads (chapter 27). Measure repeat-visit LCP and offline success rate.

Combines: HTTP caching and CDN (ch 19), full-stack framework caching (ch 24), state and server caches (ch 25), performance RUM (ch 27), security (ch 28) and this chapter.

C3. Move heavy client work off the main thread

Find the three heaviest main-thread tasks in the TiffinBox apps (menu search indexing, CSV import/export in the portal, photo resizing before upload) and move each to a worker (with Wasm where it's measurably better: P7, P9), using a shared RPC layer (P5), transferables, progress reporting, cancellation, and lazy loading of worker code. Verify with LoAF attribution and INP before and after (chapter 27).

Combines: JavaScript async and modules (ch 15), Web APIs (ch 17), performance measurement and LoAF (ch 27), UI architecture (ch 21) and this chapter.

What the chapter leaves out

Advanced device APIs for installed web apps

Chromium-based browsers (and some in Safari and Firefox) offer capabilities beyond the basics: the File System Access API and the Origin Private File System (fast file storage, usable with SQLite-in-Wasm), File Handling (open .csv files directly in the installed portal), Web Share and Web Share Target, Badging, Window Controls Overlay, WebUSB/WebSerial/WebHID/Web Bluetooth/Web NFC (kitchen printers and scanners on Android), Screen Wake Lock (keep the kitchen board on), Contact Picker, and WebGPU for compute. Check support (Project Fugu's API tracker) and design fallbacks.

SQLite and databases in the browser

SQLite compiled to Wasm (the official sqlite-wasm with OPFS persistence, or wa-sqlite) brings a real SQL database to the browser, used by local-first sync engines (ElectricSQL, PowerSync) and apps needing complex queries offline. It needs a worker (OPFS sync access handles are worker-only), careful schema migrations, and storage persistence (T5). PGlite runs PostgreSQL compiled to Wasm for local development and in-browser analytics.

WebAssembly threads, SIMD and GC

Wasm threads use shared memory (SharedArrayBuffer) and atomics across workers, requiring cross-origin isolation (chapter 28's P6); SIMD (v128) speeds up image, audio and ML kernels; Wasm GC (garbage-collected structs and arrays, shipped in major browsers in 2023–2024) lets managed languages (Kotlin, Dart/Flutter, Java via J2Wasm, OCaml) compile to Wasm without shipping their own garbage collector, making them practical for the web; exception handling, tail calls and memory64 round out the platform.

On-device machine learning

Running models in the browser uses WebAssembly (ONNX Runtime Web, TensorFlow.js Wasm backend), WebGPU (faster inference, Transformers.js), and the emerging WebNN API, plus built-in browser AI APIs being trialled in Chromium (summarisation, translation, prompt APIs with on-device models). Use cases for TiffinBox: classifying dish photos before upload, translating menu descriptions into Telugu or Hindi on device, or detecting blurry photos. Models are large (MBs to GBs), so lazy-load, cache, and check device capability.

Hybrid and cross-platform wrappers

Capacitor (and Cordova before it) wraps a web app in a native shell with plugins for device APIs and app-store distribution; Trusted Web Activities ship a PWA through the Play Store using Chrome; Tauri and Electron package web apps for desktop. These trade some web advantages (instant updates via the web, no store review) for native distribution and capabilities. For TiffinBox, a TWA for the kitchen tablets or Capacitor for a customer app are options to weigh against React Native (the mobile volume).

Senior exercises

S1. Decide PWA vs native for the kitchen tablet app

TiffinBox is rolling out 2,000 Android tablets to kitchens. Product wants reliable new-order alerts (even when the app is closed), offline order handling, a receipt printer over Bluetooth or USB, and fast updates. Compare an installed PWA, a TWA from the Play Store, Capacitor, and a native/React Native app. Recommend one, with risks and a pilot plan.

S2. Review a service worker pull request

A PR adds a service worker that: calls skipWaiting() and clients.claim() unconditionally; caches every GET response (including /api/me and /api/orders) cache-first in one cache named cache; never deletes old caches; caches cross-origin images with mode: 'no-cors'; responds to navigation requests with the cached / for every URL; and stores the auth token in IndexedDB for "offline login". Write the review.

S3. Decide whether to adopt WebAssembly for a feature

The partner portal wants an "auto-enhance dish photos" feature (exposure, white balance, sharpening, background blur) applied on the tablet before upload. Options: Canvas 2D filters in JS, WebGL/WebGPU shaders, a Wasm build of an existing C++ image library (with SIMD), or server-side processing. Decide with measurements to collect, costs and risks.

S4. Plan a storage and sync strategy that survives eviction

A kitchen's tablet was factory-reset by staff mid-shift; another's browser data was cleared by a "cleaner" app; a third ran out of disk and Chrome evicted site data. Each lost unsynced actions and the order board. Design a strategy that makes these events survivable: what's stored where, how fast data syncs, persistence and quota monitoring, recovery after data loss, and how staff are told.

S5. Teach the service worker lifecycle with one diagram and three bugs

Prepare a 20-minute session: the lifecycle diagram (install, waiting, activate, fetch, update), then three live bugs from this chapter: P1's "reload doesn't update", P2's "network-first caches a 500", and the lab's "first visit isn't controlled without clients.claim()". End with five rules.