Architecting a Real-Time Exchange Web Client
System DesignModel answerLast updated
Plan the browser-side architecture of a live crypto-style exchange screen, covering rendering, state, streaming data, order safety, security, and observability.
You are asked to lay out the browser-side architecture for a production exchange-style trading screen. The page contains:
- A price chart
- A live order book
- A feed of recent trades
- An order-entry form for buying and selling
- Account balances
- A list of open orders and their execution status
The matching engine and backend are out of scope. Concentrate on what runs in the client.
Walk through your design from these angles:
- Framework choice and rendering strategy
- Component library and design-system decisions
- State management
- How live data flows from the network to the screen
- Error states and loading behavior
- Performance and reliability
- Security
- Testing and observability
State your assumptions about load (message rates, number of instruments watched, load-time and bundle budgets) before you begin. Expect follow-up questions about trade-offs and edge cases, especially around the order-entry flow, reconnects, and stale data.
Hints
Hint 1
Separate state by how often it changes and who owns the truth: high-frequency market streams, correctness-critical account data, and local UI state each deserve a different mechanism.
Hint 2
For the order book, think about how to join a REST snapshot with a delta stream using sequence numbers, what to do on a gap, and how to limit how often the UI is updated.
Hint 3
For order submission, ask what happens if the request times out: is the order placed or not? Consider idempotency keys, no optimistic fills, and a way to look up the outcome afterward.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and assumptions
I would first separate high-frequency, read-only market data from low-frequency, correctness-critical account data. Most architectural decisions follow from that split.
Assumed load
- Order book deltas: 100–1,000/s on a busy pair during volatility.
- Trades: 10–200/s.
- One active instrument plus a watchlist of about 20 tickers.
- Time to interactive under about 2.5 s on a mid-range laptop; roughly 300 KB gzipped JS for the trading route.
Non-functional goals
- Market updates visible within about 100 ms; 60 fps even in bursts.
- Balances and order state must never be wrong. Stale data is acceptable only if clearly labeled.
- Survive dropped connections, sleeping laptops, and multiple tabs.
2. Framework and rendering
- React with strict TypeScript: mature ecosystem, concurrent rendering, easy hiring.
- Marketing and asset pages use SSR/SSG for SEO. The authenticated trading view is a client-rendered route: it is personalized, live, and not indexable, so SSR adds cost with no benefit. A Next.js shell can host both.
- Hot visuals (candles, depth chart) render on canvas/WebGL via a library such as Lightweight Charts. Provide a DOM/table fallback for accessibility.
- Split code by panel; load the chart library and advanced order types lazily.
3. Design system
- Internal component library with design tokens (color, spacing, type) and dark/light themes, built on accessible headless primitives.
- Trading-specific parts: price/size cells with tabular numerals and locale-aware formatting, tick-size-aware inputs, flash-on-change cells, status badges.
- Never encode buy/sell by color alone; add sign or label, and support a red/green inversion setting.
- Document in Storybook and reuse stories for visual regression tests.
4. State management
| State | Examples | Tool |
|---|---|---|
| Streaming market data | book, trades, ticker | External store read with useSyncExternalStore and selectors |
| Server state | balances, open orders, fills, product metadata | TanStack Query, patched by the user stream |
| Local UI | form inputs, layout | Component state, small Zustand store |
| URL | pair, timeframe | Router params |
Do not push hundreds of messages per second through Redux or Context; the re-render storm will destroy frame rate. Represent money as decimal strings, a decimal library, or scaled BigInt. Never floats (0.1 + 0.2 in an order size is a real bug).
5. Real-time data flow
WebSocket -> Worker (parse, seq check, merge book) -> coalesce per rAF -> store -> selectors -> panels
REST snapshot ----^ user channel -> Query cache patch
- One multiplexed socket per tab (or per browser via SharedWorker) with channel subscriptions and a ref-counted subscription manager.
- Snapshot plus deltas: subscribe and buffer deltas, fetch the snapshot, drop deltas with
seq <= snapshot.seq, apply the rest. Ifseq != last + 1, mark the book stale and resync. - Worker offload: parsing and book maintenance (sorted maps by price) run in a Web Worker. It posts a top-N view at most once per animation frame. Dropping intermediate states is safe because the book remains correct.
- Connection health: heartbeats detect a dead socket in about 5 s; reconnect with exponential backoff and jitter, resubscribe, resync. Throttle when the tab is hidden and resync on return.
- User channel: order lifecycle events (received, open, partially filled, filled/canceled) patch the Query cache; a periodic REST reconcile is the safety net.
6. Order entry correctness
- Validate tick size, lot size, min/max notional, and available balance from product metadata. Show fee and total previews.
- Idempotency: generate a
client_order_idper submit attempt, disable the button in flight, and reuse the ID on retry so double clicks cannot create two orders. - No optimistic fills. Show "Pending" until acknowledged; "Filled" only from execution events.
- Timeouts: do not show "failed." Show "Status unknown, checking" and look up the order by
client_order_id. Distinguish rejected, network error, and unknown. - Guardrails: confirm large orders, market orders, and prices far from mid (fat-finger check). Warn or block market orders when data is stale.
7. Errors and loading
- An error boundary per panel, so a chart crash cannot take down order entry.
- Skeletons on first load only. Afterward keep last-known data with a visible "Delayed/Reconnecting" badge and timestamp.
- Global connection banner; if the user stream is down, fall back to polling open orders.
- Map server error codes to actionable messages (for example "Insufficient funds"); never expose raw traces.
- Feature flags allow risky features to be disabled without a deploy.
8. Performance and reliability
- Virtualize long lists; memoize rows; use selector-based subscriptions so a row re-renders only when its own data changes.
- Coalesce updates per frame; avoid layout thrash; use CSS transforms for flashes.
- Track a bundle budget in CI; preconnect to API and socket hosts; cache static assets with content hashes.
- Multi-tab: elect a leader via BroadcastChannel or SharedWorker to hold one socket and fan out data.
- Clock skew: label times using server timestamps.
9. Security
- Strict CSP, no inline scripts, Subresource Integrity for third-party code, and a minimal dependency set with lockfile auditing.
- Prefer httpOnly, SameSite cookies for sessions over localStorage tokens; CSRF protection on mutating calls.
- Sanitize any user-supplied text (order labels, chat); avoid
dangerouslySetInnerHTML. - Step-up authentication (2FA) for withdrawals and API key creation; re-validate everything server-side since client checks are only UX.
- Do not log sensitive data to analytics or error reporting.
10. Testing and observability
- Unit: book merge logic, sequence-gap handling, decimal math, validation (property-based tests for the book).
- Component: Storybook interaction tests; accessibility checks.
- Integration: mock WebSocket with scripted scenarios (gap, duplicate, reconnect, timeout on submit).
- E2E: critical flows (place, cancel, partial fill) against a sandbox.
- Visual regression from Storybook; performance tests replaying recorded bursts and asserting frame time.
- Observability: real-user metrics (TTI, INP, long tasks), WebSocket health (reconnect rate, gap/resync count, message lag), order-submit funnel with unknown-outcome rate, error reporting with source maps, and a trace ID tying client actions to backend logs.
Trade-offs and common mistakes
- Putting streams in Redux/Context, causing render storms.
- Using floats for prices.
- Treating a timeout as a failure and letting users double-submit.
- Blanking the UI on reconnect instead of showing labeled stale data.
- Applying deltas without a snapshot or sequence check, silently corrupting the book.
- Using SSR for the authenticated live view where it brings no benefit.