Skip to content

    Frontend System Design

    Front-End Case Study: AI Chat Application

    Design the front end of an AI chat app from its parts: streaming, message model, tool calls, safe rendering, Stop and Regenerate, with a runnable assembly lab.

    By Published 20 min read

    • frontend-system-design
    • case-study
    • ai
    • chat
    Share

    What you'll learn: By the end of this case study you will be able to design the client side of an AI chat application by assembling parts you already know: a stream client, a message model with attempts, a tool-call registry, a safe renderer and a cancellation rule. You will see that the design work is in the seams between them: how a stream's endings map onto message statuses, what Stop and Regenerate do to a stream that is still open, and which text is allowed to become markup.

    Think of live captioning in a courtroom. Words appear as they are spoken. Sometimes the speaker stops mid-sentence and the caption must keep what it has. Sometimes the line drops and the caption has to say so, not pretend the sentence ended. Sometimes a transcript is requested again from the start and the old, late words must not leak into the new copy. An AI chat screen is that captioner: a text that arrives in pieces, ends in several ways, and may be redone.

    This is an educational reference design, not the verified internal architecture of any company or product. It is a generic chat assistant for a store's dashboard. The model is fake (a hand-driven feed of frames), the stream format is the one invented by the llm-stream-client lab, and every number is illustrative.

    This case study does not re-teach its parts. Each has its own lesson and lab, and this lesson links them and builds only what sits between them: AI-Powered Frontend Architecture (the split between browser, server and provider), Streaming LLM Responses in the Browser, Chat Interface State and Message Model, Long-Running Jobs and Cancellation in AI UI, Tool Calls and Generative UI and Prompt Injection and Output Safety in the UI. The method follows the case-study method lesson. For a chat between people, which has a different set of problems, see the web chat case study.

    The core idea

    1. A chat screen is five small models and some glue. The stream turns bytes into events. The message model says what is on screen. The registry says which tool calls are allowed. The renderer says which text may become markup. The cancellation rule says what Stop means. Each is simple alone; the failures live at the joins.
    2. Every join has a vocabulary mismatch. A stream ends in five ways; a message has four statuses. A stream knows nothing about attempts; a message must. Someone has to write the table, and it is the case study's job.
    3. The model's output is untrusted input, and its tool calls are requests, not commands. The page decides what is drawn and what runs.

    Three illustrations run through the lesson: a minimal example (one question, one streamed answer), a realistic example (a store's support assistant that looks up an order and can propose cancelling it) and a failure example (the user presses Stop, then Regenerate, while a late chunk from the first stream is still on its way).

    Requirements and scope

    Functional. A transcript of user and assistant messages. A composer that sends a message and shows the answer growing. Stop while an answer streams, with the partial text kept. Regenerate on the last answer. A visible state for every answer: waiting, writing, complete, stopped, failed. Tool proposals that run, ask for approval or are refused. Answers drawn as formatted text without letting the model write markup.

    Non-functional. Text must appear as it arrives and the page must stay responsive while it does. No late chunk may change a message it does not belong to. The conversation must survive a dropped connection with its partial text. Nothing the model writes may run script, load an attacker's image or approve its own action. Keyboard and screen-reader use must work, including announcement of new text.

    Out of scope here. Choosing a model, prompts and evaluation, retrieval and citations (AI UX: Trust, Citations and Feedback), voice, file upload, authentication, billing and the server side of the call. The server's role is only what the page needs from it: it holds the provider key, applies limits, and gives the page one stable event format.

    Illustrative sizing

    The numbers below are assumptions for reasoning, not measurements.

    Quantity Assumed value Why it matters
    Messages kept in memory 200 The whole list is not redrawn on a chunk
    Stream events in one answer 300 One state update per event would be 300 redraws of one row
    Active streams per tab 1 Send is refused while a reply streams
    Tool proposals in one turn 0 to 3 Each needs validation, and a write needs a person
    Screen refresh rate assumed 60 per second Updates faster than a frame are wasted

    The expensive part is not storage. It is drawing a text that grows 300 times without redrawing everything around it, and keeping every one of those events attached to the right message.

    The architecture

    Figure 1. The layers of an AI chat client

    An AI chat client: a stream client feeds a pure chat core, which drives a thin UI, a renderer and a tool registryChat UI to Chat core (events); Chat core to Chat UI (state); Chat API to Stream client (event stream); Stream client to Chat core (actions); Chat UI to Renderer (model text); Chat core to Tool registry (proposals); Chat core to Chat API (request); Chat API to Model provider (call)IN THE BROWSERYOUR SERVERChat UI: thin ReactChat UIthin ReactChat core: messages, attemptsChat coremessages,attemptsStream client: bytes to eventsStream clientbytes to eventsRenderer: allow-listRendererallow-listTool registry: schemas, approvalTool registryschemas, approvalChat API: key, limitsChat APIkey, limitsModel provider: streams eventsModel providerstreams eventseventsstateevent streamactionsmodel textproposalsrequestcall

    How to read this: the middle box is the only place with rules about messages. It receives actions from the stream client and events from the UI, and it decides what the next state and the next request are. The renderer and the registry are on the path between the model's text and anything the user sees or anything that runs. The provider is outside your control and only the server talks to it.

    The shape is the one AI-Powered Frontend Architecture argues for: the page does not talk to the provider, because the provider's key and event format belong on the server, and an adapter there turns the provider's events into a small format of your own. The rest of this lesson takes the browser half apart.

    One turn, end to end

    Figure 2. A turn, with a Stop

    sequenceDiagram accTitle: One turn of an AI chat with a user stop accDescr: The user sends a message. The chat core adds the user message and an empty streaming assistant message, builds the request from the earlier turns without the streaming message, and opens the stream with an abort signal. Events arrive and the core appends text to the streaming message, which the renderer draws. The user presses Stop. The core marks the message stopped and aborts the stream. A chunk that arrives later is not read. participant U as User participant C as Chat core participant S as Stream client participant A as Chat API U->>C: send "Explain CDNs" C->>C: add user message and streaming reply C->>A: request from earlier turns, signal A-->>S: delta events S-->>C: delta actions C->>C: append text, row redraws U->>C: Stop C->>C: status stopped, text kept C->>S: abort the signal A-->>S: late chunk S--xC: not read

    How to read this: two things happen at Stop, and both matter. The chat marks the message stopped, so any late action is refused by the message model. The signal is aborted, so the stream client returns at once instead of waiting for another chunk. Either alone would leave a gap.

    The seams, one at a time

    Seam 1: bytes to events

    The stream client is the subject of its own lesson. What this case relies on from it: a response body is a readable stream the page can read piece by piece; a multi-byte character can be cut by a chunk border, so decoding must be told more bytes may follow; and the events are the server's own small format, so a change at the provider does not reach every browser. Anthropic's documentation for its streaming API is a useful reminder of why the last point matters: it lists ping events that may be dispersed through a response, says the API may send an error in the event stream (for example overloaded_error during high usage), and says new event types may be added and code should handle unknown event types gracefully. A client that throws on an event it does not know breaks when the provider adds one. The lab skips unknown events and lists them.

    Seam 2: events to messages

    The message model is the subject of its lesson. It gives a message an id, a role, text, a status (streaming, complete, stopped, error) and an attempt number, and every incoming chunk carries both the id and the attempt. A chunk is applied only to a message that is still streaming and whose attempt matches. It also decides what the next request carries, which is not the list on screen: a streaming or failed message is left out, and a stopped message is kept only if it has text.

    The seam is the mapping. A stream ends in five ways and a message has four statuses, so the assembly has to say which is which.

    How the stream ended Message status Text kept What the user sees
    done event complete yes Nothing special
    error event from the provider error yes The provider's message
    Bytes ended with no terminal event ("cut") error yes "The reply was cut off"
    Connection dropped error yes "Connection lost"
    The user pressed Stop stopped yes "Stopped"

    The "cut" row is the one that is easy to get wrong. A stream that simply ends looks like a finished one to code that only watches for the end of the bytes, and the user then reads half an answer as a whole one. Nothing in the chat model has a status for it, so it becomes an error with a reason a person can read.

    Expected output, captured from a real run (Node 26.13.1; section 4 of the assembly demo):

    === 4. Five endings of a stream, four statuses of a message
    done event         outcome done    -> status complete, text "One two three"
    error event        outcome error   -> status error, text "One two three", error "The service is busy"
    stream just ended  outcome cut     -> status error, text "One two three", error "the reply was cut off"
    connection error   outcome failed  -> status error, text "One two three", error "connection lost"
    Stop after 2 of 3  outcome aborted -> status stopped, text "One two"

    Figure 3. The life of an assistant message

    stateDiagram-v2 accTitle: Lifecycle of an assistant message accDescr: An assistant message starts streaming. A done event makes it complete. Stop makes it stopped. An error event, a cut stream or a dropped connection makes it failed. Regenerate on the last message returns it to streaming with the attempt number increased by one. Late chunks for a message that is not streaming, or from an older attempt, are refused. [*] --> Streaming: send, attempt 1 Streaming --> Complete: done Streaming --> Stopped: Stop Streaming --> Failed: error, cut or dropped Complete --> Streaming: Regenerate, attempt + 1 Stopped --> Streaming: Regenerate, attempt + 1 Failed --> Streaming: Regenerate, attempt + 1

    How to read this: only Streaming accepts new text. Regenerate reuses the same message and raises its attempt number, which is what lets the message model refuse a chunk from the attempt before.

    Seam 3: Stop is a wish, not an off switch

    An AbortController's abort(), MDN says, can abort fetch requests, the consumption of any response bodies and streams. That ends the browser's reading. It says nothing about what the server and the provider do next, and the page cannot see it. Work that continues after the page stops listening is the subject of Long-Running Jobs and Cancellation in AI UI, where the screen sends a separate cancel message and shows a "Stopping" state until the server confirms. Whether a model call stops when a chat's connection closes is the server's decision. The lab's rule is the page's half: keep the partial text, abort the stream, refuse late chunks, and put the partial answer into the next request, because the user saw it.

    Expected output, captured from a real run (Node 26.13.1; section 2 of the assembly demo):

    === 2. Stop: the partial text stays, the stream is aborted, a late chunk changes nothing, and the next request carries what the user saw
    stream outcome: aborted, signal aborted: true
      m1 user      complete  attempt 1 "Explain CDNs"
      m2 assistant stopped   attempt 1 "A CDN serves copies"
    next request: user "Explain CDNs" | assistant "A CDN serves copies" | user "And caches?"

    Regenerate has the matching rule. It is allowed only on the last assistant message and only when nothing is streaming. It raises the attempt number, and the new stream is started for that attempt; the failure example of this lesson (Stop, then Regenerate, then a late chunk from the first stream) is refused twice: the first stream's reader is gone, and if a chunk somehow arrived the attempt would not match.

    Seam 4: a tool call is a proposal

    A model may ask the application to call a tool. Tool Calls and Generative UI treats this as a state machine of its own: the input streams in as partial JSON, is validated against a schema when it is complete, a write tool waits for a person, and a result is validated again before it is drawn or sent back. The streaming documentation of Anthropic describes why the middle step exists: deltas for tool input are partial JSON strings, the final input is an object, and the strings can be accumulated and parsed once the content block ends. A page that parses before the end of the block will parse a broken string.

    This case study does not wire tool parts into the message model, on purpose. The assembly skips a tool_call event it does not understand and lists it, and the typed part, the registry and the approval rule stay in their own lab. What the case does decide is where they sit: between the model's proposal and anything that runs, and always on the page's side of the trust line. OWASP's guidance for LLM applications points the same way: it describes excessive agency as damaging actions performed in response to unexpected, ambiguous or manipulated model output, and recommends limiting the tools an agent may call and their permissions to the minimum, and requiring a human to approve high-impact actions.

    For the realistic example, the support assistant has a read tool (order status) and a write tool (cancel order). The registry lab shows the write tool asking before it runs:

    Expected output, captured from a real run (Node 26.13.1; section B of the tool-call-registry lab):

    === B. a write tool, approved
      start                    input-streaming
      delta "{\"orderId\":\"A-1001\",\"reason\":\"changed_mind\"}" input-streaming
      input-complete           approval-requested
      approve                  input-available
      output {"orderId":"A-1001","cancelled":true,"refundCents":1250} output-available
      screen:      component CancelReceipt {"orderId":"A-1001","cancelled":true,"refundCents":1250}
      to the model: {"type":"tool_result","tool_use_id":"call_b","content":"{\"orderId\":\"A-1001\",\"cancelled\":true,\"refundCents\":1250}"}

    Seam 5: text to markup

    The model's text is untrusted. OWASP's entry for improper output handling describes it as insufficient validation, sanitization and handling of model outputs before they are passed downstream, notes that because the content can be controlled by prompt input this is like giving users indirect access to extra functionality, and recommends treating the model like any other user, encoding output, and using context-aware encoding for where it is used. Prompt Injection and Output Safety in the UI and the llm-output-renderer lab turn that into an allow-list renderer: fixed tags, encoded text, links only to allowed schemes, images only from allowed hosts, and while a reply is streaming only a finished block gets links and images, the unfinished tail being plain text.

    The assembly's React layer uses it and nothing else to draw an assistant message, which is why the renderer's output may be given to React as HTML: it is built from fixed tags and encoded text. The user's own messages are drawn as plain text.

    Expected output, captured from a real run (Node 26.13.1; section 6 of the assembly demo):

    === 6. What the page draws for model text: fixed tags and encoded text, a streaming tail as plain text
    while streaming (70 chars): <p>Order shipped.</p><p class="pending">See [tracking](https://shop.example/track) or [x](java</p>
    when complete:              <p>Order shipped.</p><p>See <a href="https://shop.example/track" rel="noopener noreferrer" target="_blank">tracking</a><span class="host"> (shop.example)</span> or <span class="blocked">x (link removed)</span> &lt;img src=x onerror=alert(1)&gt;</p>
    findings: link-removed, markup-shown-as-text

    The javascript: link was removed, the allowed link was kept with its host shown, and the image tag was shown as text. Nothing that was drawn can run.

    Drawing it quickly and accessibly

    • One row redraws per chunk. Each row reads only its own message through useSyncExternalStore, as the message-model lab does, so a chunk for the streaming message redraws that row and not the other 199. A burst of events inside one frame can be batched: in the stream lab's demo, 40 deltas in one task cost 40 state updates without a batcher and 1 with it, with the same final text.
    • Long conversations are windowed. See List Virtualization and the scrolling rules of the web chat case: do not move a user who has scrolled up, and offer a way back to the latest message.
    • The transcript is a log. MDN describes the ARIA log role as an element that creates a live region where new information is added in a meaningful order, with chat logs as an example, an implicit aria-live of polite and an implicit aria-atomic of false. The lab's list has that role. A streaming answer announces as it grows, which can be a lot to hear; announcing on completion instead is a design choice to test with real screen-reader users, and the lab does not decide it.
    • Stop is a button that replaces Send. It is a real button with a name, reachable by keyboard, and it appears only while a reply streams.

    Persistence

    The transcript that is stored is not the transcript that is sent. The stored one keeps every message with its status and error, so a reload shows a stopped answer as stopped and a failed one as failed. The request is built fresh each turn by the message model's rule. A message that was streaming when the page closed has an unknown outcome and should be restored as failed or interrupted, never as streaming, because no stream is attached to it any more. How to persist and synchronise tabs is covered in State Persistence and Synchronization.

    Failure modes

    What happens What the user sees What the design does
    Stream drops after some text Partial text, "Failed: connection lost", Regenerate Keep the text, mark error, new attempt on request
    Stream ends with no done event Partial text, "The reply was cut off" Treated as an error, not as a finished answer
    Provider sends an unknown event Nothing Skip it and count it
    Provider sends an error event The provider's message Error status, text kept
    User presses Stop Partial text, "Stopped" Abort the stream, refuse late chunks
    Late chunk after Regenerate Nothing Older reader is gone; attempt number would not match
    Model writes markup or a hostile link Text, a "link removed" note Allow-list renderer
    Model proposes a write tool A question with the exact call Registry validates, a person approves

    Build it: an assistant assembled from three labs

    Goal. Drive a whole turn through the real stream client, the real message model and the real renderer, and see the five endings, Stop, Regenerate, unknown events and safe rendering with one fake model.

    Setup. The lab ai-chat-assembly is in the course's example workspace (Node 26, React 19, Vitest 5, jsdom). It imports the other labs by relative path instead of copying them: llm-stream-client, chat-message-model and llm-output-renderer. The code in it is only the glue: Assistant (send, stop, regenerate, and the mapping table above), a hand-driven fake model, and a thin AiChat component that draws assistant text through the renderer. There is no network and no real model.

    cd examples/frontend
    pnpm install
    cd labs/ai-chat-assembly
    pnpm test           # 14 tests: 10 for the assistant, 4 React (jsdom)
    node src/demo.ts

    The parts keep their own labs and goldens, which this lesson does not repeat. Run any of them to see its details: llm-stream-client (chunk borders, five endings, batching), chat-message-model (attempts, stale chunks, the wire list), ai-job-cancellation (what the server does after Cancel), tool-call-registry (validation and approval) and llm-output-renderer (links, images, streaming, tool gating).

    Steps.

    1. Run the tests, then the demo. Section 1 sends a reply whose chunk borders fall inside multi-byte characters and ends complete with the exact text.
    2. Compare section 2 with the output above: Stop keeps the partial text, the signal is aborted, and the next request carries what the user saw.
    3. Compare section 4 with the output above: the stream's endings map onto four statuses, and the cut-off stream becomes an error.
    4. In section 3, a dropped connection leaves partial text marked failed; Regenerate runs attempt 2 on the same message and the second request carries only the first user message.
    5. In section 5, ping, tool_call and usage events are skipped and listed, and the reply completes.

    What the lab does not show. No real provider, no real streaming protocol (the event format is the stream lab's own), no timing, no network and no real browser (jsdom does not lay out, scroll or paint). It does not wire tool parts into the transcript, does not cancel work on a server, does not persist anything and does not batch updates. The text the fake model streams is written for the lab.

    Break it. In src/assistant.ts, in apply, replace the dispatch in case "cut" ({ type: "fail", id, attempt, message: "the reply was cut off" }) with { type: "finish", id, attempt }. A half-written reply is then shown as complete, and the test "a stream that ends without a terminal event becomes an error saying the reply was cut off" fails. Restore the line and run the tests again.

    Trade-offs

    Decision Option A Option B Reference choice
    Where the provider is called From the page From your server Server: key, limits and event format stay there
    Update rate One redraw per event Batch per frame Batch; one row redraws
    A stream that ends silently Treat as complete Treat as an error Error, with a readable reason
    Stop Hide the answer Keep the partial text Keep it and send it with the next request
    Regenerate New message Same message, next attempt Same message, next attempt
    Model text Render as Markdown HTML Allow-list renderer Allow-list renderer
    Tool calls Run what the model asks Validate, then ask for writes Validate; a person approves writes
    Late chunks Trust the stream Tag with id and attempt Tag; refuse the rest

    In practice: a support assistant on a store dashboard

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    A store's dashboard gets a support assistant that answers questions and can look up an order. Support staff report three things in the first week: some answers end in the middle of a sentence and look finished, Regenerate sometimes shows two answers glued together, and an answer once contained a link that was not what its text claimed.

    Starting architecture

    Figure 4. Starting point: the page appends whatever arrives and renders it as HTML

    Starting architecture: every chunk is appended to the last message and the whole text is rendered as HTMLStream to Append to last message (every chunk); Append to last message to Render as HTML (whole text)Stream: chunks inStreamchunks inAppend to last message: no idsAppend to lastmessageno idsRender as HTML: no allow-listRender as HTMLno allow-listevery chunkwhole text

    How to read this: nothing says which message a chunk belongs to, so a late chunk lands wherever the last message is. Nothing says how a stream ended, so a silent end looks like a finish. Nothing limits what the text may become.

    Options considered

    Option What it fixes What it costs Risk
    Debounce and trim the text Looks tidier Cheap Fixes none of the three reports
    Add a done flag and a sanitizer library The cut-off look, some markup A library to trust and keep current Late chunks and the link claim remain
    Message model with attempts, an ending table and an allow-list renderer All three A small core, tests and a renderer The server must keep an event format and say how a stream ends

    The decision

    Field Decision record
    Context Cut-off answers shown as finished, glued answers after Regenerate, a misleading link.
    Decision Tag every chunk with message id and attempt; map the five stream endings to four statuses, treating a stream with no terminal event as an error; draw model text only through an allow-list renderer; tool calls are validated proposals and writes need a person.
    Consequences, good No cut-off answer reads as complete; Regenerate cannot mix attempts; the page controls what becomes markup.
    Consequences, bad The server contract grows (a terminal event is required); there is a core to maintain and a renderer that shows less than full Markdown.
    Revisit when The product needs tables, math or images in answers, or a mobile client must share the rules.

    Rollout and verification

    1. Test orders, not components. Drive the assistant with recorded event sequences: done, error, cut, drop, Stop mid-word, Regenerate with a late chunk, an unknown event.
    2. Ship the terminal event on the server first, so old clients keep working and new ones can tell a finish from a cut.
    3. Watch three counters: replies ending in the cut-off error (a spike points at a proxy or a timeout), skipped unknown events (a new provider event type), and links removed by the renderer (an attack or a prompt problem).
    4. Review the renderer's allow-list whenever the product wants a new kind of content.

    The 2 a.m. failure

    The provider starts sending a new kind of event during a busy period. A client that throws on events it does not know stops reading mid-answer for every user whose answer contains one (illustrative). The assembled client skips the event and lists it, so answers continue; the skipped-event counter climbs and the team sees it.

    First three checks: (1) which event name is being skipped, and since which deploy; (2) did any reply end as cut-off at the same time; (3) does the server's adapter or the client need to learn the event. Mitigation: none needed for the page, because unknown events are not fatal; the adapter can drop the event for old clients. Follow-up: put the event name in the server's contract tests, because documentation says new event types may be added, so the surprise will recur.

    The other side of this topic

    On the back end the same turn is a gateway that holds the provider key, enforces per-user limits, adapts the provider's stream into your own events and decides what to do when the page disconnects: see API Gateway Pattern and WebSockets, SSE and Long Polling. The page's rules are only as good as the server's promises about a terminal event and about what happens after a disconnect.

    Architect's notes

    • Write the endings table first. If a stream can end in a way the message model has no status for, the user will read it wrong.
    • Tag everything with id and attempt. A chunk without them is a bug waiting for a slow network.
    • Keep the provider's format on the server. Your page should depend on your events.
    • Draw model text through one door. A second path that renders it differently is the one an attacker will find.
    • Treat Stop as the page's half of a conversation. Say what the server does next, or admit the page does not know.

    Common mistakes

    • Treating the end of the bytes as a finished answer.
    • Appending chunks to "the last message" instead of the one they belong to.
    • Throwing on an unknown event.
    • Dropping the partial text on Stop or on failure.
    • Sending the streaming message back to the model as history.
    • Rendering model text as HTML, or letting it run a write tool.
    • Redrawing the whole list on every chunk.

    Key takeaways

    • An AI chat client is five small, known parts; the design is in the seams between them.
    • Map a stream's five endings onto the message statuses explicitly; a silent end is an error.
    • Tag every chunk with message id and attempt, so a late chunk is refused.
    • Stop keeps the partial text, aborts the reader, and tells the next request what the user saw.
    • Model text is untrusted: draw it through an allow-list, and treat tool calls as proposals.
    • Keep rules in a pure core with effects, so the awkward orderings are unit tests.

    Practice exercises

    1. A sixth ending. Add a time limit: if no event arrives for a stretch of virtual time, end the stream as dropped. Which status should the message get, and what should the user be offered?
    2. Wire a tool part. Add a tool_call part to the message using the tool-call-registry lab and decide what toWireMessages sends for a tool result.
    3. Break the rule. Remove the attempt check from the chat model, or the abort from stop, and write the test that shows what each protects.
    4. Restore a reload. Persist the transcript and decide how a message that was streaming is shown after a reload.
    5. Announce. Decide when a screen reader should announce a streaming answer, and list what you would test with real users.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments