Design an LLM Chat Service
How to design an LLM chat service: streaming replies, sharing a fixed GPU pool, building context and safety checks.
On this page
An LLM chat service lets a user send a message to a language model and read the reply as it is generated. Interviewers ask for it because the model servers behave differently from ordinary web servers: the GPUs are expensive and slow to add, each reply takes several seconds, and every request carries the whole conversation so far.
The design has to deliver a long reply over a connection that can drop, share a fixed GPU pool between free and paid users, fit a long conversation into the model's limited input and run safety checks. The steps follow A Framework for Any Design, and you should try each "Your turn" box before reading the answer.
Clarify the problem
Design a chat assistant product on top of a language model.
I will assume the model exists and I build the product around it. Do we run the model servers ourselves, or call an outside API?
You run the model servers on your own GPUs.
How many users are there, and are there free and paid tiers?
There are 10 million daily users who send about 10 messages each, and both tiers exist.
Then GPU capacity is the scarce resource. My priorities are fast first words, replies that survive a dropped connection, paid users who keep working during overload, and a safety check on every input and output. I will leave out file uploads, tools and web search.
- Functional requirements: a user can start a conversation, send a message, read the streamed reply, stop it, reopen past conversations, and edit a message or regenerate a reply.
- Non-functional requirements: the first words appear within 1 second for most requests, a reply survives a reconnect, no user message is lost, free users are throttled before paid users, and all input and output passes safety checks.
- Out of scope: training the model, file uploads, tool use, web search and voice.
Estimate the scale
Model cost depends on the number of tokens processed, so the estimate counts tokens. The figures below are assumptions.
- Message rate: 10 million users sending 10 messages is 100 million messages a day. Divided by 86,400 seconds, that is about 1,200 messages a second on average and about 3,500 at a peak of 3 times the average.
- Tokens per request: a request has about 2,000 input tokens (instructions plus history) and 500 output tokens. A free user's daily budget of 25,000 tokens covers about 10 such messages, and input tokens count because they cost GPU time too.
- Token rate at peak: 3,500 × 500 is 1.75 million output tokens a second.
- Open streams: a model replica generates about 50 tokens a second per stream, so a 500-token reply takes 10 seconds. The streams open at once are the arrival rate times the duration: 3,500 × 10 = 35,000 at peak.
- Storage: one exchange needs about 400 B for the message, 2,000 B for the reply and 600 B of metadata, which is 3 KB. That is 300 GB a day and about 110 TB a year.
A model replica (one copy of the model on its GPUs) runs 40 streams at once, each at about 50 tokens a second. How many replicas cover the peak output rate?
- 3,500 messages a second at peak
- 500 output tokens per reply
- One replica: 40 streams × 50 tokens a second
Show the working
- Peak output: 3,500 × 500 = 1,750,000 tokens a second
- One replica: 40 × 50 = 2,000 tokens a second
- 1,750,000 ÷ 2,000 = 875, which rounds to 900; the average of 1,200 messages a second needs about 300
Estimate 900 (anything from 300 to 3000 is a good answer)
The streams give the same answer: 35,000 ÷ 40 = 875.
Write the endpoints for sending a message and streaming the reply. What happens when the connection drops halfway through a reply, and what does an overloaded server return?
Compare with a model answer
Sending a message is a POST that is answered with a server-sent event stream of numbered chunks, and a resume endpoint accepts the id of the last chunk the client saw. A client-generated message id makes retries safe. An overloaded server returns 429 with a Retry-After header.
Define the API Optional
Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.
POST /conversations 201 { "conversation_id": "c42" }
POST /conversations/{id}/messages Accept: text/event-stream
body: { "content": "Plan three days in Lisbon",
"client_msg_id": "m-7f3a", makes a retry safe
"parent_id": "a19" } the reply this message follows
200 event stream:
event: start data: { "user_msg_id": "u20", "reply_id": "a21" }
id: 1 event: delta data: { "text": "Day one:" }
id: 2 event: delta data: { "text": " start in Alfama" }
...
event: done data: { "finish": "complete", "tokens_out": 520 }
400 message too long
429 Too Many Requests Retry-After: 30 { "reason": "budget" | "busy" }
GET /replies/{reply_id}/stream Last-Event-ID: 180
200 event stream from chunk 181, or the whole reply if it has finished
POST /replies/{reply_id}/stop stops generation, keeps the text so far
GET /conversations?cursor=... newest first
GET /conversations/{id}/messages?before=...The API decision worth arguing is server-sent events instead of WebSockets. Streaming a reply sends data in one direction only. Server-sent events are plain HTTP, so they pass through existing proxies, and they define resuming, because a reconnecting browser sends the Last-Event-ID header. A WebSocket would add two-way traffic that this product does not need (see real-time communication).
Sketch the conversation and message records. How do you represent "regenerate this reply" and "edit my earlier message", and where do the tokens live while a reply is still streaming?
Compare with a model answer
Messages form a tree, so a regenerated reply or an edited message becomes a new sibling under the same parent. Tokens that are still being generated live in a short-lived stream buffer, and the finished reply is stored once in the message table.
Model the data
conversations -- partition key: user_id
user_id, conversation_id PRIMARY KEY
title TEXT
updated_at TIMESTAMP -- used to list newest first
summary TEXT NULL -- summary of older turns, see deep dives
summary_upto message_id NULL
current_leaf message_id -- the branch the user is viewing
messages -- partition key: conversation_id
conversation_id, message_id PRIMARY KEY -- time-ordered ids
parent_id message_id NULL
role VARCHAR(10) -- user | assistant
content TEXT
tokens INT
status VARCHAR(10) -- streaming | complete | stopped | blocked | failed
usage -- one row per user per day
user_id, day, tokens_in, tokens_outThe access patterns are to append a message, to read one conversation in order and to list a user's conversations by recency. None needs a join, and the data grows by about 110 TB a year. A wide-column store such as Cassandra, keyed by conversation, fits this pattern, as it does in Design a Chat App. The stream buffer is an in-memory log for each reply that expires 10 minutes after the reply finishes.
Sketch the components between the user's phone and the GPUs. Where are token budgets checked and context built, what chooses the replica, and how do tokens travel back to the phone?
Compare with a model answer
A gateway checks the token budget. A chat service saves the message, builds the context and runs the safety checks. An inference router queues requests by tier and places them on replicas, and the tokens return through a stream buffer.
High-level design
- budget left
- 13,000
1A free user sends a message. She has 16,000 tokens left of her 25,000 daily budget, and the gateway reserves 3,000 of them: the 2,000-token context estimate plus a 1,000-token reply cap.
- budget left
- 13,000
2The chat service saves the message first, keyed by
client_msg_id, so it cannot be lost and a retried POST finds it.- context
- 2,100 tokens
3The chat service builds the context from the instructions, the summary and the recent turns: 2,100 tokens.
- context
- 2,100 tokens
4A fast input classifier checks the message before any GPU time is spent, and this one passes.
- context
- 2,100 tokens
- queue wait
- 0.3 s
5The router queues the request as free tier and sends it to the replica that served this conversation last, which probably still holds the prompt prefix.
- first words
- 0.8 s
- chunks sent
- 42
6The replica reads the prompt and starts generating. Numbered chunks land in the buffer, and the chat service checks each sentence before forwarding it, so the first words arrive at about 0.8 seconds.
- client saw
- 180
- generated
- 230
7The phone loses its connection at chunk 180, and the replica keeps writing chunks into the buffer.
- client saw
- 230
- generated
- 230
8The phone reconnects with
Last-Event-ID: 180, possibly to another chat server, which replays chunks 181 to 230 and then follows the live stream.- tokens
- 2,100 in + 520 out
- budget left
- 13,380
9The reply finishes at 520 tokens and is saved once, and the budget refunds 380 of the 3,000 reserved tokens.
10In another reply, the replica dies at token 300. The router sends the prompt plus those 300 tokens to another replica ahead of new requests, and generation continues from token 301.
11At peak the free queue's expected wait passes 10 seconds, so new free requests get a 429 response while paid requests keep flowing.
Deep dives
Streaming a reply so that it survives reconnects
A reply takes about 10 seconds to generate, and mobile connections drop often. If generation is tied to the HTTP connection, a dropped connection loses the half-finished reply and wastes the GPU time already spent on it.
The fix is to separate generating a reply from delivering it. Generation writes numbered chunks into a per-reply buffer, whether or not anyone is listening. Delivery is any chat server forwarding chunks from that buffer. A reconnecting client sends the number of the last chunk it saw, and whichever server receives the request replays everything after it and then follows the live stream.
Three details matter. First, a retried POST with the same client_msg_id attaches to the existing reply instead of creating a second one (see idempotency). Second, a stop request frees the replica's batch slot immediately, but a disconnect does not, because the user usually returns for the reply. Third, if a chat server crashes, the buffer still holds every chunk, so another server that finds the reply stuck in the streaming state with no heartbeat can finish delivering it.
Sharing a fixed GPU pool
You cannot autoscale out of a traffic peak, because new GPU capacity takes minutes to start and may not exist, so the system must decide who is served when demand exceeds a fixed pool. Four mechanisms work together.
Continuous batching is how one replica serves many streams. In each step the replica produces one token for every stream in its batch, so 40 streams cost little more per step than one. Continuous batching adds new requests between steps and frees a slot the moment a reply ends, instead of waiting for the longest reply in a fixed batch. The limit is memory: each stream keeps per-token state in the attention key/value cache, so an 8,000-token conversation takes about four times the memory of a 2,000-token one.
Admission control limits how much work enters the pool. The router keeps a queue per tier and estimates the wait as the queued tokens divided by the pool's throughput. When the estimated wait for the free tier passes 10 seconds, new free requests receive a 429 response with a retry time. An immediate "busy" answer is better than a timeout that arrives after the user has waited.
Token-based rate limits keep any one user from taking the pool. A per-user token bucket counts tokens and not requests. The gateway reserves the input tokens plus the output cap when the request arrives and refunds the difference when the reply ends.
Priority tiers decide who is served first. The router fills free slots from the paid queue first but reserves a fixed share for free requests, so free users slow down but are not starved.
| Option | Good at | Bad at | Pick it when |
|---|---|---|---|
| Queue everything | No request is refused. | Waits grow without limit, and users who give up and resend add even more load. | Only as one part of the design, never as the only control. |
| Shed by tier when the wait is too long Usual default | Load stays at what the pool can serve, paid users are protected, and errors are fast and clear. | Free users see refusals at peak. | This is the right choice for a product with tiers. |
| Degrade the work | Everyone gets some answer, for example a shorter reply or one from a smaller model. | Quality drops without the user having chosen it. | Together with shedding, for the free tier at peak. |
Building the context for each request
The problem is that the model remembers nothing between requests, so each request must carry the instructions and the conversation so far inside a limited context window. Longer prompts cost more, delay the first word and can make answers worse (see context rot), so each request gets a fixed budget. Here the budget is 8,000 tokens: 1,000 for instructions, 1,000 for the reply, 500 for a summary and 5,500 for recent turns.
A 40-turn conversation at about 600 tokens a turn is 24,000 tokens, so most of it cannot be sent. There are three ways to handle that.
Truncation drops the oldest turns. It is trivial to build, but the model forgets everything early in the conversation, including the user's original goal.
A rolling summary keeps the gist of the old turns. When the recent turns pass about 4,500 tokens, a background job folds the oldest 2,000 tokens into the stored summary with a small model and records the last message it covered. This keeps the main facts for the price of an occasional extra model call, although the summary can lose details.
Retrieval over old turns indexes every turn and adds the most relevant ones to the prompt. It can recover a detail that a summary dropped, but it needs an index and adds latency (see Design a RAG System). A rolling summary is the right default for most chat products, with retrieval added only when users expect exact recall of old details.
Prompt order affects cost. A model server can reuse the work it did on a recent prompt prefix, but only if the new prompt matches the old one token for token from the start. For that reason the prompt puts the fixed instructions first, then the summary, then the turns, so that consecutive requests share a long prefix between summary refreshes. The router also sends a conversation back to the replica that served it last, using consistent hashing on the conversation id.
Where to run the safety checks
Every message and every reply must be checked (see guardrails), but a check in the wrong place either delays every user or lets harmful text reach the screen.
The input check runs before the request enters the queue. A small, fast classifier reads the message, so a blocked request uses no GPU time.
For the output check there are three placements. Checking only the finished reply is simple, but the user has already read up to 10 seconds of unchecked text. Checking every token is too slow and too noisy for a classifier to judge. The compromise is to hold each sentence back until it passes the classifier, which adds a fraction of a second. Only chunks that passed are replayed to a resuming client. If a later sentence fails, the service stops generation and sends a retract event that makes the client replace what it showed.
If the safety service is down, the system fails closed and pauses new generations. This turns a classifier outage into a product outage, so the classifier runs redundantly.
Bottlenecks and failures
At 10 times the load, or 35,000 messages a second at peak, the gateway, chat service and store scale out. The GPU pool is the real limit: it would need about 8,750 replicas, which may be impossible to buy or power. The remaining levers are shorter replies and smaller models.
| When this fails | What happens | What you do |
|---|---|---|
| A GPU replica | The 40 streams on it stop in the middle of their replies. | The router resends each prompt plus its tokens so far to other replicas, ahead of new requests. |
| A chat server | The client connections on it drop. | Clients resume on another server, and orphaned replies are finished from the buffer. |
| The stream buffer | Chunks that are in flight are lost and resuming fails. | Replicate the buffer, and if it is lost anyway, mark those replies failed so users can regenerate. |
| The safety service | New generations pause because the system fails closed. | Run the classifiers redundantly. |
| The conversation store | New messages cannot be saved. | Refuse new messages, because answering an unsaved message would lose it. |
What a strong answer sounds like
| Level | What the answer does |
|---|---|
| Junior | A web server calls the model and keeps the history in a database. |
| Mid-level | The answer streams with server-sent events, rate-limits requests, truncates history and queues requests in front of the model. |
| Senior | The answer counts in tokens, sizes the GPU pool, separates generation from delivery, explains batching and its memory limit, sheds load by tier, and places safety checks by cost. |
It is peak hour and the GPUs are full. What happens?
The pool is fixed for the next few minutes, so I have to decide who waits. The router keeps a queue per tier and estimates the wait from queued tokens. When the estimate for free users passes 10 seconds, the gateway returns 429 with a retry time, and paid users keep their slots.
Follow-up questions
How do you measure whether you are meeting the latency goal?
Track the time to the first token and the tokens per second for each tier, and split the first figure into queue wait and model time. If queue wait rises while model time stays flat, the problem is capacity and not code speed.
How does regenerating a reply work?
The service adds a new sibling of the old reply under the same parent message and runs the context-building step again. The current leaf then points to the new reply, and the old one stays reachable as another branch.
What happens when the user presses stop?
The client calls the stop endpoint, and the router frees the replica's batch slot at once. The text generated so far is saved with the status stopped. The user is charged only for the tokens actually produced, so the gateway refunds the rest of the reserved budget.
How would you add memory across conversations?
After a conversation ends, a background job extracts a few facts about the user and stores them, and the most relevant ones are added to later prompts within the context budget. Users must be able to see and delete these facts (see memory).
After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".