Design ChatGPT
Understanding the Problem
💬 What is ChatGPT? ChatGPT is a chat app in front of a large language model. A user types a message, the model writes a reply that appears word by word, and the whole exchange is saved as a conversation the user can come back to, continue, edit or fork. The model is the expensive part, but most of what makes the product feel solid is the system around it: how messages are stored, how a reply keeps streaming when the network blips, and how a fleet of GPUs is shared fairly between millions of people.
You'll also hear this as "design an end-to-end chatbot." It is the same problem. Whether the model is your own or a hosted API, you still need conversation storage, streaming, context assembly and capacity management. We'll assume we run our own model servers, because that's where the GPU questions come from, and note where a hosted API changes things.
Functional Requirements
Pin down the scope first. ChatGPT has grown tools, browsing, images, voice and memory; trying to design all of it in 45 minutes is a common way to run out of time.
Core Requirements
- Users should be able to send a message in a conversation and see the model's reply stream in token by token.
- Users should be able to see a list of their conversations and reopen any of them with its full history, on any device.
- Users should be able to edit an earlier message or regenerate a reply, which creates a new branch, and switch between branches.
- Users should be able to refresh the page, lose their connection or open another device mid-reply and pick the reply up where it was, without it starting over.
Below the line (out of scope)
- Training and fine-tuning the model (see LLM Fine-Tuning).
- Tools, browsing and code execution (see Agentic Systems) and voice mode (see Voice Assistant).
- Image generation, file uploads and shared links.
- Billing. We'll treat "free" and "paid" as tiers with different limits.
Non-Functional Requirements
Ask your interviewer about scale. We'll design for 50M daily active users sending an average of 10 messages a day, with replies averaging 500 output tokens.
Core Requirements
- The system should show the first token quickly: under 1 second at p50 and under 3 seconds at p99, then stream at a steady rate faster than people read (30+ tokens per second).
- The system must never lose a message the user sent or a reply that finished. History should look the same on every device.
- The system should handle the daily peak (about 3x the average) and launch-day spikes without falling over: when GPUs run out, it should queue, degrade or reject cleanly, not time out at random.
- The system should share GPU capacity fairly between users and give paid users priority.
- Chat should be available 99.9% of the time, and reading history should work even when generation is degraded.
Below the line (out of scope)
- Multi-region data residency.
- Detailed safety policy. We'll include a moderation step but not design the classifiers.
Now the arithmetic, because it tells you where the hard part is.
- 50M users x 10 messages = 500M messages a day, about 5,800 per second on average and roughly 17,000 per second at peak.
- Each reply is 500 tokens at about 50 tokens per second, so it takes around 10 seconds to generate. By Little's law, 17,000 new replies per second x 10 seconds = 170,000 replies streaming at once at peak.
- That's 170,000 x 50 = 8.5M output tokens per second. On top of that, every request re-reads its context. If the average prompt (system prompt plus history) is 3,000 tokens, that's 17,000 x 3,000 = 51M input tokens per second of prefill.
- A well-batched 8-GPU H100 node serving a large model produces output on the order of 10-20k tokens per second. 8.5M / 15k is roughly 550 nodes, or several thousand GPUs, for decode alone.
- Storage is small by comparison: 500M messages x ~2 KB is about 1 TB of text a day.
The web tier here is ordinary: 17,000 requests per second and 170,000 open streams is a few dozen servers. The GPU fleet is thousands of machines and almost all of the cost. Every design choice should be judged by what it does to GPU time: how much context we re-process, how well we batch, and what happens when demand exceeds supply.
The Set Up
Planning the Approach
We'll build the request path first (send, stream, store), then add history, branching and resumable streams. The deep dives cover the parts interviewers push on: dropped connections, GPU capacity and fairness, long conversations, and storage at scale.
Defining the Core Entities
- User: an account with a tier (free or paid) that sets rate limits, model access and priority.
- Conversation: a titled thread owned by one user. It points at the current leaf, the message the user is looking at now.
- Message: one turn, from the user or the assistant. Each message has a
parent_id, so a conversation is a tree, not a list. The path from the root to a leaf is one version of the conversation. - Generation: one run of the model that produces an assistant message. It has a status (
queued,streaming,done,failed,cancelled), the model used and how many tokens have been produced so far. It exists separately from the message so a reply in progress has its own identity that clients can reconnect to.
API or System Interface
POST /conversations
-> { conversationId }
GET /conversations?cursor=...
-> { items: [{ conversationId, title, updatedAt }], nextCursor }
GET /conversations/{id}
-> { title, messages: [{ id, parentId, role, content, status }], currentLeafId }
POST /conversations/{id}/messages
{ parentId, content, model, clientMessageId }
-> { userMessageId, assistantMessageId, generationId }
POST /conversations/{id}/messages/{assistantMessageId}/regenerate
-> { assistantMessageId, generationId }
GET /generations/{generationId}/stream (Server-Sent Events)
Last-Event-ID: 182 // resume after token event 182
-> event: token id: 183 data: {"text": " the"}
-> event: done data: {"finishReason": "stop"}
POST /generations/{generationId}/cancel
PATCH /conversations/{id} { currentLeafId }
Sending a message and streaming the reply are two calls on purpose. The POST creates durable records and returns IDs; the stream is just a way to watch a generation that exists without it. That split is what makes reconnecting possible. In practice the client can open the stream right after the POST returns, or the server can return the SSE stream directly from the POST and still support GET .../stream for reconnects.
clientMessageId is an idempotency key generated by the client. If the user's POST times out and the client retries, we return the same IDs instead of creating a second message and a second (expensive) generation.
High-Level Design
1) Users should be able to send a message and see the reply stream in
Start with the simplest thing that works. The client sends the message to a Chat Service. The Chat Service:
- Writes the user's message to the Conversation DB.
- Loads the conversation history and builds the prompt: system prompt, prior turns, the new message.
- Sends the prompt to the Inference Service, a pool of GPU servers running an engine such as vLLM or TensorRT-LLM, and gets tokens back as a stream.
- Forwards each token to the client over Server-Sent Events (SSE), and when the model finishes, writes the assistant message to the database.
SSE is the right transport here. The traffic is one-directional (server to client) once the message is sent, it's plain HTTP so it passes through proxies and CDNs, and the browser's EventSource reconnects automatically and sends Last-Event-ID. WebSockets work too and are worth it if you also need bidirectional events (voice, live tool approvals), but they add connection management for no benefit here. See Real-Time Updates for the full comparison.
The prompt has to fit in the model's context window (say 128k tokens), and every token in it costs prefill compute on every turn. For now, assume conversations are short and we send the whole history. We'll fix that in the deep dives.
A moderation check runs on the user's message before it goes to the model (a small, fast classifier, a few milliseconds) and on the output as it streams. We'll keep it as one box.
This works, but it has a serious flaw. The generation lives inside one HTTP request on one Chat Service instance. If the user's connection drops, the Chat Service either keeps generating with nowhere to send the tokens or cancels the generation, and either way the reply is lost until it's saved at the end. If the Chat Service instance dies, the reply is gone. We'll fix this in step 4.
2) Users should be able to see and reopen their conversations
History is a simple read path, and it's the part of the product that must keep working when GPUs are busy.
The Conversation DB stores conversations and messages. The access patterns are narrow:
- List a user's conversations, newest first (the sidebar).
- Load all messages of one conversation.
- Append a message to a conversation.
There are no cross-conversation joins and no transactions spanning users. That points to a wide-column or key-value store partitioned by user or conversation, such as Cassandra or DynamoDB. A sharded Postgres works too if you prefer it and shard by user_id.
conversations PK user_id, SK updated_at desc, conversation_id
-> title, current_leaf_id, model, created_at
messages PK conversation_id, SK message_id (time-ordered, e.g. ULID)
-> parent_id, role, content, model, status, token_count
The list endpoint reads one partition (user_id), sorted by updated_at. Opening a conversation reads one partition (conversation_id). Both are single-partition queries, which is what makes them fast at any scale.
Two small features fall out of this:
- Titles. After the first exchange, a background job asks a small, cheap model to write a 4-6 word title and updates the conversation row. It runs off a queue, at low priority, so it never competes with live chat for GPUs.
- Cross-device sync. Because every message is written to the database before the response finishes, any device that opens the conversation sees it. For live updates on a second device (a new message appearing without refresh), the client can poll the conversation's
updated_ator subscribe to a per-user event channel.
3) Users should be able to edit a message or regenerate a reply, creating branches
If messages were a list, editing message 3 of 10 would mean deleting 4-10 or copying the conversation. Instead, we store a tree. Every message has a parent_id. Editing a user message creates a new user message with the same parent as the original; regenerating a reply creates a new assistant message with the same parent as the original reply. The originals stay, and the UI shows "< 2 / 3 >" arrows to flip between siblings.
The conversation row stores current_leaf_id. To render the conversation, or to build the prompt for the model, we walk from the current leaf up through parent_id to the root and reverse it. That path is the only thing the model sees. Other branches never leak into the prompt.
Switching branches is a PATCH that moves current_leaf_id. If a user flips to an older sibling in the middle of the conversation, we need a leaf under it: the client picks the most recent descendant of that sibling (it has the whole tree loaded), and sets that as the new leaf.
A few details worth saying out loud:
- Conversations are small (dozens to a few hundred messages), so we load the whole tree in one partition read and walk it in memory. No recursive queries needed.
- A new message's
parentIdcomes from the client. The server checks that the parent belongs to the conversation; it doesn't need to be the current leaf, because sending from an older branch is a legitimate action. - Two devices editing the same conversation at once don't conflict. They just create two branches. The last
PATCHdecides which leaf is current, which is fine for a single user.
4) Users should be able to pick up a reply after a dropped connection
To make a reply survive the connection, decouple the generation from the request that started it.
When the user sends a message, the Chat Service writes the user message, creates an assistant message in status streaming and a Generation record, and puts a job on a queue. A Generation Worker picks up the job, calls the Inference Service and appends every token (or small batch of tokens) to a per-generation stream log in Redis Streams, with an increasing event ID. When the model finishes, the worker writes the full text to the assistant message in the Conversation DB, marks it done, and sets a TTL on the stream log.
The client's SSE connection is now a reader, not the producer. Any Chat Service instance can serve GET /generations/{id}/stream: it reads the log from the client's Last-Event-ID and then blocks on new entries (XREAD BLOCK). If the connection drops, the client reconnects to any instance with the last ID it saw and gets everything after it. A second device opening the same conversation sees the message in status streaming and attaches to the same stream from the start.
The model doesn't know or care about any of this. It keeps generating while the user is in a tunnel, and the reply is waiting when they come out.
Potential Deep Dives
1) How do we make streaming survive disconnects, refreshes and server failures?
The high-level design introduced a stream log. Interviewers often push on this, so it's worth walking through the options and their failure modes.
Bad Solution: Generation Tied to the HTTP Request
Approach
The Chat Service calls the model inside the request handler and pipes tokens to the client. If the client disconnects, the handler notices and cancels the generation to save GPU time.
Challenges
Every network blip loses the reply. Mobile users switch from Wi-Fi to cellular constantly, laptops sleep and proxies kill idle connections. The user sees half an answer vanish, hits regenerate, and we pay for the same tokens twice. If we don't cancel on disconnect, we keep generating, but nobody can see the tokens until the end, and if the instance dies they're gone. Deploys are painful too: every rolling restart cuts thousands of live replies.
Good Solution: Buffer on the Chat Server, Sticky Reconnects
Approach
Keep generating after a disconnect, and buffer the tokens in memory on the Chat Service instance that owns the generation. The load balancer routes reconnects for the same generation back to the same instance (a cookie, or consistent hashing on generationId), which replays from the client's offset.
Challenges
It survives client blips but not server failures. If that instance crashes or is drained for a deploy, the buffer goes with it. Sticky routing also fights with load balancing: a few instances can end up holding a lot of long generations, and you can't move them. And a second device has to find the right instance too.
Great Solution: Detached Workers and a Durable Stream Log
Approach
This is the design from step 4. Generations run in workers that don't hold client connections. Each token batch is appended to a Redis Stream keyed by generationId:
XADD gen:{generationId} MAXLEN ~ 5000 * seq 183 text " the"
XADD gen:{generationId} * seq 184 type done finish stop
EXPIRE gen:{generationId} 600 # after done: keep 10 minutes for late readers
Clients read from any Chat Service instance with their last sequence number. Once a generation is done, the full text is in the Conversation DB, so a client that reconnects after the stream log expires just loads the message. We append every few tokens, or every 50 ms, rather than every token, which cuts Redis writes by roughly 5-10x with no visible difference to the user.
Cancellation becomes explicit. A disconnect no longer cancels anything; the user pressing Stop sends POST /generations/{id}/cancel, which sets a flag the worker checks between token batches. The worker stops the model, saves the partial text and marks the message cancelled. We can still add a rule like "cancel if nobody has read this stream for 2 minutes" to reclaim GPU time from abandoned tabs.
Challenges
Redis becomes part of the hot path. At 8.5M tokens per second, batched to roughly 1M appends per second, that's a cluster of a few dozen shards, sharded by generationId, which spreads perfectly. If a Redis shard fails, live streams on it break, but nothing durable is lost: the client falls back to polling the message, and the worker can re-create the stream from its own in-memory copy or simply write the final text to the database. If a Generation Worker dies mid-reply, the generation is marked failed after a heartbeat timeout and the UI offers "regenerate." Restarting a reply from the middle on a different model server is possible (re-prefill prompt plus partial output and continue), but most products just retry.
A strong answer separates three things that the naive design conflates: the generation (GPU work with its own lifecycle), the stream (a replayable log of what it produced) and the connection (a disposable view of the stream). Once they're separate, reconnects, multiple devices and deploys all become easy.
2) How do we handle GPU load, peaks and fairness?
Demand for generation is spiky (launches, viral moments, the daily peak), and GPU supply can't scale in minutes the way CPU does. A new node takes minutes to boot and load hundreds of gigabytes of weights, and you may simply not have more GPUs to add. So the question is what happens when 20,000 requests per second arrive and you can serve 15,000.
Bad Solution: Send Everything Straight to the Model Servers
Approach
Round-robin every request to a model server and let it queue internally.
Challenges
Model servers run continuous batching, and their throughput per GPU is bounded by memory for the KV cache (the cached attention state for every active sequence). Once a server is full, extra requests wait in its local queue, time to first token climbs for everyone on that server, and requests start timing out at random. A heavy user with a 100k-token prompt can stall a server for seconds of prefill while short chats queue behind it. Free and paid users get the same bad experience.
Good Solution: Admission Control and Per-User Limits
Approach
Put a rate limiter in front of generation with limits per user and tier (for example, messages per 3 hours for each model, and tokens per minute), enforced in Redis at the Chat Service. Then add admission control: a router that tracks how much capacity each model pool has (active sequences, KV cache usage, queue depth) and only admits a request when there's room. Requests that can't be admitted wait in a short queue; if they'd wait more than a few seconds, we reject with a clear "at capacity" message instead of a slow timeout.
Challenges
It's fair per user but not across tiers, and it treats all requests as equally expensive. A 50-token "thanks!" and a 100k-token document question consume wildly different GPU time. It also only says no; it doesn't use capacity better.
Great Solution: A Capacity-Aware Scheduler with Priorities and Degradation
Approach
Treat GPU time as the scarce resource and schedule it explicitly:
- Cost-based admission. Estimate each request's cost from its prompt length and expected output (prefill tokens plus a decode budget), and charge it against per-user token budgets rather than counting messages.
- Priority classes. Interactive chat from paid users first, then interactive chat from free users, then background work (titles, summaries, batch API jobs) that can wait minutes. When the fleet is full, lower classes queue or get shed first. Background jobs fill the troughs at night.
- Graceful degradation. Under pressure, route free users to a smaller, cheaper model, lower their max output tokens, or temporarily disable expensive features (very long context). The product stays up for everyone; the experience gets slightly worse for some.
- Cache-aware routing. Send a conversation's next turn to a replica that likely still holds its prefix in KV cache (more in the next deep dive), and route long-context requests to a pool configured for them so they don't stall short chats.
- Separate prefill and decode. Large deployments split prefill (compute-bound, bursty) and decode (memory-bandwidth-bound, steady) onto different GPU pools, so a burst of long prompts doesn't slow down the tokens already streaming.
The inference engines themselves (continuous batching, paged attention, speculative decoding) are covered in LLM Inference and Inference Optimization. For this question, it's enough to know that throughput per GPU depends on batch size, and batch size is limited by KV cache memory.
Challenges
Cost estimates are guesses (output length is unknown until the model stops), so budgets need correcting after the fact. Priority queues can starve free users at peak, so put a floor on their share. And degradation needs product buy-in: "you've been switched to a smaller model" is a visible change.
If the model is behind a hosted API (OpenAI, Anthropic, Bedrock), the same ideas still apply at your layer. You get a rate limit per API key instead of a GPU fleet, so per-user budgets, priority queues and fallback to a cheaper model become your capacity plan. See LLM Gateway.
3) How do we handle long conversations without blowing up cost and latency?
Every turn re-sends the whole conversation, so cost grows with the square of the conversation length: turn 50 pays prefill for turns 1-49 again. Long conversations also eventually exceed the context window.
Bad Solution: Send the Full History Every Time
Approach
Concatenate every message on the current path and send it.
Challenges
Prefill time grows with prompt length, so time to first token creeps up as a conversation grows, and at 128k tokens the request simply fails. Most of that compute re-derives KV cache entries we already computed on the previous turn.
Good Solution: Token-Budgeted Truncation
Approach
Count tokens with the model's tokenizer and keep the system prompt, the newest message and as many recent turns as fit in a budget (say 16k tokens), dropping the oldest. Store token_count on each message so this doesn't require re-tokenizing the history.
Challenges
The model forgets the start of the conversation, which is often where the user explained the task ("I'm writing a cover letter for a nursing job..."). Users notice.
Great Solution: Rolling Summaries Plus Prefix Caching
Approach
Two techniques that work together:
- Rolling summary. When the history passes a threshold, a background job asks a small model to summarize the older turns. The prompt becomes: system prompt, summary of turns 1-30, verbatim turns 31-50, new message. Store the summary on the conversation, tied to the message ID it covers, so branches get their own summaries. For very long or important conversations, store older turns as embeddings and retrieve the few relevant ones per turn, which is the same retrieval machinery as a RAG System.
- Prefix caching. The KV cache for a prompt's prefix can be reused if the next request starts with exactly the same tokens. In a chat, turn N+1's prompt is turn N's prompt plus two messages, so if we route the conversation to the replica that served turn N and it still has those blocks in memory, we only prefill the new tokens. Engines like vLLM and SGLang support this (automatic prefix caching, RadixAttention). The router hashes the conversation ID (or the prefix) to pick a replica, falling back to any replica when that one is busy.
Keep the prompt layout stable to make caching work: a fixed system prompt first, then history, then the new message. Anything that changes per request (the current date, a random greeting) goes at the end, or it invalidates the whole cache.
Challenges
KV cache is large. For a 70B-class model with grouped-query attention, it's around 0.3 MB per token in fp16, so a 4,000-token conversation holds over 1 GB of GPU memory. You can't keep every idle conversation in HBM. Engines evict least-recently-used blocks, and some deployments spill to CPU memory or local SSD so a conversation resumed after a few minutes still hits. Summaries also lose detail, and they change the prefix, so the cache resets each time a summary is rewritten. Rewrite them in large steps, not every turn.
4) How do we store conversations reliably at this scale?
The data is modest (about 1 TB a day) but the write rate is high and the rules are strict: a sent message must never disappear.
Write order. On POST /messages, write the user message and the placeholder assistant message (status streaming) before enqueueing the generation, and return IDs only after those writes succeed. If the write fails, the user sees an error and nothing was spent on GPUs. The clientMessageId makes the retry safe: a conditional insert (IF NOT EXISTS in Cassandra, a condition expression in DynamoDB) on (conversation_id, client_message_id) returns the existing IDs.
Finishing a reply. The worker writes the full text to the assistant message when the generation finishes. For long replies, it also checkpoints partial text every few seconds, so if both the worker and the stream log are lost, we keep most of the reply. Status moves streaming -> done | cancelled | failed with a conditional update, so a late retry can't overwrite a finished message.
Partitioning. Messages are partitioned by conversation_id, which spreads writes evenly (no user has millions of conversations being written at once). The conversations table is partitioned by user_id; a heavy user with 50,000 conversations is still a single, sorted partition that the sidebar pages through. At 17,000 messages per second, with two message writes and one conversation update each, we're at roughly 50,000 writes per second, comfortable for a Cassandra or DynamoDB cluster.
Search and retention. Searching your own history ("that recipe from last month") needs an index across conversations, which the primary store can't do. Stream message writes through CDC or Kafka into Elasticsearch or OpenSearch, partitioned by user ID. Deleted conversations are soft-deleted, then purged by a background job, including from the search index and any summaries or embeddings derived from them.
5) Where does safety fit without hurting latency?
Moderation has to happen on both sides of the model, and it can't add a second to every message.
- Input: a small classifier runs on the user message in parallel with prompt assembly. It adds milliseconds. Clearly disallowed content is refused before any GPU time is spent.
- Output: we can't wait for the full reply before showing it, or streaming is pointless. Instead, the worker runs the output classifier on the accumulated text every few hundred tokens. If it flags, the worker stops generation, and the stream sends a
retractevent that replaces the partial reply with a refusal. The tokens a user saw for a moment are the accepted trade-off for streaming. - Abuse: per-account and per-IP limits, plus checks on account age and behavior, keep scripted abuse of free tiers in check. This sits in the same rate limiter as the tier limits.
Final Design
The full flow:
- The client sends a message through the API gateway (auth, rate limits) to the Chat Service with a
clientMessageId. - The Chat Service runs input moderation, writes the user message and a placeholder assistant message to the Conversation DB, creates a Generation and enqueues it with its priority class.
- The Admission Router admits the generation when its model pool has capacity, choosing a replica that likely holds the conversation's prefix in KV cache, or queues, degrades or rejects it under load.
- A Generation Worker builds the prompt (system prompt, summary, recent turns on the current branch), streams tokens from the model server and appends them to the generation's stream in Redis, running output moderation as it goes.
- The client's SSE connection, on any Chat Service instance, tails the stream from its last event ID. Reconnects and second devices replay from an offset.
- When the model finishes, the worker writes the full reply to the Conversation DB and marks it
done. Background jobs write titles and summaries at low priority, and CDC feeds the history search index.
What is Expected at Each Level?
Mid-level
You should get to a working design: a chat service that stores messages, calls a model and streams tokens back over SSE or WebSockets, with a conversation store partitioned sensibly. You should know that the model has a context window and that history has to be trimmed. With prompting, you should see that tying the generation to one HTTP connection loses replies, and that GPU capacity needs some kind of rate limiting.
Senior
You should model conversations as a tree with a current leaf, explain how edits and regenerations create branches and how the prompt is built from one path. You should separate the generation from the connection with a replayable stream, and walk through reconnects, cancellation and worker failure. Expect to do the GPU math, explain why throughput depends on batching and KV cache memory, and propose admission control with per-user and per-tier limits.
Staff+
You should frame the problem around GPU cost and run the conversation toward it: cost-based admission, priority classes, degradation to smaller models, prefill/decode separation and cache-aware routing for prefix reuse. Expect to discuss the trade-offs of rolling summaries against prefix caching, how to run deploys without cutting live streams, how capacity planning works when GPUs can't be added on demand, and what you'd put on the dashboard (time to first token, tokens per second, queue time by tier, rejection rate, KV cache hit rate). Knowing what not to build (no WebSockets unless you need them, no exotic database for a single-partition access pattern) is part of the signal.