Skip to content

How to design a ChatGPT-style chat (frontend)

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Practice this question

The problem

A chat screen where someone sends a message and the assistant's answer arrives word by word for about 20 seconds, with a stop button, a retry, and a list of past conversations. The answer turns on treating a reply as a long-running stream with a definite end state: text is appended as it arrives, formatting and sanitizing run again on what has arrived so far as text lands, and the message box keeps answering keystrokes the whole time.

Clarifying questions

AskWhy it mattersA typical answer

Does the reply have to appear word by word, or can it show whole once it's ready?

Word by word is most of the question: a stream to read, a reply that's half there, formatting that's half finished. A whole reply is one request and one draw.

Word by word. First words within 1 to 2 seconds, and a typical reply of about 500 tokens takes around 20 seconds to arrive, so a spinner for the whole time isn't acceptable.

Does the server already stream, and in what shape? Or do I pick how the reply is delivered?

If the server streams typed events over HTTP, the client's job is to read them well. If the transport is open, choosing it is part of the answer.

You pick. The server can answer a POST with a stream of events typed start, text, done and error, and it can stop a reply in progress when asked. How the model runs is out of scope.

What's in a reply: plain text, or formatting like lists and code blocks?

Plain text can be appended as it comes. Formatting means parsing text that's still growing, and drawing markup from a source we don't trust.

Markdown-style formatting with lists and code blocks. The reply is model output, so it's untrusted until it has been sanitized.

Do conversations need to follow the person across devices, or is one browser enough?

Across devices means the server is the home for conversations and the browser keeps little. One browser opens the door to storing everything locally, with its size limit.

Across devices: someone closes the tab and opens the chat the next day on another machine, expecting all their conversations in the list. Sign-in itself is out of scope.

When someone presses stop, does the server need to stop too, or is it enough to stop showing text?

It decides whether stop is a local abort or a request to the server as well, and what the saved conversation holds for that reply.

Both. Stop should end generation on the server, and the partial text should remain in the conversation as a stopped reply that can be retried.

Can someone send a second message before the current reply has finished?

Two replies streaming into one conversation at once complicates the state and the view. Blocking or canceling is simpler, and the interviewer may want you to choose.

A single in-flight reply per conversation. Say whether a second send gets blocked or stops the first one, and why.

Who uses it, and with what?

Keyboard use and screen readers change the markup and how a finished reply is announced, and phones have less processing headroom for a growing page.

Keyboard and mouse, desktop and phone browsers. A screen reader user should learn that a reply has arrived without hearing each word as it lands.

The requirements menu

RequirementScopeWhy

Send a message and see the reply appear word by word

Core

The defining behavior. It brings the stream, the growing reply and the responsiveness problem with it.

Stop a reply while it is still arriving

Core

A reply takes around 20 seconds to arrive, long enough that people change their minds. Stop has to reach the server, not just the screen.

Retry a reply that failed or was stopped

Core

A reply takes around 20 seconds to arrive, so a network drop mid-reply is a case to design for. Retry gives a cut-off reply a way forward without retyping the message.

Come back to past conversations from a list

Core

Conversations outlive the tab and the device, so the list is paged from the server and the open one is cached.

Show formatted replies with lists and code blocks

Core

Formatting while text is still arriving is where the draw cost and the sanitizing question come from.

Keep a reply arriving after the page reloads

Optional

Take it if the interviewer raises it: it needs the server to keep the stream and the client to ask for it on load. Leave it out of the first design; a reply lost on reload is a known gap, not a core failure.

Keep an unsent draft when the tab closes

Optional

Cheap to take: a draft is small and belongs in the browser's key-value storage. Leave it if time is short, since it changes nothing about the stream.

Edit a sent message and regenerate from that point

Optional

Take it for a product where people refine prompts. It turns the conversation into a tree of branches, which complicates the message store and the list, so leave it in a short round.

Copy a code block with one tap

Optional

Small and expected in a code-heavy chat. Take it as a detail of the reply view once the stream and the end states are settled.

Search across past conversations

Optional

Leave it: the search runs on the server, and the client side is a results list, which teaches the interviewer little about streaming.

Sign-in and accounts

Out of scope

Assume an authenticated session exists and each request carries it.

How the server runs the model

Out of scope

The client sees a stream of events; GPU scheduling and model serving are a backend round.

Uploading files and images

Out of scope

Uploads bring their own progress, size and preview questions that would crowd out the stream.

Sharing conversations with others

Out of scope

Links, permissions and a public read view are a separate feature.

Non-functional requirements

RequirementWhat it forces

The first words of a reply show within 1 to 2 seconds

The response must be read as it arrives, so the request is a stream, not a body that resolves at the end. The reply view appears in a waiting state the moment the message is sent, and the first text event replaces it.

Typing and scrolling answer within 200 milliseconds while a reply streams

Work per arriving piece must stay small and flat as the reply grows: append rather than re-parse, and coalesce the paints. Interaction to Next Paint measures the time from the keystroke to the next frame, so anything long on the main thread shows up in that number.

Model output is treated as untrusted text before it is drawn

Formatted replies pass through a sanitizer before they become markup, and the sanitizer runs on the accumulated text, since a harmful tag may be split across two pieces. Plain text pieces go in as text nodes, not as HTML.

Usable with a keyboard, with new replies announced to screen readers

Stop and retry are real buttons reachable by Tab, the message box keeps focus during streaming, and a polite live region announces that a reply has finished rather than reading out each piece as it lands.

Estimates

QuantityWorkingResultWhat it sizes

Pieces of text per second during a reply

500 tokens / 20 seconds = 25 tokens a second

About 25 a second

If each token became a separate screen update, the page would be redrawing about 25 times a second for 20 seconds. That is the rate the batching has to absorb.

Screen updates one reply causes

Unbatched: one per token = 500 updates. Batched to at most one update per 200 ms (the keystroke budget): 20 seconds / 0.2 seconds = 100 updates. Batched per animation frame, the count depends on the display's frame rate and on how the pieces cluster, so it isn't worked out here.

500 without batching, about 100 or fewer with it

The reply view's update count. The number itself matters less than what each update costs: an append is cheap, a full re-parse of the reply grows with its length.

Messages that fit in the browser's key-value storage

5 MB per site divided by 1 KB per message = 5,000 messages

About 5,000 messages

Why localStorage is for drafts and settings, not history. A heavy user with many code-filled replies can reach that limit, and the write that goes over it throws.

Wait at a spinner without streaming

A reply takes about 20 seconds to generate, and the System Design Newsletter puts the unstreamed wait at 10 to 30 seconds

10 to 30 seconds of nothing on screen

The gap between the first-words target of 1 to 2 seconds and what a whole-body response delivers. It is the reason the request is a stream.

Core entities

EntityWhat it holds

Conversation

One thread in the list, owned by the server and shown by title.

Message

One turn in a conversation, from the person or the assistant.

Reply in progress

Client-side state for the one assistant message currently streaming in a conversation.

Conversation list on the client

What the sidebar knows: a page of conversations and where the next page starts.

The API

EndpointNotes

POST /conversations/{id}/messages { text } → a stream of events: start, text pieces, done or error

One request per sent message; the response body is an event stream rather than a single JSON body. The client reads it with fetch and a body reader so it can send a POST body and inspect the status before reading. start carries the new message id, text carries a piece to append, and done or error closes the reply. A stream that ends without either is treated as failed.

POST /conversations/{id}/messages/{message_id}/stop → { stopped }

Called together with aborting the fetch in the browser, so the server stops generating and the partial text is saved as stopped. The client treats a non-OK answer as a stop that still happened locally, and lets the next load of the conversation show the server's view.

POST /conversations/{id}/messages/{message_id}/retry → a new stream of events

Asks for a fresh reply to the same user message. It replaces the stopped or failed message in the view, and its stream is read exactly like the first one.

GET /conversations?cursor → { conversations, next_cursor }

Pages the sidebar newest first. The client keeps next_cursor and asks for more as the person scrolls the list; a null cursor means the end.

GET /conversations/{id}/messages?before={message_id} → { messages, has_more }

Loads older messages when the person scrolls up, keyed by the oldest message already on screen rather than by page number, so a new message at the bottom doesn't shift the pages.

The high-level design

sendwhole replyMessage boxServerReply view

Step 1 of 5

Message box, server, reply view

Start with the shape that works for any form: the message box sends a POST, the server answers with the whole reply, and the view draws it. It shows the data flow in one line, and it fails the first requirement at once: for a reply that takes about 20 seconds to generate, the person watches a spinner for the whole time, and the first words are nowhere near the 1 to 2 second target.

sendabortGETstreampagespiecesvisiblemessagedoneMessage boxReply controllerStop buttonConversation listServerMessages by idMessage listReply viewLive region
The whole design

What breaks first

The deep dives

A reply that arrives word by word. Someone sends a message and the answer streams in over about 20 seconds, with a list and a code block in it. How does each piece of text get from the server onto the screen, and what in your view gets slow first?

A concept that helps here: Streaming responses in the UIA concept that helps here: Batching UI updatesA concept that helps here: WebSockets, server-sent events and polling

A reply that stops halfway. Halfway through a reply one person presses stop, and in another chat the network drops and the text stops arriving. What does each of them see, what gets saved, and what happens when they press retry?

A concept that helps here: Partial failure in the UIA concept that helps here: Debounce and request cancellationA concept that helps here: Reconnect and resume

A very long conversation. One conversation has been running for weeks, full of long replies with code, and now typing in the message box lags while a new reply streams. What does the page do with all those messages, and what did you give up to keep it fast?

A concept that helps here: List virtualizationA concept that helps here: Pagination and infinite scrollA concept that helps here: Core Web Vitals

Where conversations are kept. Someone closes the tab in the middle of the week and opens the chat the next day on a laptop, expecting all their past conversations to be in the list. Where do the conversations live, which copy is the truth, and what happens to a reply that was still streaming at the moment the tab closed?

A concept that helps here: Where state livesA concept that helps here: Client caching and normalized storesA concept that helps here: Offline-first storage

Concepts this guide uses

Sources

  1. Chrome for Developers: Best practices to render streamed LLM responses
  2. MDN: Using server-sent events
  3. MDN: EventSource
  4. MDN: Using readable streams
  5. MDN: AbortController
  6. MDN: Storage quotas and eviction criteria
  7. MDN: IndexedDB API
  8. MDN: ARIA live regions
  9. web.dev: Interaction to Next Paint (INP)
  10. web.dev: Web Vitals
  11. AI SDK: Chatbot resume streams
  12. The System Design Newsletter: ChatGPT system design
  13. sdeoffer: AI chat assistant system design
Sign in to report a mistake