"Design ChatGPT" is not a question about how a language model works. It is a question about serving one: a chat product where each response is a long-lived stream that occupies expensive hardware for ten seconds or more. Training is out of scope, and you should say so in your first minute.
What makes it different from every other design in this series is the unit of cost. A typical web request costs a fraction of a CPU-millisecond. A chat response holds a share of a GPU for the whole time it is generating, and GPUs are the scarce, expensive resource. Capacity, queueing and who gets served first under load are the design.
This page is the product-level design. The mechanics of the model server (prefill, decode, the KV cache, batching) are in LLM inference and serving, and the routing layer is in AI gateways and model routing. We link to them instead of repeating them.
Clarify the requirements
Functional requirements:
- A user sends a message and receives the answer streamed token by token.
- Conversations are saved: users see a list of past chats and can continue one.
- Each reply uses the conversation so far as context.
- Users can stop a generation, regenerate it, or edit an earlier message.
- Plans differ: a free tier and paid tiers get different limits and model choices.
- Basic safety: input and output are checked against content policy.
Out of scope, said aloud: model training and fine-tuning, the model architecture, tools and plugins, file uploads, voice, and billing.
Non-functional requirements:
- Fast first token: the user should see text begin within about 1 to 2 seconds. Total time matters much less, since they read as it streams.
- Steady streaming: a smooth 30 to 50 tokens a second per user.
- Graceful under overload. Demand will exceed GPU capacity at times. The system must queue or shed in a controlled way, not fall over.
- Never lose a conversation. A user's saved messages are durable, even if a generation is interrupted.
- Fair, tiered access. Paid users get priority and higher limits, and one user cannot consume a pool.
- Cost-aware. GPU time is the main expense, so every wasted token is money.
Estimate the scale
Assume 50 million daily active users, each sending 8 messages a day. An answer averages 400 output tokens. The conversation sent as context averages 2,000 input tokens (the history plus the new message). A stored message pair (question plus answer) is about 3 KB.
Request rate: 50M × 8 = 400 million messages a day ÷ 86,400 s ≈ 4,630 per second, about 13,900 per second at 3× peak.
Output tokens: 400M × 400 = 160 billion tokens a day, which is 160B ÷ 86,400 ≈ 1.85 million tokens per second on average.
GPUs: assume one GPU sustains a batch of about 50 streams, each producing about 40 tokens a second, so 2,000 tokens a second per GPU. Then 1.85M ÷ 2,000 ≈ 925 GPUs for decoding. Reading 2,000 input tokens each (prefill) adds about half again, so roughly 1,400 GPUs on average and 4,200 at peak. These are assumptions, and you should say they are.
Concurrent streams: a 400-token answer at 40 tokens a second lasts 10 seconds. Open streams = 4,630 × 10 ≈ 46,300 on average, about 139,000 at peak. That is a connection-count problem for the gateway layer, not just a GPU one. It also agrees with the GPU count: 46,300 ÷ 50 streams per GPU ≈ 925.
Storage: 400M × 3 KB = 1.2 TB a day, or about 438 TB a year.
History reads: if each user opens past conversations about 5 times a day, 50M × 5 ÷ 86,400 ≈ 2,900 per second. Cheap.
"Everything outside the GPUs is easy: 4,600 requests a second and 1.2 TB a day of text. The GPU fleet is the system. It is about 1,400 machines at average load and 4,200 at peak, and you cannot add them in seconds. So the design is about admission control, queueing, priority, and using every GPU second well."
Reproduce the request rate and storage in the capacity estimator.
API and data model
POST /v1/conversations/{id}/messages { content, model } -> text/event-stream
event: token data: {"delta": "Hel"}
event: done data: {"messageId": "m_184", "usage": {...}}
POST /v1/generations/{genId}/stop
GET /v1/conversations?cursor= -> { items[], nextCursor }
GET /v1/conversations/{id}/messages?cursor=conversation (user_id, conversation_id) -> title, created_at, updated_at, model
message (conversation_id, seq) -> role, content, status, token_count, created_at
generation (gen_id) -> conversation_id, status, started_at, tokens_so_far
usage (user_id, window) -> messages, tokensThe non-obvious choice is message.status (pending, complete, stopped, failed). The user's message is saved before generation starts, and the assistant message is created as pending and filled in as tokens arrive, so a dropped connection never loses the conversation.
High-level design
We simulate the serving path: a gateway, a stateless chat service, a conversation store and a fleet of inference replicas that batch requests.
- The chat service loads the conversation from the store, builds the prompt and sends it to the model fleet.
- Inference replicas batch many requests and stream tokens back through the chat service and gateway.
Describe this diagram
Components
- users (Client)
- gateway (API gateway)
- chat service (Service)
- model replicas (LLM inference)
- conversation store (DynamoDB)
Connections
- users sends to gateway
- gateway sends to chat service
- chat service sends to model replicas
- chat service sends to conversation store
Run it, then reduce the model replicas or raise the load, and watch the requests waiting and the time to first token rise while the rest of the system stays idle. The model fleet is where this design runs out first.
The write path: the gateway authenticates the user and checks their rate limit. The chat service saves the user's message, builds the prompt from the history, and asks the model fleet for a stream. Tokens are forwarded to the client as they arrive and appended to the pending message. On completion the status becomes complete.
The read path: listing and opening conversations are ordinary key lookups on the conversation store, keyed by user, and cached for recent items.
The interesting problem: GPU capacity, queueing and priority
When demand exceeds what the GPUs can produce, something has to give. The three designs differ in what.
Approach A: one request per GPU, first come first served
Each GPU handles one stream at a time and a single queue feeds them all.
Good: simple to reason about, and latency per request is excellent once running.
Bad: it wastes almost the entire GPU. Decoding is memory-bound, so a GPU doing one stream uses a small fraction of its throughput, and you would need roughly 50 times more hardware. A single queue also gives every request the same treatment, including a free user's 4,000-token essay prompt ahead of a paying user's short question.
Approach B: continuous batching with a bounded queue
Replicas run continuous batching: new requests join the running batch between decoding steps, so the GPU stays full (the serving lesson explains why). In front of the fleet, an admission controller limits how many requests may wait.
Good: high GPU utilization, which is the main cost lever. A bounded queue keeps waits predictable.
Bad: under overload, a bounded queue rejects whoever arrives last, regardless of who they are. And a single pool treats all work as equal.
Approach C: batching plus tiered queues, priority and controlled degradation
Keep B and add policy:
- Priority queues by tier. Paid traffic goes first. Free traffic fills spare capacity and is the first to wait. Reserve a minimum slice of capacity for free users so they are never fully starved.
- Admission control by estimated cost. Estimate each request's cost (input tokens plus a cap on output tokens) and refuse early, with a clear "high demand, try again" message, instead of accepting and timing out after 30 seconds. A fast no is kinder than a slow failure.
- Controlled degradation. Under load, free users get a smaller or faster model, a lower output cap, or a longer wait. Paid users keep the full model.
- Prefix-aware routing. A conversation's earlier turns share a prompt prefix. Send the next turn to a replica that still holds that prefix's KV cache, which skips most of the prefill. See prompt and semantic caching.
- Autoscaling that knows its limits. Loading a large model onto a new GPU takes minutes, so scale on a forecast and keep headroom, rather than reacting to the current queue.
Diagram, as text
- Request leads to Rate limit and token budget
- Rate limit and token budget leads to Admission controller
- Admission controller leads to Priority queue (paid)
- Admission controller leads to Standard queue (free)
- Priority queue leads to Prefix-aware router
- Standard queue leads to Prefix-aware router
- Prefix-aware router leads to GPU replica: continuous batch
- Prefix-aware router leads to GPU replica: continuous batch
- Admission controller leads to Fast refusal: try again (over capacity)
This is the answer to aim for. The core idea is that you cannot create GPUs in seconds, so you decide in advance who waits. State the policy aloud, because the policy is the product.
The second decision: streaming, and not losing the answer
Tokens flow from the GPU to the browser through three hops, and any of them can break. Choose a transport first. Server-sent events over HTTP is a good default: one-directional, works through proxies and load balancers, and reconnects on its own. WebSockets add a second direction you do not need for a basic stream, though they help if you add voice or live cancellation later.
Then handle the failures this raises:
- The client disconnects mid-answer. Should the GPU keep generating? Stopping saves money, since the user is gone. But most people reconnect after a flaky network and want the answer. A good policy: keep generating for 10 to 30 seconds after a disconnect, writing tokens to the pending message, then stop if nobody returns.
- Resume. Give each generation an id and number its events. A reconnecting client sends
Last-Event-IDand the server replays from a short buffer (in a fast store such as Redis) or from the saved partial message. - A replica dies mid-stream. The stream breaks. Mark the message
failed(keeping the partial text), and let the user click regenerate. Do not silently restart: the second attempt will produce different text. - Backpressure. If the client reads slowly, buffering unlimited tokens in the gateway costs memory across 139,000 streams. Drop the stream after a bounded buffer, and let the saved partial message serve the rest.
Stop matters economically. When the user presses stop, the chat service must cancel the generation on the GPU, which frees the batch slot immediately. A UI that only hides the text keeps burning GPU time.
Bottlenecks and failures
Per-tier rate limits. Limit by messages per window and by tokens, since a 20-token question and a 30,000-token document are very different costs. Use a token bucket per user, refilled by plan, and check it before enqueueing. See design a rate limiter. Charge actual tokens after the response, not just the estimate, and refund unused budget when a generation stops early.
Long conversations. Resending 100,000 tokens of history on every turn is expensive and hits the context window. Truncate or summarize older turns, and cache the prefix (the context engineering lesson covers how). Store the summary with the conversation.
Hot launch day. A viral moment multiplies demand and you cannot add GPUs in time. Your tiered admission control, smaller-model fallback and "high demand" refusal are the plan. Test them before you need them.
Abuse. Free accounts are farmed for compute. Combine per-account and per-IP limits, device signals and a lower output cap for unverified users. Prompt content is also screened by a safety layer before it reaches the model and after, which adds latency you must budget for.
What if a model replica pool is down? The router retries on another pool, or falls back to a smaller model with a note to the user. If every pool is down, show a clear outage message and keep conversation history reads working, since they do not need a GPU.
What if the conversation store is slow or down? The user's message cannot be saved, so do not generate. Return an error early, because answering without saving breaks the "never lose a conversation" promise.
Trade-offs to name aloud
- Utilization against latency: larger batches use the GPU better and slow each stream a little.
- Priority for paying users: a better paid experience, while the free tier takes the waits.
- Early refusal over long queues: some rejected requests, in return for no timeouts.
- Continue after disconnect: a little wasted GPU time buys a better experience on flaky networks.
- Smaller model under load: lower quality for the free tier in exchange for staying up.
What interviewers listen for
- A working answer: gateway, chat service, conversation database, a GPU inference fleet and streaming with SSE or WebSockets.
- A strong answer: sizes the GPU fleet from tokens a second, explains continuous batching, queues and rejects early, limits by tokens and saves the user's message before generating.
- A standout answer: gives tiered priority with a reserved slice, routes to a replica with the cached prefix, handles disconnect and resume with numbered events, cancels on stop and plans degradation for overload.
Check your understanding
Common mistakes
Designing the web tier and stopping. The load balancer, chat service and database are the easy part. Not sizing the GPU fleet misses the point of the question.
One request per GPU. It leaves most of the hardware idle. Continuous batching is why the economics work.
Counting requests, not tokens, in rate limits. One user with huge prompts can use a thousand times more GPU than another. Budget by tokens.
Accepting every request. An unbounded queue turns overload into timeouts for everyone. Admit what you can serve and refuse the rest early.
Generating before saving. If the process dies after the model answers but before the message is stored, the user's conversation has a hole. Save first.
Ignoring stop and disconnect. Without cancelation, a user who closes the tab still costs GPU time for a 4,000-token answer.
Practice
The product team wants to launch a larger, higher-quality model for paid users. It runs at roughly a third of the tokens per second per GPU of the current model. How does that change your capacity plan and your design?
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Start with the arithmetic. Then ask how routing, queues and limits should change so the new model does not starve everything else.
Show a strong answer
Redo the fleet math. If one GPU now produces about 670 tokens a second (a third of 2,000), serving the same token volume takes three times the GPUs. Do not move all traffic. Estimate the paid share: if paid users produce 20% of tokens, they need 0.2 × 1.85M = 370,000 tokens a second, which is 370,000 ÷ 670 ≈ 550 GPUs for the large model, against about 185 on the old one.
Separate pools. Run the large model in its own replica pool and queue, with its own autoscaling. Mixing models in one batch makes both worse and complicates the prefix cache.
Route by tier and need. The model router can send simple prompts to the smaller model even for paid users, which cuts the new pool's load substantially. Let users pick the large model explicitly for hard tasks.
Cap the cost. A large model needs its own token budget per paid user, or a heavy user can use the new pool's capacity on their own.
The pattern worth keeping: a better model is a capacity change. Redo the tokens-per-GPU arithmetic before you promise it to anyone.
Users on mobile networks often lose their connection mid-answer. Design the behavior from the client's retry to the server's cleanup, and say what it costs.
Write your own answer first, on paper or in a note. Then compare.
Show a hint
Think about event ids, the partial message, a grace period and what to do if the user never returns.
Show a strong answer
Number every event. The server assigns each token event an increasing id within its generation, and writes tokens to the pending message in batches (every few hundred milliseconds), not one database write per token.
Reconnect with the last id. The client re-opens the stream with Last-Event-ID. The server finds the generation, sends everything after that id from a small buffer in a cache, and continues live if the generation is still running.
Grace period. If the client is gone, keep generating for about 20 seconds. If it returns, it resumes. If not, cancel the GPU work, save the partial text with status stopped, and let the user see it later.
Count the cost. At 4,630 messages a second, if 2% disconnect and half of those never return, that is about 46 generations a second continuing for 20 seconds, which is roughly 900 streams held open: about 18 GPUs' worth of batch slots (900 ÷ 50) spent on nobody. That is the price of resuming, and it is small enough to accept.
The pattern worth keeping: make an interrupted stream resumable by numbering events and saving partial state, and put a number on what the grace period costs.
Key takeaways
- Serving, not training. The system is a chat front end over a scarce GPU fleet.
- Plan in tokens per second. About 1.85 million output tokens a second needs on the order of 1,400 GPUs, and more at peak.
- Continuous batching and prefix caching are where cost is won.
- Decide who waits. Tiered queues, early refusal and graceful degradation are product policy.
- Save before you generate, and make streams resumable with numbered events.
- Limit by tokens, and cancel GPU work when the user stops.
Further reading
- Gyeong-In Yu and colleagues, "Orca: A Distributed Serving System for Transformer-Based Generative Models" (OSDI, 2022): iteration-level scheduling, the idea behind continuous batching.
- Woosuk Kwon and colleagues, "Efficient Memory Management for Large Language Model Serving with PagedAttention" (SOSP, 2023): how KV cache memory limits concurrency and how paging relieves it.
- WHATWG, HTML Living Standard, "Server-sent events": the streaming transport and its
Last-Event-IDresume mechanism.