Workbench / Volume 2 Companion: The Web Frontend
V2·17
The DOM and Browser APIs
Companion to Volume 2, chapter 17: how the DOM, networking and storage, and real-time APIs connect; new angles (the DOM as a live switchboard, delegation as one receptionist for a whole floor, observers as subscriptions instead of patrols, a service worker as a restaurant's own delivery desk); what the chapter simplifies, measured in Chromium: six open event streams that freeze every other request to the server on HTTP/1.1 (and don't on HTTP/2), an `EventSource` that gives up for good after one 503, twenty displays reconnecting in the same second after a restart, and a countdown that's four minutes wrong because the tablet's clock is; the theory behind it; how `@microsoft/fetch-event-source` is written (and why its parser hands you empty messages for keep-alives); four debugging drills; interview questions with how to approach each.
Understanding it better
Concept map
Chapter 17 has three strands. The DOM: finding elements, changing the tree safely, events with capture and bubbling, delegation, and observers (mutation, intersection, resize, performance). Networking, navigation and storage: fetch and URLs, history and the Navigation API, the clipboard and Web Crypto, IndexedDB, Cache Storage, and files. Concurrency and real time: Web Workers, service workers, WebSocket, Server-Sent Events, BroadcastChannel and notifications.
The links worth remembering:
- Events flow through the tree, so one listener can serve many elements. Bubbling is what makes delegation work, and delegation is what makes lists of thousands of items cheap to wire up and safe to re-render.
- Observers replace polling. Instead of checking on every scroll or every frame, you subscribe and the browser tells you, batched and off the hot path.
- Every real-time API is a long-lived connection, and connections are a shared, limited resource (Gaps 1). Choosing SSE, WebSocket or polling is also choosing how many connections, through which proxies, with what reconnection behaviour.
Explain it differently
1. The DOM is a live switchboard, not a printout. Changing a node changes what's on screen, what screen readers announce and what other scripts see, immediately. Reading layout properties (offsetHeight) asks the browser to finish all pending changes first, which is why reading and writing in alternation is slow (Chapter Exercises P3 and C3).
2. Event delegation is one receptionist for a whole floor. Instead of a doorbell on every desk, visitors announce themselves at reception, which looks at the name on the visitor's card (event.target.closest('[data-order-id]')) and calls the right desk. Desks can be added or removed without rewiring anything.
3. Observers are subscriptions, not patrols. A scroll listener checking whether a card is visible is a guard walking the corridor every few milliseconds. An IntersectionObserver is a motion sensor: silent until something crosses the line.
4. A service worker is the restaurant's own delivery desk. Every request from the page passes the desk, which can answer from the pantry (cache), send it on to the kitchen (network), or both. It outlives any single page and must be updated carefully, because the old desk keeps working until every page using it has closed.
5. IndexedDB transactions are a till that closes itself when you walk away. A transaction stays open only while you keep giving it work in the same turn of the event loop. Go to fetch something mid-transaction (await fetch), and the till closes behind you; the next write fails.
6. SSE is a radio station; WebSocket is a phone call. The station broadcasts and the receiver retunes automatically after interference (reconnection with Last-Event-ID). A phone call is two-way, but if it drops, you have to call back and work out what you missed yourself.
7. BroadcastChannel is the kitchen's intercom between rooms. Every tab of the same origin on that channel hears a message at once. It doesn't cross devices, and nothing is stored: a tab that opens later hears nothing about what was said before.
8. The browser's clock is the customer's watch, not the restaurant's. Date.now() on a kitchen tablet is whatever that tablet thinks the time is. Anything computed from it (countdowns, "late" flags) is only as right as the tablet (Gaps 4).
Gaps and misconceptions
What the chapter oversimplifies
All outputs are real, from Chromium (Playwright) against small Node servers in exp/17.
1. "SSE is plain HTTP": and HTTP/1.1 allows six connections per origin. Each open EventSource holds a connection for as long as it's open. Browsers allow six HTTP/1.1 connections per origin, shared by every tab of that origin in the same browser profile. Opening tabs that each keep an event stream, and timing a fetch from another tab:
http/1.1: 1 tab(s) with an open EventSource -> fetch from another tab: 4 ms
http/1.1: 5 tab(s) with an open EventSource -> fetch from another tab: 3 ms
http/1.1: 6 tab(s) with an open EventSource -> fetch from another tab: no answer in 4 s
tab 7 can't even load its page in 4 s
h2: 6 tab(s) with an open EventSource -> fetch from another tab: 8 ms
h2: 7 tab(s) with an open EventSource -> fetch from another tab: 3 ms
With six streams open, every other request to that origin queues behind them: API calls, images, and new pages. A kitchen manager with the display open in six tabs (one per station) freezes their own app. HTTP/2 multiplexes all streams over one connection, so the same test over TLS with h2 (the nextHopProtocol the browser reported) has no limit in sight. Serve event streams over HTTP/2, or share one stream between tabs (a SharedWorker, or one leader tab relaying over BroadcastChannel) (drill D1).
2. "EventSource reconnects automatically": unless the server answers with anything but a 200 event stream. After a dropped connection, the browser reconnects. If the reconnection gets an HTTP error (a 503 during a deploy) or the wrong content type, the specification says to fail the connection: readyState becomes CLOSED (2) and it never tries again:
drop, server fine: ['0s open', '1s error (readyState 0)', '4s open'] | final readyState 1 | reconnect attempts seen by the server: 1
drop, server answers 503 for 10 s: ['0s open', '1s error (readyState 0)', '4s error (readyState 2)'] | final readyState 2 | reconnect attempts seen by the server: 1
In the second case the server was healthy again after 10 s, and the display stayed disconnected forever: one attempt, then nothing. A load balancer answering 502 for a few seconds during a rolling deploy silently kills every kitchen display it touches. The client must watch for readyState === EventSource.CLOSED in onerror and create a new EventSource itself, with back-off (drill D2).
3. Reconnection is synchronised: every display comes back at the same moment. Without a retry: field, Chromium waits a fixed 3 s. Twenty displays, one server restart:
retry none : 20 reconnects, from 3.0 s to 3.0 s after the drop; busiest second had 20
retry jitter: 20 reconnects, from 4.1 s to 10.0 s after the drop; busiest second had 4
All twenty reconnected within the same tenth of a second. With 2,000 displays, a restarting server receives 2,000 connections (each re-sending Last-Event-ID and asking for missed events) in its first seconds, the moment it's least able to cope. Sending each client a random retry: (here 2–10 s) spreads them out. Chapter Exercises P9 sends a fixed retry: 300, which resynchronises everyone just as well (drill D3).
4. Times from the server, countdowns from the client's clock. The chapter computes durations in the browser. A tablet's clock can be minutes off (no network time sync, a manually set clock, a dead battery). The same "promised at 09:30" order, shown at 09:00 server time on three tablets:
tablet clock +0 min: naive: due in 30 min | server-relative: due in 30 min
tablet clock -4 min: naive: due in 34 min | server-relative: due in 30 min
tablet clock +7 min: naive: due in 23 min | server-relative: due in 30 min
The naive countdown (promisedAt - Date.now()) is wrong by exactly the clock error; on the fast tablet, orders would turn "late" seven minutes early. Measure the offset once per response from the server's Date header (or a serverTime field) and compute promisedAt - (Date.now() + offset); use performance.now() for elapsed time on the device itself, which isn't affected by clock changes (drill D4). The experiment uses Playwright's page.clock, which makes time-dependent UI testable without waiting.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Each tab has its own connections." | Six HTTP/1.1 connections per origin are shared by all tabs in a browser profile. | Gaps 1; drill D1 |
"EventSource always reconnects." |
Not after an HTTP error or a wrong content type: it closes for good. | Gaps 2; drill D2 |
| "Reconnecting clients spread out naturally." | They reconnect after the same fixed delay, all at once. | Gaps 3; drill D3 |
"Date.now() is the time." |
It's the device's clock, which may be minutes off. | Gaps 4; drill D4 |
"Every SSE library behaves like EventSource." |
Libraries differ in retrying, back-off, and even in what counts as a message. | Code walkthrough |
Theoretical gaps: the ideas behind the chapter
1. Connection limits exist to protect servers from browsers. HTTP/1.1 can carry one request at a time per connection, so browsers open several in parallel; the limit of six per host is a convention to stop one page from overwhelming a server. HTTP/2 replaced it with stream multiplexing over one connection (with a much higher limit on concurrent streams, negotiated by the server), and HTTP/3 does the same over QUIC without TCP's head-of-line blocking. Long-lived streams are where the difference stops being theoretical (Gaps 1).
2. Liveness needs failure detection, and failure detection needs timeouts. An idle TCP connection that's been cut by a NAT box or a sleeping Wi-Fi radio looks open to both ends. Keep-alive comments every 10–30 s let both sides notice (the server's write fails; the client can watch for silence). Every real-time system, from SSE displays to distributed databases (Volume 3), has the same two parameters: how often to send heartbeats, and how long silence means death.
3. Retry policies are a shared-resource problem. One client retrying quickly is fine; a thousand doing it in lock-step is a denial-of-service attack on your own server. Exponential back-off with jitter (randomness) is the standard remedy, analysed by AWS's "Exponential Backoff and Jitter" (2015): full jitter (a random delay between zero and the back-off ceiling) spreads load best. The same applies to every retrying client in stages 19 and 29.
4. Clocks are local; time is a protocol. There's no global "now"; each device has its own clock that drifts and gets corrected. Systems agree on time by exchanging it (NTP), or avoid needing agreement by computing in one place (the server stamps promisedAt; clients compute relative to the server's clock). Elapsed time on one device should use a monotonic clock (performance.now(), Java's System.nanoTime()), which never jumps when the wall clock is corrected (Volume 1, stage 5's backwards-time bug).
5. The browser is an operating system with permissions. Notifications, clipboard reads, geolocation, wake locks and persistent storage all require a user gesture or a permission grant, can be revoked at any time, and behave differently in background tabs. Code that uses them has to handle "no" and "not any more" as normal outcomes, the way a server handles a refused connection.
6. Background tabs are throttled by design. Browsers slow timers in hidden tabs (to once a second, and to once a minute after a while in Chromium's intensive throttling), freeze some pages entirely, and may discard them. An always-on display must not rely on timers in a hidden tab; it should hold the screen awake and react to visibilitychange, and any countdown must be recomputed from timestamps rather than from counting ticks.
Applying it
Code walkthrough
EventSource can't send custom headers, can't use POST, and gives up on HTTP errors (Gaps 2). @microsoft/fetch-event-source reimplements SSE on top of fetch to get around all three. Excerpts from version 2.0.1 (lib/esm/fetch.js and parse.js, installed from npm).
The retry loop
const DefaultRetryInterval = 1000;
const LastEventId = 'last-event-id';
...
async function create() {
var _a;
curRequestController = new AbortController();
try {
const response = await fetch(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
await onopen(response);
await getBytes(response.body, getLines(getMessages(id => {
if (id) {
headers[LastEventId] = id;
}
else {
delete headers[LastEventId];
}
}, retry => {
retryInterval = retry;
}, onmessage)));
onclose === null || onclose === void 0 ? void 0 : onclose();
dispose();
resolve();
}
catch (err) {
if (!curRequestController.signal.aborted) {
try {
const interval = (_a = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a !== void 0 ? _a : retryInterval;
window.clearTimeout(retryTimer);
retryTimer = window.setTimeout(create, interval);
}
catch (innerErr) {
dispose();
reject(innerErr);
}
}
}
}
Three design decisions are visible. Every failure goes to the catch and schedules a retry, including the default onopen's check of the content type (which throws), so a 503 during a deploy is retried rather than fatal, the opposite of EventSource. The retry interval is fixed (1 s, or the server's retry:), unless your onerror returns a number, so back-off and jitter are your job (Gaps 3). And Last-Event-ID is kept as a request header, updated as ids arrive, so a reconnect resumes where it left off. Notice also that when the stream ends normally (the server closes it), the promise resolves and nothing reconnects: a server that closes streams periodically needs onclose to throw.
A detail above this excerpt: unless openWhenHidden is set, the library closes the stream when the tab is hidden and reopens it when visible (a visibilitychange listener aborts and recreates the request). That saves server connections and battery for most pages, and is exactly wrong for a kitchen display left behind another window.
The parser
export function getMessages(onId, onRetry, onMessage) {
let message = newMessage();
const decoder = new TextDecoder();
return function onLine(line, fieldLength) {
if (line.length === 0) {
onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
message = newMessage();
}
else if (fieldLength > 0) {
const field = decoder.decode(line.subarray(0, fieldLength));
const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
const value = decoder.decode(line.subarray(valueOffset));
switch (field) {
case 'data':
message.data = message.data
? message.data + '\n' + value
: value;
break;
getLines (not shown) splits bytes into lines without decoding, recording where the first : is (fieldLength); getMessages turns lines into messages: a blank line dispatches, data lines are joined with newlines, a single space after the colon is dropped. Lines starting with : are comments: fieldLength is 0, so they're skipped. Working on bytes and decoding only complete fields avoids splitting a multi-byte UTF-8 character across network chunks (the same bug class as Volume 1's stage 6 decoder).
Read it yourself
- A server sends a keep-alive comment every 10 s (
: keep-alivefollowed by a blank line), as Chapter Exercises P9 recommends. What does this parser'sonmessagereceive, and what does the browser'sEventSourcedispatch? - Why does the library put
Last-Event-IDinheadersinstead of the URL?
Debugging drills
D1. The whole app freezes when the manager opens a sixth station
A kitchen manager runs the order display in one tab per station. With five stations it works. When they open the sixth, every tab stops responding to clicks that call the API, and new pages spin forever. Closing any one tab fixes it immediately. The server's logs show no errors and low load.
D2. Displays went blank after last night's deploy, and stayed blank
After a deploy at 23:00, morning staff found all kitchen displays showing the last orders from before the deploy. Reloading fixed every display. The deploy took 40 seconds; the load balancer answered 502 for part of that time. The display uses new EventSource('/kitchens/k7/stream') with an onerror that logs.
D3. The server falls over every time it restarts
The order service restarts cleanly in tests. In production, with 1,800 kitchen displays connected, each restart is followed by a minute of timeouts and a spike to 100% CPU, and sometimes a second crash. Logs show a burst of /stream requests with Last-Event-ID headers in the first seconds after start.
D4. "Late" orders that aren't late, on one tablet
On the station 3 tablet, orders turn red ("late") several minutes before their promised time. Other tablets are fine. The code:
const lateBy = Date.now() - Date.parse(order.promisedAt);
card.classList.toggle('late', lateBy > 0);
Career-oriented
Interview prep
Mid level
Q1. Render a list of 500 orders that updates when any order changes. How do you wire up the click handlers, and how do you update one order without breaking the user's focus or scroll position?
How to get there. Delegation for events; keyed updates for changes (find the element by order id and update it in place), never re-rendering the whole list with innerHTML. Then think about focus and screen readers.
Q2. WebSocket or Server-Sent Events for a kitchen display that shows new orders and status changes?
How to get there. Compare by direction of data, reconnection and resumption, infrastructure (proxies, HTTP/2, auth), and failure behaviour. Chapter Exercises T9 compares them in general; answer for this case, including the traps (Gaps 1–3).
Senior level
Q3. How do you test the kitchen display's real-time behaviour (reconnection, late orders, missed events) automatically?
How to get there. Chapter Exercises leaves testing browser APIs out. Separate pure logic (unit tests with fake time), browser behaviour (Playwright with a controllable server and clock), and failure injection (dropping connections, error responses, clock skew).
Q4. The display must keep working on a tablet left on all day, sometimes behind other apps. List what can go wrong over 12 hours and what you'd build.
How to get there. Think in time: the screen (sleeping), the page (throttled, frozen, discarded), the connection (dropped, half-open), memory (growth), the clock (drift), and the code itself (a new deploy).
Staff level
Q5. Decide whether TiffinBox's real-time features (kitchen displays, customer order tracking, partner locations) share one infrastructure or each team builds its own.
How to get there. Consider scale differences (2,000 displays, 200,000 trackers, 20,000 partners), common concerns (auth, reconnection, back-pressure, observability), and organisational costs. Chapter Exercises S2 designs order tracking at scale; this is the platform decision across features.
Q6. Users report "it's slow" in the kitchen app, but your server dashboards are green. How do you get visibility into what the browser experiences?
How to get there. Chapter Exercises leaves performance APIs beyond observers out. Name the browser-side measurements, how to collect them without hurting users, and how to connect them to server data.