CapstoneVol. 19 · Part XIX
0 / 0

Trails / Capstone

CP·211B

The Frontend Layer

TiffinBox's web app built to the capstone's list: React and TypeScript with a typed API client, an accessible component system, responsive layouts, state that lives in the URL, server-state caching with optimistic updates, sign-in through a backend-for-frontend with HTTP-only cookies, live delivery tracking, end-to-end tests of the critical journeys, and real-user performance monitoring; with a lab that compares polling, long polling, server-sent events and WebSockets for live updates, and measures what each costs at a thousand users.

21 topics · ~13 min read · 16-question quiz
Updated Suggest a correction

Start here: what the frontend must do

The frontend is where users meet everything else you build. If the backend is perfect but the skip button gives no feedback, isn't reachable by keyboard, or shows yesterday's data, the product is broken. The capstone list for the frontend reads like a checklist, but each item exists because of a specific way frontends fail:

Requirement The failure it prevents
React + TypeScript with a generated API client the UI and API drifting apart until something breaks in production
accessible component system users who can't see, can't use a mouse, or use a screen reader being locked out (and legal risk)
responsive UI a desktop-only app in a mobile-first market
URL state shared links and the back button not working; refresh losing context
server-state caching duplicate requests, stale screens, spinners everywhere
authentication done safely tokens stolen by injected scripts
realtime users refreshing to see if lunch is near
end-to-end tests the journey that matters breaking unnoticed
performance monitoring a slow app on real phones that nobody on the team ever sees

Live updates, measured

TiffinBox shows delivery status live. The lab sent 40 status changes at random times over about a minute and delivered them to clients five different ways:

Method Mean delay Worst delay HTTP requests Bytes
poll every 5 s 2,000 ms 4,557 ms 14 ~4.6 KB
poll every 1 s 482 ms 995 ms 66 ~12.8 KB
long polling 0.7 ms 1.6 ms 40 ~8.7 KB
server-sent events (SSE) 0.4 ms 1.1 ms 1 ~2.9 KB
WebSocket 0.5 ms 1.2 ms 1 ~2.4 KB

And for 1,000 users watching for 20 seconds with nothing new to report: 1,000 open SSE connections cost the server no measurable CPU (about 12 MB of memory), while 1,000 users polling every second made 20,000 requests and used about 10% of a CPU core to say "nothing new" over and over.

Polling is either slow or wasteful; push (SSE or WebSocket) is both fast and cheap when there are many watchers and few updates.

How deep to go

Volume 17 defines six mastery levels. For the frontend layer:

Level What you can do
L1 Name each capstone requirement and what it's for
L2 Build the screens with React, TypeScript and a component library
L3 Explain caching, rendering, accessibility trees and cookie security from first principles
L4 Debug stale data, layout shifts, slow interactions and broken focus on real devices
L5 Design the frontend architecture, its contracts and budgets, and defend the trade-offs
L6 Run it in production: field metrics, error budgets, safe releases, accessibility over time

Volume 2 (chapters 12–32) teaches every topic below in depth; this chapter is the build guide.

The screens

Screen Users Data Special concern
kitchens and menus everyone catalogue (cacheable) search, filters in the URL, images
plan checkout customers plans, payment idempotent submit, clear errors
my calendar customers subscription schedule skip before cut-off, optimistic update
order tracking customers order status, rider position live updates, map, reconnects
kitchen dashboard kitchen staff today's orders big counts, fast marking, works on a tablet
operations console staff orders, refunds, roles permissions, audit visibility
assistant panel customers answers with sources streaming text, citations, actions confirmed

TypeScript and the API contract

  • Generate the client from contracts/openapi.yaml (e.g. openapi-typescript plus a thin fetch wrapper, or Orval). Commit the generator, not hand-edited output, and run it in CI.
  • Validate at the edge: TypeScript types vanish at runtime. Parse responses that matter (money, dates) with a schema library such as Zod so a backend mistake fails loudly at one place.
  • Model states explicitly: a request is idle | loading | success | error, and the UI handles all four. Use discriminated unions so the compiler forces it.
  • Money and dates: amounts arrive as integer paise, formatted with Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }); times arrive in UTC (ISO 8601) and are shown in the kitchen's time zone (Volume 23 covers this fully).

An accessible component system

Build a small component library first, then the screens from it. Accessibility done once in a Dialog is done for every dialog.

  • Design tokens (colour, spacing, type scale, radii) as CSS custom properties, with light and dark values; check contrast (4.5:1 for body text) when choosing them.
  • Primitives on proven foundations: buttons are <button>, links are <a href>; for complex widgets (dialog, menu, combobox, tabs, date picker) use a headless accessible library (React Aria, Radix) rather than reinventing keyboard and ARIA behaviour.
  • Focus management: dialogs trap focus and return it on close; route changes move focus to the main heading; nothing removes the focus outline without replacing it.
  • Forms: every input has a visible label; errors are linked with aria-describedby and announced; the skip-a-day confirmation is announced with a polite live region.
  • Test it: axe checks in component tests and in Playwright; a keyboard-only and a screen-reader walkthrough (NVDA or VoiceOver) of each journey before release. Automated tools find roughly a third of issues; the walkthrough finds the rest.

Responsive by default

  • Mobile first: TiffinBox customers are mostly on phones; design the small screen, then enhance.
  • Layout primitives (stack, cluster, grid) with CSS grid and flexbox; container queries for components that appear in different widths (a dish card in a list and in a sidebar).
  • Fluid type with clamp(); touch targets at least 44 × 44 px; no hover-only interactions.
  • Images: srcset/sizes, modern formats, explicit dimensions to prevent layout shift, lazy loading below the fold.
  • The kitchen dashboard runs on a shared tablet in a hot kitchen: large targets, high contrast, works in landscape, survives flaky Wi-Fi (queue actions and retry).

State: URL, server and client

URL state. The menu page's filters (?veg=1&allergen-free=peanut&sort=price), the operations console's search and page, the calendar's month: all in the URL. Use the router's search-params API (or a helper like nuqs), parse and validate them (an invalid value falls back to a default), and use replaceState for keystrokes and pushState for deliberate navigation so the back button behaves.

Server state. Use a server-state cache (TanStack Query, RTK Query or the framework's loaders):

  • Each query has a key (['orders', 'today', kitchenId]) and a stale time chosen per data type: menus can be minutes old; today's order count should refetch on focus and every 30 s; tracking comes from the push channel.
  • Mutations invalidate the queries they affect: skipping a day invalidates the calendar and the next invoice.
  • Optimistic updates for actions users repeat: the skip button flips immediately, the request goes out with an idempotency key, and on failure the UI rolls back and says why ("too late: the kitchen's cut-off was 10:30").
  • Deduplication and retries come free; set retries to zero for non-idempotent mutations unless they carry an idempotency key.

Client state. What's left (an open drawer, a draft message) stays in component state or a small store. If you find yourself copying server data into a global store, stop: that's the cache's job.

Authentication

The safe pattern for a browser app (OAuth 2.0 for Browser-Based Apps, Volume 10, chapter 109) is a backend-for-frontend (BFF):

  1. The user clicks "Sign in"; the browser goes to the BFF (part of the API), which starts the OIDC authorization-code flow with PKCE against the identity provider.
  2. After login, the BFF exchanges the code for tokens server-side and stores them in its session.
  3. The browser gets only a session cookie: HttpOnly; Secure; SameSite=Lax (or Strict), with a short idle timeout.
  4. API calls carry the cookie; the BFF attaches the access token when calling downstream services.
  5. State-changing requests also need CSRF protection: SameSite cookies plus a CSRF token header (or checking Origin).

The frontend then only needs: a /me call to know who's signed in and their roles (to show or hide UI, never to enforce security), a way to handle 401 (session expired: send to sign-in and come back to the same URL), and sign-out that clears the server session.

Realtime: live tracking

From the lab: push beats polling for delay and for cost at scale. TiffinBox uses server-sent events from the tracking gateway, because updates flow one way:

  • GET /orders/{id}/events returns text/event-stream; each event has an id. On reconnect, the browser's EventSource sends Last-Event-ID and the gateway replays what was missed.
  • Send absolute state ("status: out for delivery, position: …"), not diffs, so a missed event never corrupts the screen.
  • Reconnect with exponential backoff and jitter, so that when the gateway restarts, 10,000 clients don't reconnect in the same second.
  • Mind the plumbing: proxies must not buffer the stream (X-Accel-Buffering: no for nginx), and idle timeouts must exceed the heartbeat interval (send a comment line every 15–30 s).
  • Under HTTP/1.1 a browser allows only ~6 connections per host; SSE over HTTP/2 avoids that limit.
  • Fallback: if the stream can't connect (some corporate proxies), fall back to polling every 10 s and say "live updates paused".

End-to-end tests

Write few, valuable end-to-end tests (Volume 11, chapter 118) with Playwright:

  • The critical journeys only: sign in → subscribe → skip a day → see the credit; kitchen marks an order packed → customer sees it live; ask the assistant → answer with a source.
  • Run against a seeded, production-like environment, with test data created through APIs, not the UI.
  • Make them reliable: role-based locators (getByRole('button', { name: 'Skip Tuesday' })), web-first assertions that wait, no fixed sleeps, isolated test users.
  • Test failure paths with network interception: the payment provider returns an error; the stream disconnects; the session expires mid-flow.
  • Include axe checks and a mobile viewport project in the same suite.

Performance and monitoring

  • Budgets in CI: JavaScript per route (e.g. < 170 KB compressed for the first load), Lighthouse CI thresholds; a pull request that breaks the budget fails.
  • Field data: collect Core Web Vitals (LCP, INP, CLS) with the web-vitals library and send them, tagged by route, device class and release, to your observability backend (an OpenTelemetry endpoint or a RUM product). Targets at the 75th percentile: LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1.
  • Errors: capture unhandled errors and rejected promises with source maps uploaded per release, and link them to traces (pass the traceparent header on API calls).
  • The dashboard shows field vitals by release, so a regression is visible the day it ships.

Done when

  • All screens built from the component library; axe passes; keyboard and screen-reader walkthroughs pass for each journey.
  • Filters, tabs and dates survive refresh and sharing; the back button does what users expect.
  • No tokens in browser storage; CSRF protection on all state-changing calls; session expiry handled gracefully.
  • Live tracking delivers updates within the 5 s freshness target, survives a gateway restart, and falls back to polling.
  • Playwright covers the critical journeys and their failure paths, on desktop and mobile viewports.
  • Field Core Web Vitals meet the targets at p75 on mid-range phones, and are visible per release.

Common traps

  • Hand-written API types that drift from the backend.
  • Server data copied into a global store, then going stale.
  • Div soup: clickable <div>s with no keyboard or screen-reader support.
  • Tokens in localStorage.
  • Polling everything every second "for realtime".
  • Lab-only performance: great Lighthouse scores, slow on real phones.

Lab: getting live updates to the browser

Setup. An aiohttp server on the lab machine with an in-memory event log. A background task emits 40 delivery-status events at random times (exponential gaps averaging 1.5 s, so about a minute in total), each stamped with the server's clock. Five clients ran at the same time, receiving the same events, and recorded each event's delay (arrival time minus emit time; one machine, one clock):

  • poll every 5 s and poll every 1 s: GET /poll?since=<last id>
  • long polling: GET /longpoll?since=…, which the server holds open until there's a new event (or 25 s)
  • server-sent events: one GET /sse stream
  • WebSocket: one connection

Bytes are approximate (bodies plus headers as received).

Experiment 1: delay and traffic for one user

Method Mean delay p95 Max HTTP requests Bytes
poll every 5 s 2,000 ms 4,246 ms 4,557 ms 14 ~4,630
poll every 1 s 482 ms 922 ms 995 ms 66 ~12,822
long polling 0.7 ms 0.9 ms 1.6 ms 40 ~8,700
SSE 0.4 ms 0.5 ms 1.1 ms 1 ~2,930
WebSocket 0.5 ms 0.9 ms 1.2 ms 1 ~2,420

Experiment 2: a thousand users and nothing to say

After the events stopped, 1,000 clients connected for 20 s each way (client and server on the same 2-CPU machine):

Requests Server CPU Server memory
1,000 open SSE connections, idle 1,000 (one each) 0.00 s (no measurable use) 50 MB (from 38 MB before: ~12 KB per connection)
1,000 clients polling every 1 s 20,000 1.93 s (~10% of a core) 51 MB

What it shows

  • Polling delay is half the interval on average, up to the full interval. Faster polling cuts the delay but multiplies requests, almost all of which return nothing.
  • Long polling gets push-like delay over plain HTTP but costs one request per event; it's a good fallback.
  • SSE and WebSocket delivered events in under a millisecond on one connection, with the least traffic.
  • At scale, idle push connections are cheap; idle polling isn't. The polling cost grows with users × frequency even when nothing happens. The push cost is memory per connection, which is why the tracking gateway is a separate, connection-oriented service.
  • What one machine hides: in production, add network latency (tens of milliseconds) to every method, proxies that buffer or time out streams, and mobile networks that drop connections. That's why reconnection with Last-Event-ID, heartbeats and a polling fallback are part of the design.

Try it yourself

  1. Kill and restart the server mid-stream; make the SSE client resume with Last-Event-ID and verify no event is missed or duplicated.
  2. Put nginx in front with default settings and observe SSE buffering; fix it with proxy_buffering off or X-Accel-Buffering: no.
  3. Raise the idle test to 10,000 SSE connections (raise the open-file limit first) and plot memory per connection.
  4. Add exponential backoff with jitter to reconnection and simulate 1,000 clients reconnecting after a restart: compare the reconnection spike with and without jitter.

Revision sheet: the frontend layer

Key ideas

  • Generated, validated API client from the shared contract; explicit request states.
  • A component library with accessibility built into its primitives; axe plus manual walkthroughs.
  • Mobile-first responsive layout; container queries; no hover-only actions.
  • URL state for what the user is looking at; a server-state cache for backend data; little client state.
  • BFF pattern: tokens server-side, HTTP-only cookies, CSRF protection.
  • SSE for one-way live updates with resume, heartbeats, backoff with jitter and a polling fallback.
  • Few, reliable Playwright journeys; budgets in CI; field Core Web Vitals per release.

Numbers to remember

  • Lab: poll 5 s → mean 2 s delay; poll 1 s → 482 ms; SSE/WebSocket < 1 ms.
  • 1,000 users polling 1/s = 20,000 requests in 20 s, ~10% of a core; 1,000 idle SSE ≈ 0 CPU, ~12 KB each.
  • Vitals at p75: LCP ≤ 2.5 s, INP ≤ 200 ms, CLS ≤ 0.1; touch targets ≥ 44 px; text contrast ≥ 4.5:1.

Pitfalls

  • Hand-written types; server data in global stores; div soup; tokens in storage; polling for realtime; lab-only performance.

Glossary

  • BFF: backend-for-frontend, holding tokens and sessions for the browser app.
  • SSE: server-sent events, a one-way HTTP stream with automatic reconnection.
  • Stale time: how long cached server data counts as fresh.
  • Optimistic update: showing a change before the server confirms it, with rollback.
  • RUM: real-user monitoring.