The TiffinBox BuildOne system, every chapter
0 / 0

Workbench / The TiffinBox Build

S24 · V2·24

Keep the First Screen

Volume 2, chapter 24. The kitchen page has been server-rendered since stage 21, but the React and Angular views threw that work away: they removed the server's cards, waited for the stream, and sent the whole state a second time. Measured frame by frame, the React view showed no cards for 130 ms and the Angular view didn't show any until 420–450 ms. Stage 24 makes the server embed the state it rendered from (escaped for a script element, checked against the contract), lets both views start from it and swap in after their first render, and resumes the stream from the page's event id instead of sending a 108 KB snapshot again. A missing first message would have left "Connecting…" on screen for 15 seconds; a ping fixes it. The views now show cards from the first paint, with no blank frames, at the cost of 4.7 KB more compressed HTML.

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

Stage 24: keep the first screen

The brief

What you'll build.

  • server: the kitchen page, for the framework views, embeds <script type="application/json" id="tb-initial"> with the snapshot and the event id it corresponds to, taken atomically (KitchenEvents.current) and escaped by Html.scriptJson; the stream resumes from ?after=<id> when there's no Last-Event-ID, and a resuming stream starts with a ping;
  • contract: a KitchenPage type (snapshot, lastEventId), checked by ContractTest against the real page;
  • client: kitchen/page.ts reads and checks the embedded state (and measures tb:page); store.ts starts from it and resumes the stream from the newest event it has applied; React and Angular render into a hidden element beside the server's list and swap after their first render;
  • checks: PagesTest.jsonInAScriptElementCannotEndIt, a stream test that a page's id resumes exactly after the page and that a resume with nothing missed gets a ping at once, a store test for starting from the page; web-tests/stage24.py, a frame-by-frame count of cards on screen per view, and what the stream sends first.

Why a real company needs this. Server rendering pays off only if the client keeps what the server sent. Pages that render on the server and then blank out while a framework starts, or fetch the same data again, pay for SSR and get CSR's experience. Embedding state is the standard answer, and it's where serialisation bugs and script-injection holes live, so it has to be done carefully.

Why now. Chapter 24 is full-stack frameworks: where and when HTML is made, hydration, streaming and embedded state. The build's server is Java, so React and Angular can't hydrate its HTML (that needs the same renderer on both sides); this stage gets the benefit SSR is for, content from the first paint, with the architecture the build has.

What you'll have at the end.

  • every view shows cards from the first paint and never blanks;
  • the stream sends only what changed since the page was made;
  • ADR-0026: the rendering strategy per page, and why the build renders on the Java server and hands state to client views.

Theory to own

  1. What SSR buys and costs. What does server HTML improve, what doesn't it, and what is hydration? (The chapter's lab, Experiment 1; Companion, Gaps 1.)
  2. Embedding state. How is server data handed to a client view, and how is it made safe in a script element? (Companion, Gaps 3 and interview Q2.)
  3. Hydration versus taking over. Why can't React hydrate the Java server's HTML, and what's the alternative? (Companion, interview Q5.)
  4. Resuming a stream. How does a page that already has a snapshot get only what came after it? (Stage 17's event ids.)
  5. Measuring what the user sees. How do you show that a page never blanks? (This stage's stage24.py.)

Build it

Step 1: measure what each view shows while it starts

Write stage24.py: place 500 orders, then for each view load the kitchen page with the CPU throttled 4×, record the number of visible cards in every animation frame from navigation start, and listen to the DevTools protocol's Network.eventSourceMessageReceived to see what the stream sends first. Run it before changing anything.

Checkpoint. You can say, for each view, when cards first appear and whether the screen ever goes blank.

Step 2: embed the page's state, safely

In KitchenEvents, add current(snapshotSupplier): under the publishing lock, take the snapshot and the current event id together. In Server, kitchenPageJson(kitchen) builds {"snapshot":…,"lastEventId":…}. In Pages.kitchen, for the framework views (?view=…), append it in a <script type="application/json" id="tb-initial">, through Html.scriptJson. Add KitchenPage to the contract and check the real page in ContractTest. Write PagesTest.jsonInAScriptElementCannotEndIt with a hostile string, and break scriptJson once to see the test fail.

Checkpoint. 30 server tests pass; the planted break fails one of them.

Step 3: resume the stream from the page

Let the stream take ?after=<id> when the request has no Last-Event-ID. In store.ts, accept an optional KitchenPage: seed the open orders, offset and loaded from it, keep its id, open the stream with ?after= that id, and update the id from every event's lastEventId, so a stream reopened after a back-off resumes too. Write kitchen/page.ts to read and validate the embedded state. Extend the tests: a stream opened with a page's id gets the orders placed after the page, not a snapshot; the store starts with the page's open orders and builds the right URLs.

Checkpoint. The tests pass; the framework views' stream sends no snapshot.

Step 4: take over without a blank frame

Change both views to render beside the server's list, hidden, and swap when their first render is done: React from a layout effect after its first commit (before the browser paints), Angular after ApplicationRef.whenStable(). Run stage24.py again, and stage18.py on both views.

Checkpoint. No blank frames in any view; the stream's first message is a ping.

Step 5: what it costs

Measure the page with and without the embedded state, raw and compressed, and run the regressions: stages 14, 17, 19, 20 and 22 (both views), check-js.sh and the server tests.

Checkpoint. You know the price in bytes and nothing else broke.

Senior and architect lens

1. SSR is a promise the client must keep. The server had rendered the first screen since stage 21; two of three views broke the promise by discarding it. Measuring frames, not just "time to interactive", is what showed it.

2. ADR-0026: rendering strategy. Write it with these points:

  • Decision: the Java server renders every page's first screen; pages with client views embed the state they were rendered from; client views take over without a blank frame; the stream resumes from the page's event id.
  • Not chosen: a Node rendering tier for React hydration (a second production runtime for one internal screen), and static generation for the kitchen page (its content changes every few seconds). Revisit for public, content-heavy pages (the menu), where static generation with revalidation may fit.
  • Rules: embedded state goes through Html.scriptJson and is validated on the client against the contract; only data the page needs, never another user's; the plain view keeps working without JavaScript.
  • Costs accepted: the page carries its data twice (4.7 KB compressed at 500 orders).

3. A snapshot and an id must be atomic. The page's state and the event id are taken under the same lock as publishing, so "after this id" is exactly what the page lacks: no lost order, no duplicate. It's the same rule as stage 17's subscribe-and-snapshot.

4. Defaults that hide in quiet conditions. The 15-second "Connecting…" appeared only when nothing was happening, which is when nobody is testing. A test for the quiet case now guards it.

5. Try the obvious fix, measure, and write down why it lost. flushSync removed the blank and created a long task; yielding before Angular's bootstrap changed nothing. Both are recorded in the code, so the next person doesn't repeat them.

What breaks first, and when it's addressed:

Pressure What breaks Where it's addressed
the plain view still waits for a full snapshot 108 KB sent again on every load of the default view stage 25 (the plain view moves onto store.ts and the embedded state)
pages and streams aren't compressed the embedded state costs 111 KB raw instead of 4.7 KB stage 31 (compression, hashed assets, CDN)
the public menu is rendered per request the same HTML is built for every visitor stage 31 (cache headers) and stage 27 (budgets)
start-up long tasks of 100–200 ms remain in the framework views interaction is blocked during start-up on slow devices stage 27 (performance budgets per view)

Evidence

  • stage24.py before and after, with the blank frames and the first stream messages, is in the README.
  • 30 server tests pass, including the escaping test (and its planted failure) and the resume-with-ping test (and its failure without the ping).
  • check-js.sh passes (17 modules, 24 tests); stages 14, 17, 19, 20 and 22 (React and Angular) pass.
  • The page sizes with and without embedded state are recorded.
  • ADR-0026 is committed.

Carry forward

  • tb-initial and store.ts's page start are what the plain view uses from stage 25, so all three views share one start-up path.
  • ?after= resume is how any client that already has state joins the stream; stage 29's offline display uses it after a reconnect.
  • stage24.py's frame sampling becomes part of stage 27's budgets ("no blank frames after first paint").
  • Html.scriptJson is the only way JSON enters a page; stage 28 checks it under Trusted Types.