Design an LLM chat service
Read first: Serving LLMs, Retrieval-augmented generation, Agents and tool calling
A chat turn streams tokens from a stateless model while the transcript lives in your database. Prefill and decode are different costs, the KV cache is what limits concurrency, and a tool call needs an idempotency key. Retrieval is optional. You evaluate it separately from the answer, and you talk about cost as memory and steps.
The product is a conversation. The person types, tokens start appearing, and the next message still remembers the last one. The model does not remember anything. You store the transcript, you rebuild a prompt, and you stream a completion. Everything hard in the design is about that split: what is durable, what is a GPU slot, what may run twice, and what you refuse to invent a number for.
You will not quote a tokens-per-second figure for a named model. You have not measured one, and this page will not make one up. Parameter counts are the same kind of fiction here. Cost is how many sequences occupy memory, how long those sequences are, and how many tool steps a turn is allowed to take.
Requirements
The user is a person in a chat window. Sometimes they have attached documents. Sometimes the assistant should call a tool that touches the world, such as creating a calendar event or sending a message.
Functional requirements:
- Create a conversation and append turns.
- Stream the assistant reply as tokens, and survive a refresh.
- Optionally retrieve passages from the user’s documents and put them in the prompt.
- Run a tool when the model asks, then continue, with a cap on steps.
- Keep history so the next turn sees the previous one.
Non-goals:
- Training, fine-tuning, and a horse-race between model brands.
- Voice, images, and a plugin marketplace. A tool is a function you wrote, with a timeout and a key.
- A vector store as the system of record. Documents have a home. The index is derived.
- Guaranteeing that the model is right. You can guarantee that you stored what it said, that a tool ran once, and that you measured retrieval separately from the reply.
Estimation
Assumptions, and none of them is a model benchmark:
- 1 million user turns a day to start. You can scale the arithmetic linearly later.
- Peak is 4× the average, an evening bulge you state as an assumption.
- A turn that actually generates occupies a model slot for 10 seconds. That is a planning assumption about the slot you reserve, including queueing inside the server, not a claim about how many tokens any model emits.
- You cap a prompt at 6,000 tokens because that is the product limit you are willing to pay memory for. It is not a discovered property of a checkpoint.
- A stored turn, user text plus assistant text, averages 4 KB.
- You keep transcripts 30 days, three copies.
average turns 1,000,000 / 86,400 ≈ 11.6 / s, about 12
shortcut 1,000,000 / 100,000 = 10 / s
peak, 4× 11.6 * 4 ≈ 46 / s
slots, Little 46 * 10 s ≈ 460 in flight at peak
plan for about 500 concurrent sequences
transcripts 1e6 * 4 KB = 4 GB / day
30 days 120 GB
three copies 360 GB
A day is 86,400 seconds, so a million turns is about 11.6 a second, the usual about 12. The 100,000-second shortcut says 10. Four times 11.6 is about 46 turns a second, and 46 times the assumed 10 seconds is about 460 generations in flight. That is what GPU memory has to hold, or you queue, or you shed. Doubling the traffic doubles the slots if the 10 seconds still holds. That is the scaling sentence. It does not require a price or a parameter count.
Disk for the transcript is the small resource. Three hundred and sixty gigabytes is uncomfortable for a laptop and ordinary for a database. The scarce resource is memory on the model servers during those 10 seconds, and you release it when the turn ends. You do not retain a KV cache for 30 days.
Retrieval changes the length. Assumption: the transcript portion is 4,000 tokens and you attach four passages of 500 tokens, which is 2,000 more. The prompt becomes 6,000. If KV-cache memory scales with sequence length, that turn costs 6,000 / 4,000 = 1.5 times the cache of the same chat without the passages, and the prefill reads a longer prompt. Label the linear step: cache growth with length is the relationship to plan with. Layers and batch size multiply it further. You do not need a byte formula you cannot derive.
High-level design
A chat orchestrator accepts the turn, loads the transcript, decides whether to retrieve, builds the prompt, and opens a stream to a model server. Tokens are appended to the transcript as they commit, and also written to the client. Tools run in the orchestrator, not inside the model process. Any orchestrator can resume a conversation by reading the store. The model servers are a pool of slots, each slot a sequence and its cache.
flowchart LR
user[User]
chat[Chat orchestrator]
store[Transcript store]
retrieve[Retriever]
docs[Document source]
model[Model servers]
tools[Tool runner]
user --> chat
chat --> store
chat --> retrieve
retrieve --> docs
chat --> model
chat --> tools
model --> chat
chat --> user
The client connection can be a long HTTP response or a socket. If a process holds the socket, that state wants the same machine or a shared backplane, which is the networking constraint on a sticky connection. Prefer the store as the resume path so a dead orchestrator does not take the conversation with it. The client reconnects, sends the same turn id, and the new process reads what was already saved.
Deep dive
Streaming, prefill, and decode
Serving splits a request into two phases, and the product feels them differently. Prefill reads the whole prompt and is compute-heavy. Decode produces one token at a time and is limited by memory bandwidth, because each new token has to read the attention state of the prompt so far. The KV cache stores those keys and values so decode does not recompute the prompt. It grows with batch size, sequence length, and layers. GPU memory is the constraint. “The API” is not a capacity plan.
Two SLIs fall out of that split. Time to first token includes your queue, retrieval if you did it, and prefill. The gap between later tokens is decode, plus any stall where the server waited on a long neighbor. Observability here is those two series, not a single “latency” average. A user who stares at a blank screen and then gets a paragraph had a slow first token. A user who sees a fast first token and then a stutter is in decode. You cannot tell from one histogram.
Continuous batching is the idea that a server adds a sequence to the batch at each step instead of waiting for the longest one to finish. Paged attention is the idea that the cache is allocated in pages so a finished sequence frees memory without fragmentation. Both are serving-stack details. In the interview, the sentence is: a slot is memory, finished turns have to give it back, and a batch should not sit idle because one prompt was long.
Cancellation is part of capacity. If the user hits stop and you keep decoding, Little’s law still counts that generation inside the 460. Cancel the decode and free the cache. A client disconnect is the same signal.
When the 500 slots are full, shed. A bounded queue of a couple of hundred turns (assumption) absorbs a short bulge. Past that, a retryable error. Load shedding at the orchestrator is how you avoid accepting work you have no memory for. A queue without a limit turns the bulge into a slow death and a bill measured in steps you did not mean to run.
The transcript is the memory
The model is stateless. The next turn loads the conversation from the database and sends it again, up to the 6,000-token cap. That load is a read-your-writes read. A replica that has not caught up will drop the last turn, and the model will answer the wrong question with confidence. Read the transcript from the primary, or from a session that is known to include the write.
When the history no longer fits the cap, summarize the older part in a separate call and store the summary as its own message. The next turn reuses the summary. If you summarize on every turn from scratch, you added a full extra prefill to every message, which is a step and a longer sequence. The summary is allowed to lose detail. The unsummarized tail, the recent turns, stays verbatim.
Stream tokens into the transcript every few dozen tokens (assumption: a small batch, so a crash loses a phrase and not the whole answer). On reconnect, replay the stored text. Do not call the model again for a turn id that already completed. If the turn is still in progress, a single-flight lock on the turn id attaches the new client to the same generation or tells them to wait. Two locks skipped means two generations, two bills in GPU-seconds, and maybe two tool calls.
Prefix reuse is an optimization, not a requirement. If the serving stack can keep the cache for an unchanged prefix, the next turn skips part of the prefill. If it cannot, you recompute. The product still works. Do not invent a hit rate.
Retrieval is optional, and it is not the source of truth
RAG is a path you turn on when the turn depends on documents: chunk them, embed the chunks, retrieve a few, optionally rerank, put the passages in the prompt. The source of truth is the document store, object storage or a database, which you can link as object storage when the bytes are files. The vector index is derived. It can be stale, and it can be rebuilt.
Failures you should name because they look like a model bug and are not:
- A chunk boundary split the sentence that contained the answer.
- The index lags an edit or a deletion, so you retrieve a passage the user has already replaced.
- The nearest neighbor is about the same words and is not evidence.
- The model ignores the passages and answers from somewhere else.
Those are why you do not retrieve on every turn. “Thanks” does not need four passages, and the 1.5× cache above is a real cost on the first-token path. A small gate (the user attached files, or the turn is a question about them) skips retrieval otherwise. Exact nearest-neighbor search will not survive a large corpus. You pick an approximate index knowingly, and you do not quote a recall number you did not measure.
Tools, evals, and the step budget
An agent loop here is model, tool call, observation, until a stop. Cap it. Assumption: 4 model rounds on a turn, then the orchestrator stops and says it could not finish. Each round can grow the prompt and can hold the KV cache the whole time. Four rounds is four times the chance to do something in the world.
A tool that reads is safe to retry. A tool that sends, creates, or deletes is not. Carry an idempotency key derived from conversation id, turn id, and the index of the tool call. The calendar event is created once. A retry of the turn, or a second attempt after a timeout, returns the stored result. Give the tool a timeout. If it can touch production systems, run it behind an allowlist, not behind a sentence in the prompt that says “be careful.” Guardrails are checks. A tool that fails returns the failure as the observation, or the loop stops. It does not get an unbounded retry.
Evals come before prompt edits. A starter set of 100 scripted tasks (assumption about the size of the set, not a score) is enough to begin:
- Did the retriever return a passage that contains the answer? That is a retrieval score.
- Did the reply stay inside the passages you supplied? That is an answer score.
- Did the tool run once, with the arguments you expected?
A prompt change that helps the reply and hurts retrieval is not a win. You will not see it if you only grade the final paragraph. Keep the three numbers separate. Do not tune against the live traffic and call it an eval. The live traffic is where you notice a regression after a change that already passed the set.
Cost, restated without a currency. A turn with retrieval holds about 1.5× the cache of a turn without it, under the length assumption above. A turn that uses all 4 rounds holds a slot longer and may prefill more than once. A disconnected client that you forget to cancel holds the slot for the full 10 seconds anyway. The transcript on disk is the 360 GB. The thing you run out of first is the 500 sequences of cache. Shed there.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Stream tokens and store them as you go | Refresh resumes, and a crash loses a phrase | Extra writes during the turn |
| Recompute the prompt from the transcript every turn | Any orchestrator can serve the conversation | Prefill repeats work a prefix cache might have kept |
| Retrieve on every turn | The model always sees passages | First token waits on search, and the cache grows about 1.5× on the assumed lengths |
| Retrieve only when the turn needs documents | Short chats stay short | A bad gate skips a passage the model needed |
| Cap of 4 tool rounds | A loop cannot spend the evening | Some tasks stop unfinished |
| Idempotency key on write tools | A retry does not create a second event | You store the key and the tool result |
| Shed at 500 in-flight generations | Memory stays bounded | Peak users wait or get a retryable error |
| One latency histogram for the whole turn | A simple dashboard | You cannot tell prefill from decode |
Failure modes
Dependency down. Model servers are out of memory or out of process. Stop admitting at the orchestrator. Do not queue without a bound, and do not retry a turn that already started decoding unless you are willing to pay a second prefill. A retriever outage should degrade to “answer without documents” or a clear error, chosen on purpose. Silent failure looks like a model that forgot the files. A tool timeout is not a model outage. Record it and stop or continue with the observation.
Retry storm. Clients reconnect after a blip and resubmit the turn id. Single-flight plus a stored result means one generation. Without that, every refresh doubles GPU work and can fire the tool again. Bound client retries. A user mashing send is the same storm with a person attached.
Hot partition. One conversation is not hot. One tenant running a batch of long prompts can fill the 500 slots and make the interactive product wait. Cap in-flight generations per tenant, a bulkhead around the shared pool. A single enormous document that retrieves into every turn is a hot key in the index and a length problem in the cache. Cap passages and cap tokens.
Consistency. Transcript lag is the consistency bug: the new turn is missing, the model contradicts itself, the user loses trust. Tool side effects without a key are a different consistency bug, in the world rather than the database. The vector index lagging the document store is expected. Treat it as staleness with a rebuild path, and do not tell the user the index is the document.
Durability. Completed tokens that were only in process memory vanish on a crash, and the client sees a reply that stops mid-sentence and then regenerates differently. Flush tokens in small batches to the transcript store, which is the durable copy. The KV cache is not durable and should not be. Rebuild it from the prompt. A tool that ran and was not recorded will run again. Write the recovery point before you declare the tool finished, the same pattern as any other side effect.
In the interview
First five minutes: the transcript is the memory, the model streams tokens, prefill and decode are different SLIs, concurrency is arrival rate times occupied time and you assumed 10 seconds to get about 460 slots. Retrieval is optional. Tools are idempotent and capped. You do not know a tokens-per-second number and you will not invent one. The bottleneck is GPU memory for the KV cache. The tradeoff is shedding versus a longer queue once the 500 slots are taken.
Skip tokenizers, parameter counts, and a tour of attention. One sentence on paging and continuous batching is enough if they ask how the server uses the GPU.
The question that usually follows is “the user hits stop” or “the same message is sent twice.” Cancel and free the cache, or replay the stored turn. The question after that is “why was the second message slower?” The prompt got longer, prefill grew, and the cache for that sequence grew with it. If you retrieved four passages, you also put search on the first-token path and about 50 percent more length under the assumption above.
Check yourself
What is the difference between time to first token and the gap between later tokens, in terms of the work the model server is doing?
Time to first token includes the wait to get a slot, optional retrieval, and prefill, which reads the whole prompt and is compute-heavy. Later gaps are decode, one token at a time, which is limited by reading the KV cache. One average latency mixes a blank screen with a stutter and you cannot tell which you have.
Under the lesson assumptions, about how many generations are in flight at peak, and what did you refuse to use in that estimate?
1,000,000 / 86,400 is about 11.6 turns a second, the usual about 12. An assumed 4× peak is 11.6 × 4 ≈ 46 a second. Times an assumed 10 seconds of slot occupancy is about 460, so you plan for about 500 slots. The 10 seconds is a capacity assumption. It is not a tokens-per-second measurement, and there is no parameter count in the estimate.
Why does attaching four 500-token passages change the cost of a turn whose transcript was 4,000 tokens?
The prompt grows from 4,000 to 6,000 tokens. If cache memory scales with sequence length, that sequence holds about 1.5 times the KV cache, and prefill reads a longer prompt. First token also waits on the search. You skip retrieval on turns that do not need the documents so you do not pay that on every message.
The model asks the tool runner to create a calendar event, the client retries the turn, and the tool times out once. What has to be true so the user gets one event?
The tool call carries an idempotency key from the conversation, the turn, and the call index. A retry returns the stored event instead of creating another. A timeout does not launch an unbounded second attempt without that key. The step cap still applies, so a stuck tool cannot keep the loop in the GPU forever.
The vector index returns a passage the user deleted yesterday. What is the source of truth, and what do you evaluate?
The document store is the source of truth. The index is a derived structure and it can lag. Rebuild or update it. An eval should score whether the right passage was retrieved separately from whether the reply followed the passages it was given. A single grade on the final paragraph hides which half broke.
Based on: Alex Xu, ByteByteGo volumes; Designing Data-Intensive Applications, Kleppmann and Riccomini; Google SRE book and SRE workbook.