Architecting a Streaming LLM Chat Front End
System DesignModel answerLast updated
Design a browser client that streams model output into a virtualized, richly formatted chat log while surviving dropped connections and branching edits.
Context
You are asked to architect the browser-side of a conversational AI product: a single-page app where users hold long back-and-forth conversations with a language model. The model's output arrives incrementally, one fragment at a time, and the transcript must feel instant even when it grows to hundreds of messages with code blocks, images, and math.
Treat this as a front-end system design interview. The server and model are given; your job is the client architecture.
What the client must do
- Incremental output. Tokens arrive continuously while the model is generating. The UI must show them as they land without stuttering scroll or blocking typing in the composer.
- Long transcripts. A conversation can hold roughly a thousand messages, some of them tens of thousands of tokens long. Scrolling must stay smooth and initial load must not require fetching everything.
- Rich content. Render Markdown (paragraphs, lists, tables), highlight fenced code, and typeset math delimited with
$...$/$$...$$. Messages may also carry images. - Message actions. The user can edit an earlier prompt, ask for a fresh response to the same prompt (a variant), stop generation mid-stream, copy content, and retry a failed response.
Non-functional targets
- The first arriving fragment should be visible within about one frame of reaching the client.
- Steady-state updates should never push the main thread past a frame budget on a mid-range phone.
- The visible thread must stay consistent across the local cache, the server record, and other open tabs.
- A dropped connection mid-generation must not lose output that the server already produced.
Deliverables
- A component/data-flow overview of the client.
- How fragments move from the network into rendered state.
- Schemas for a conversation and a message.
- Your rendering strategy for very long logs, and how you handle network failure. Mention the trade-offs you weighed.
Hints
Hint 1
Model the transcript as a tree rather than an array — edits and regenerations create siblings, and rendering is just a walk from the current leaf up to the root.
Hint 2
Decouple the arrival rate of fragments from the render rate: accumulate deltas in a buffer and publish to the store at most once per animation frame.
Hint 3
Only the tail block of a streaming message is unstable; memoize every closed Markdown block by content hash so per-frame parse cost stays constant as the message grows.
Hint 4
Give the server a durable per-message stream with sequence numbers so a reconnect can resume from the last seen index, and treat the client cache as a derive-only replica.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Framing the problem
This is a client-architecture question. Four threads matter: transport of fragments into the app, the shape of client state, the cost of painting a huge transcript, and recovery when the socket dies. I'll state assumptions first, since they drive everything downstream.
Assumptions: 30–100 fragments per second per active generation; up to ~1,000 messages per conversation, individual messages up to 10k+ tokens; one active generation per conversation but several tabs open; target 60 fps and first-fragment paint within ~16 ms.
API contract
GET /conversations?cursor=…
GET /conversations/:id/messages?before=cursor # paged, newest-first
POST /conversations/:id/stream { clientMsgId, parentId, parts, action }
GET /messages/:id/stream?after=seq # resume
POST /messages/:id/stop
Stream events are typed and ordered: start {messageId, parentId}, delta {seq, text}, end {reason}, error {code, retryable}. The server persists fragments to a durable per-message log keyed by messageId with monotonically increasing seq.
I'd use SSE carried over fetch + a ReadableStream reader, not EventSource, because I need a POST body, auth headers, and cancellation via AbortController. WebSockets add bidirectionality I don't need and complicate proxy/auth handling. clientMsgId is an idempotency key so a retried send can't duplicate a message.
Client components
fetch/SSE ──► StreamClient ──► FragmentBuffer ──► Store (normalized)
(parse, seq (rAF flush) │
dedupe, resume) ├─► IndexedDB cache
├─► BroadcastChannel (tabs)
└─► React tree
Sidebar
VirtualLog
MessageRow (memo)
MarkdownBlocks
Worker: highlight
KaTeX: closed math only
StreamClient is the only place that knows about the network. Components subscribe to slices, never to raw sockets.
Data model
The transcript is a tree, not a list — edits and regenerations fork it.
type Conversation = {
id: string;
rootId: string;
activeLeafId: string; // branch currently displayed
title: string;
updatedAt: number;
sync: "synced" | "pending" | "conflict";
};
type Message = {
id: string; // client id until server confirms
clientId: string;
parentId: string | null;
children: string[]; // siblings = edits / variants
role: "user" | "assistant" | "system";
parts: Part[]; // text | image {url,w,h} | code
status: "optimistic" | "streaming" | "done" | "stopped" | "error";
lastSeq: number; // resume cursor
createdAt: number;
};
State is normalized as conversationsById + messagesById. The rendered thread is derived by walking from activeLeafId up parentId and reversing — so switching branches is a pointer change, not a data copy. Using Zustand with per-id selectors (Redux Toolkit is equally fine) means a streaming message bumps only its own row.
From bytes to pixels
- Buffer per frame.
FragmentBufferappends raw deltas to a string and flushes to the store insiderequestAnimationFrame. This caps store writes at 60/s and typically fewer, and React's automatic batching collapses the rest. The first delta of a message bypasses the buffer and flushes synchronously so the first fragment paints immediately. - Incremental Markdown. Split the accumulated text into top-level blocks (paragraph, fenced code, list, table) at the block boundary. Closed blocks are parsed once and memoized by content hash; only the trailing open block re-parses each flush. Per-frame cost is then O(size of last block), independent of message length.
- Defer expensive rendering. An open code fence renders as plain monospace; syntax highlighting (Shiki/Prism) runs in a Web Worker when the fence closes. Math renders only once its closing delimiter arrives — half-parsed
$$blocks cause visible flicker. Remote images reserve space using storedwidth/height. - Don't block the composer. Non-urgent store updates are wrapped in
startTransitionso keystrokes stay synchronous. The composer holds its own local state and never subscribes to the streaming message.
Rendering very long logs
- Virtualize with variable heights (TanStack Virtual / react-virtuoso). Measure rows with
ResizeObserver, cache heights by(messageId, contentHash), overscan 3–5 rows. Heights of offscreen streaming messages are estimates until they scroll into view. - Page in history. Fetch older pages when scroll approaches the top; after prepending, adjust
scrollTopby the inserted height to keep the viewport anchored. Landing on a conversation starts at the latest leaf. - Stick to bottom only if already at bottom. Pin auto-scroll while the user is within a small threshold of the end; otherwise show a "jump to latest" affordance.
content-visibility: autoon rows is a cheap complement that skips layout/paint for offscreen content.
Failure and consistency
- The server owns generation. A dropped SSE connection does not stop it.
- On disconnect: reconnect with exponential backoff + jitter, then
GET /messages/:id/stream?after=lastSeq. Duplicate or out-of-orderseqvalues are dropped by comparing tolastSeq. If resume is refused, fetch the message as a completed record. - Optimistic user messages render immediately with
clientId; reconciliation swaps in the server id onstart, and the idempotency key prevents double-send on retry. - Authority lives on the server. IndexedDB is a read cache (stale-while-revalidate, versioned schema for migrations); offline writes queue and replay in order.
BroadcastChannelpropagates id and status changes across tabs so two tabs can't both stream the same message.
Trade-offs
| Decision | Choice | Cost |
|---|---|---|
| Transport | fetch+SSE | simpler than WS; stop needs a second POST |
| Store | Zustand, normalized | less tooling than Redux |
| Cache | IndexedDB | fast cold start; eviction + migrations |
| Highlighting | worker, post-close | no jitter; slight delay on final render |
| Buffering | rAF flush | token granularity coarser than arrival |
Common mistakes to avoid in the interview: modeling history as a flat array that breaks branching; calling setState per token; re-parsing the entire message Markdown on every fragment; forgetting that stop-and-resume needs a server-side sequence; treating the browser cache as source of truth.
Follow-ups I'd expect: how branch selection interacts with pagination (walk leaves, not pages), how you'd test streaming under throttled networks (inject fake stream clients), and how cost changes when a message is 100k tokens (chunk blocks by byte size, not just block boundary).