Workbench / The TiffinBox Build
S17 · V2·17
The Kitchen Display, Live
Volume 2, chapter 17. Kitchens get a live display: the server streams each kitchen's order changes as Server-Sent Events, with ids that survive restarts correctly, a replay buffer for clients that reconnect, a snapshot for those that can't resume, a random retry delay per client and a ping every 15 seconds. The display updates cards in place (keyboard focus survives), handles actions with one delegated listener, reconnects even after the browser gives up on a 503, and computes ages from the server's clock. Browser tests show an order on two displays within 90 ms, recovery from a restart in 1.4 s and from a burst of 503s, a tablet seven minutes fast showing the right ages, and the one thing this server can't fix: six display tabs freeze everything else on HTTP/1.1.
Stage 17: the kitchen display, live
The brief
What you'll build.
KitchenEvents(server): every order change is published to its kitchen with an id<epoch>-<seq>; the last 1,000 events are kept for resuming clients; subscribing and taking a snapshot happen under the same lock as publishing;GET /kitchens/{k}/stream: Server-Sent Events: aretry:between 2 and 10 seconds (random per client), then asnapshot(open orders and the server's time) or the missedorderevents, then each change, and apingevent (with the server's time) every 15 seconds; at most 500 streams, more get a 503;/kitchen/{k}: the server-rendered display (open orders, oldest first), andweb-src/kitchen.ts, which keeps it live;- contract additions:
KitchenSnapshotandPing, checked byContractTeston real stream messages; - tests:
StreamTest(3 tests, 23 server tests in all) andweb-tests/stage17.py.
Why a real company needs this. A kitchen that learns about orders by refreshing a page misses them during the lunch rush. Live displays are where real-time systems meet unreliable reality: restaurant Wi-Fi, deploys, tablets left on all day, clocks nobody set. Most of the work in this stage is about what happens when things go wrong, because that's where real-time features fail in production.
Why now. Chapter 17 is the DOM and browser APIs: events and delegation, observers, fetch, storage, workers, and real-time APIs (WebSocket, Server-Sent Events, BroadcastChannel). Stage 16's contract means stream messages can be checked like any other response.
What you'll have at the end.
- a live display that recovers from restarts, errors and silence without a reload;
- evidence for each failure mode, and one measured limitation with a plan;
- ADR-0019: real-time delivery.
Theory to own
- SSE or WebSocket for the display? Decide from the direction of data and what each gives you when the connection drops. (Companion, interview Q2.)
- Resuming. A display was disconnected for 20 seconds. What must it receive when it reconnects, and what if the server restarted in between?
- Snapshot and stream. A client subscribes while orders are changing. How do you make sure it never shows an order in an older state than it already displayed?
- Failure modes. List what
EventSourcedoes on a dropped connection, a 503, and silence. (Companion, Gaps 2.) - Time. The display shows "waiting 7 min" and marks late orders. Which clock should those come from? (Companion, Gaps 4.)
Build it
Step 1: the event hub
Write KitchenEvents: publish(kitchen, json) assigns <epoch>-<seq>, appends to a bounded buffer (1,000 events) and offers the event to each subscriber's bounded queue (256); a subscriber whose queue is full is marked overflowed and sent a CLOSED marker (it reconnects and resumes or re-snapshots). subscribe(kitchen, lastEventId, snapshotSupplier) registers, then either collects the missed events for that kitchen or, if the id is from another epoch, too old, or malformed, calls the snapshot supplier, all under the hub's lock. closeAll() wakes every stream on shutdown. In Server, publish right after storing each placement and each lifecycle event, inside the order's lock.
Checkpoint. The server still builds and its 19 tests pass.
Step 2: the stream endpoint
In serve(), before routing, hand GET /kitchens/{k}/stream connections to stream(...), which owns the connection until it ends. Acquire one of 500 stream permits (or answer 503 with Retry-After). Write the headers (Content-Type: text/event-stream; charset=utf-8, Cache-Control: no-store, Connection: close, the stage 12 security headers), then retry: with a random 2,000–10,000 ms, then the snapshot or the replay, then loop: wait up to 15 s for an event; write it, or write a ping event carrying the server's time. A write that fails means the client has gone; the subscription and the permit are released. Write StreamTest with raw sockets: snapshot then live events for that kitchen only; resume with Last-Event-ID; an id from another epoch gets a snapshot; closing the server ends streams quickly.
Checkpoint. 22 server tests pass.
Step 3: the contract for stream messages
Add KitchenSnapshot (kitchenId, serverTime, orders: Order[]) and Ping (serverTime) to contract/api.json and regenerate. In ContractTest, read a real stream: check the snapshot against KitchenSnapshot and an order event (after placing an order) against Order.
Checkpoint. 23 server tests pass; contract.ts has 6 types.
Step 4: the display page and its script
Render /kitchen/{k} on the server: a status line (role="status"), a list of ticket cards with data-order-id, data-status and data-at, and "No open orders" when empty. Without JavaScript it says the view is a snapshot (the exception ADR-0017 anticipated). Write web-src/kitchen.ts:
- load dish names once from
/menu/search; add the action buttons to the server-rendered cards; connect()opens anEventSource;snapshotreplaces the cards and sets the clock offset;orderupdates one card in place (or removes it when the order is no longer open);pingrefreshes the offset;- every 15 s, recompute ages from
Date.now() + offsetand mark late cards (placed for 5 minutes, accepted for 30, ready for 10); onerror: show "Reconnecting since …"; ifreadyStateisCLOSED, reconnect yourself; also reconnect after 45 s of silence; back-off is exponential with full jitter (random between 0 and 1 s × 2ⁿ, at most 30 s);- one delegated click listener posts the button's event (
accept 15,ready,handover) and renders the returned order.
Add ticket styles to app.css: late cards get a thick --danger border and the word "Late:", not colour alone.
Checkpoint. tsc compiles; check-js.sh passes (4 modules).
Step 5: prove it in a browser
Write web-tests/stage17.py against a real server with a temporary data directory:
- two displays of kitchen 7; place an order through the API; time until both show it;
- click "Accept" on one; time until the other shows
Accepted; - focus a card's button on one display; place another order; check where focus is;
- stop the server, start it again on the same data, and place an order at once; time until the display shows it;
- make the stream answer 503 for 6 s (
page.route); count the display's attempts; stop the 503s; time until it's live; - a tablet whose clock is 7 minutes fast (
page.clock.install): the age of a new order; - one browser, more and more display tabs: time a search from another tab after each.
Checkpoint. Every scenario recovers on its own; record the limit in 7.
Senior and architect lens
1. Real-time features are mostly failure handling. The happy path (open a stream, render events) is a few lines. The rest is epochs, snapshots, back-pressure, jittered retries, giving-up detection, silence detection, clock correction and a status line that tells people when to worry. Each was a measured failure in the Companion before it was code here.
2. ADR-0019: real-time delivery. Write it with these points:
- Decision: Server-Sent Events per kitchen; actions are ordinary idempotent
POSTs; messages follow the contract. - Delivery semantics: at-least-once with resumption (
Last-Event-ID, a 1,000-event buffer); ids carry the process epoch; clients apply events idempotently and get a snapshot when they can't resume. - Protection: at most 500 streams per server (503 beyond), 256 queued events per client (slow clients are disconnected), random
retry:2–10 s, pings every 15 s. - Client rules: reconnect on
CLOSEDand on 45 s of silence, back-off with full jitter, server-relative time, keyed DOM updates. - Known limit: HTTP/1.1 allows six streams per browser per origin; HTTP/2 arrives with the deploy in stage 31.
- Revisit when: one server can't hold all displays (a fan-out tier), or events must survive restarts (replay from the order log instead of memory).
3. Make the state recoverable, not the connection reliable. No amount of engineering makes a restaurant's Wi-Fi reliable. A protocol that can always get back to the right state (resume, or snapshot) makes reliability a property of the design instead of the network.
4. Protect the server from its own clients. Bounded queues, a stream cap, disconnecting slow clients and randomised retries all exist to stop clients (which are numerous, synchronised and uncoordinated) from taking the server down at its weakest moment, a restart.
5. Test the failures you designed for. Each recovery path here has a test that triggers it on purpose: a restart, a 503, a skewed clock, too many tabs. Without them, the code paths that matter most at 13:00 on a Friday are the ones nobody has ever run.
What breaks first, and when it's addressed:
| Pressure | What breaks | Where it's addressed |
|---|---|---|
| several display tabs in one browser | six HTTP/1.1 connections per origin | stage 31 (HTTP/2 in front of the server) |
| a restart loses the replay buffer | resuming clients get a snapshot, not missed events | Volume 3 (replay from a durable event log) |
| more displays than one server can hold | 500-stream cap | Volume 3 (a fan-out tier, horizontal scaling) |
| a menu of more than 50 dishes | the display loads names with limit=50 |
stage 19 (a menu endpoint with caching) |
| anyone can open any kitchen's stream | no authentication | Volume 3 (staff sign-in and roles) |
| the display's screen goes to sleep | no Wake Lock yet | stage 20 (with the display's accessibility pass) |
Evidence
StreamTestand the stream part ofContractTestpass (23 server tests).check-js.shpasses with 4 modules;kitchen.tscompiles under the strict options.stage17.py's output is in the README, including the six-tab limit.stage14.py(8 pages,failures: 0) andvalidate.sh(7 pages) pass; stages 13, 15 and 16 still pass.- ADR-0019 is committed.
Carry forward
- The event hub gets a durable source in Volume 3 (events replayed from the order log, so resuming survives restarts).
- The display's reconnect logic is the template for stage 29's background sync: back-off with jitter, recover state rather than trust the connection.
- Server-relative time (
serverTimein messages) is the rule for every countdown from now on. - The six-connection limit is the first concrete requirement for stage 31's deploy: HTTP/2 between browsers and the edge.