How to design ChatGPT
The first sections are free. The deep dives, level expectations and quiz are part of Pro.
On this page
- The problem
- Clarifying questions
- The requirements menu
- Non-functional requirements
- Estimates
- Core entities
- The API
- The high-level design
- What breaks first
- The deep dives
- Entity fields
- Streaming tokens
- Scheduling the GPUs
- Long conversations
- Cancelling a run
- Variants
- What each level is expected to show
- The 30-second answer
- Quiz
The problem
A chat assistant's backend takes a prompt, builds the model's input from the conversation so far, runs it on a GPU, and streams the answer back a token at a time while saving the exchange for later. The design turns on one fact: GPU time is the scarce resource, and each running chat holds memory on its GPU for as long as it generates. So the backend is a scheduler around scarce, stateful workers, with a streaming layer that keeps an answer alive even when the browser's connection doesn't.
Clarifying questions
| Ask | Why it matters | A typical answer |
|---|---|---|
How many people use it, how many prompts arrive at peak, and how many answers are streaming at once? | The prompt rate sizes the GPU fleet; the number of open streams sizes a different tier, the one holding connections. They are different problems and you want both figures before drawing anything. | A little over 200 million daily users, about 20,000 prompts a second at peak, and about 120,000 answers streaming at the same time, each at about 50 tokens a second. |
Is the model a black box I call, or do I design its internals too? | It sets the boundary of the round. The serving system (queues, batching, memory, streaming) is where the design lives; attention math is not. | A black box: you're given inference workers that take a prompt and emit tokens. Design what surrounds them, including how many chats one worker holds and how work is shared across them. |
What does the first-token target look like, and does it apply to free users too? | A blank screen is the failure users notice. The target decides how much queueing you can tolerate and whether tiers get different treatment at peak. | Time to first token under 200 ms is the goal. Paid tiers should hold it at peak; free users may wait or be moved to a smaller model when GPUs run out. |
What do the free and paid tiers differ in? | Limits per tier are a functional requirement here, and they shape the gateway (what it counts) and the scheduler (who it serves first). | Free users get a capped number of messages and tokens per window and lower priority; paid tiers get higher limits and priority for GPU time. |
When a user presses stop, what should the chat keep? | It decides whether a run is a durable object with a lifecycle or just an open connection, and what the next turn's history contains. | Keep the partial answer and mark it as stopped. The user sees what was generated, and the next turn includes it. |
How long do conversations get, and is there a context limit I should plan around? | If chats run to hundreds of turns, re-reading the history on each turn becomes the main expense of the system, and trimming it becomes a design problem. | Some chats run to hundreds of turns. The model has a fixed context window; what goes into it on each turn is your call. |
Is text the whole product for this round? | Images, audio, tools and browsing each add a pipeline. Confirming a text product keeps the round on the serving system. | Text. Images, audio, tools, custom assistants, sharing and search over history are out of scope. |
Non-functional requirements
| Requirement | What it forces |
|---|---|
Time to first token under 200 ms: a blank screen feels broken | Stream from the first token rather than returning a finished answer, keep the wait for a GPU short, and make the prompt-reading step cheap with a cached prefix. Under overload, protect this for paid users by shedding or downgrading free ones. |
About 20,000 prompts a second at peak | A scheduler and a GPU fleet sized from this rate and the answer length, with per-tier queues so the fleet is shared on purpose rather than first come, first served. |
About 120,000 answers streaming at the same time | A separate tier of stream servers sized by open connections, and a token buffer keyed by run so a connection can drop and come back without losing the answer. |
GPUs are scarce and cost about $2 an hour each, so GPU time is the budget | Batch many chats on each GPU, keep each chat's state on the worker already holding it, stop runs promptly when users cancel, and avoid recomputing shared prompt prefixes. |
Estimates
| Quantity | Working | Result | What it sizes |
|---|---|---|---|
Token events a second across the stream layer | 120,000 open streams × about 50 tokens a second = 6,000,000 token events a second, about 6 million | About 6 million tokens a second entering the stream layer; the number of writes and pushes is that divided by how many tokens each append carries | The token buffer's write rate and the stream servers' fan-out. It is why a worker should write a few tokens per buffer append rather than one network call per token. |
How long a stream stays open, and how long an average answer is | Open streams ÷ arrival rate = average time open (Little's law): 120,000 ÷ 20,000 a second = 6 seconds; 6 seconds × 50 tokens a second = 300 tokens in an average answer | About 6 seconds a connection, about 300 tokens an answer | The lifetime of a connection (many open at once, each short) and the size of one run's token buffer. It also says how long a buffer should outlive its run for a late reconnect: minutes, not hours. |
GPUs at peak and at noon: a worked example with a mid-size open model | vLLM's blog puts the attention cache of one sequence at up to 1.7 GB for | About 4,000 GPUs at peak and 8,000 at noon, about $16,000 an hour at noon, for this example model | The GPU fleet, and why its memory rather than request count is the unit of capacity. A frontier model holds far fewer sequences per GPU and a paged allocator holds more; the method matters more than the figure, which is an example and not a target. |
Sequences a paged attention cache recovers | Earlier allocators wasted 60% to 80% of attention-cache memory, and paging brings that under 4%. Live tokens then fill 20% to 40% of the cache before, and about 96% after; 96 ÷ 40 ≈ 2.4 and 96 ÷ 20 ≈ 4.8 | Roughly 2.4 to 4.8 times more sequences in the memory set aside for the attention cache; the weights' share of GPU memory does not change | How much of the fleet in the row above is allocator waste rather than hardware, and why the worker's memory manager is part of the scheduling answer. |
Prompt tokens re-read over a long chat | If each turn adds about 300 tokens (the answer text, before the user's prompt) and a chat reaches 100 turns, the history is about 30,000 tokens. Each turn re-reads what came before it, so the total read over the chat is about 300 × (1 + 2 + ... + 100) ≈ 1.5 million tokens, against 30,000 if each token were read once | About 50 times the tokens of the chat itself; the reading cost grows with the square of the turn count | Why trimming, summaries and a cached prefix exist: the part of a long chat's cost that grows with its length is re-reading the history on each turn, while generating the new answer still costs one model pass per token. |
Prefix work a shared system prompt would repeat | OpenAI's prompt caching needs a prefix of at least 1,024 tokens to cache for | About 20.5 million prefix tokens a second that can be served from cached state instead of recomputed; since entries live per machine, a worker holding a live entry can reuse it, while misses, expiry and eviction leave some recomputation | What the prefix cache saves, and why requests that share a prefix should land on the worker that already holds it. |
Throughput multipliers the serving literature reports | Anyscale measured 8x over naive batching from continuous batching, and up to 23x once paged memory is added. DistServe reports 7.4x more requests within the same first-token and per-token latency limits by putting prompt reading and generation on different GPUs | Between 7.4x and 23x, depending on the baseline | The order of magnitude the scheduler and memory manager are worth, which is why the GPU conversation should be about them before it is about buying GPUs. |
What a token limit implies per request | OpenAI's Build tier allows 5,000 requests a minute and 1,000,000 tokens a minute on its standard models; 1,000,000 ÷ 5,000 = 200 tokens a request before the token limit binds first | About 200 tokens a request on average; above that the token limit binds before the request limit | Why limits per tier count tokens and not just messages: the budget being protected is GPU time, which prompts of different lengths consume unevenly. |
Core entities
| Entity | What it holds |
|---|---|
User | Who is asking, which tier they are on, and how much of their window they have used. |
Conversation | One chat: a title, an owner, and an ordered list of messages the next turn is built from. |
Message | One turn from the user or the assistant, with its token count so the prompt builder can budget without re-tokenizing. |
Generation run | One attempt to answer one message: where it is in its life, which worker holds it, and how far the stream has got. |
Token event | One entry in a run's buffer: a few tokens and the id the browser echoes back on reconnect. |
The API
| Endpoint | Notes |
|---|---|
| Stores the user message, creates a run, enqueues it and answers with |
| The owner's chats, newest first, paginated. Served from the conversations table by |
| History for one chat, with a cursor on the message id. A stopped assistant message comes back with its status so the client can show the marker. Also how a client that lost its stream for good fetches the final text. |
| Idempotent. Marks the run stopped and signals the worker holding it; for a run that already finished it returns the final status and changes nothing. The partial answer stays in the history. Closing the SSE connection doesn't count as a stop; this call does. |
The high-level design
Step 1 of 4
The straight line: gateway, chat service, a GPU worker
Start with the shortest path that meets the first requirement. The browser posts a message to an API gateway, which authenticates the user and reads their tier. A chat service stores the message, loads the conversation's history from the conversations store, builds the model input (system prompt, history, new message) and calls a GPU worker. The worker generates tokens and they flow back to the browser over the same response as server-sent events, so the first word shows as soon as it exists. This already streams, stores history and knows the tier, which is more than the obvious single-response version does.
What breaks first
The deep dives
Streaming tokens. A user presses enter and the first word appears a moment later. Trace the path from the browser to a GPU and back, say why you stream the way you do, and say what the user sees when the connection drops halfway and comes back on a different server.
Scheduling the GPUs. Traffic doubles at noon and the GPUs are already full. What decides which prompt waits and which runs, where a chat's next turn is placed, and how many GPUs the noon peak needs by your own numbers?
Long conversations. Some chats run to hundreds of turns, and each new turn carries the chat so far. How do you keep a reply's cost from growing with the chat while the assistant still remembers what matters, and what do the GPUs recompute when thousands of users share the same system prompt?
A concept that helps here: The KV cache and prefix caching
A concept that helps here: Retrieval-augmented generationA concept that helps here: Caching strategiesCancelling a run. A user hits stop halfway through a long answer. How does the stop reach the right GPU, how soon is its memory back, what if the stop arrives after the run finished or before it started, and what does the chat keep?
Concepts this guide uses
- Streaming LLM tokens
- WebSockets, server-sent events and polling
- Queues and logs
- GPU batching and scheduling
- Fair queuing across tenants
- Backpressure and load shedding
- The KV cache and prefix caching
- Retrieval-augmented generation
- Caching strategies
- Idempotency keys
- State machines in database rows
- Routing messages between stateful servers
Sources
- MDN: Using server-sent events
- HTML Living Standard: Server-sent events
- server-sent-events.com: Replaying missed events with Redis Streams
- OneUptime: How to use XREAD in Redis Streams to read messages
- Anyscale blog: continuous batching for LLM inference
- USENIX OSDI: Orca, a distributed serving system for Transformer-based generative models
- vLLM blog: Easy, fast, and cheap LLM serving with PagedAttention
- How vLLM works internally: a deep dive (Varun K)
- arXiv: DistServe, disaggregating prefill and decoding for goodput-optimized LLM serving
- OpenAI API documentation: Prompt caching
- OpenAI API documentation: Rate limits
- OpenAI API documentation: Background mode
- Microsoft Foundry API reference: Cancel a model response
- Reading notes on Ainslie et al., GQA: Training generalized multi-query Transformer models from multi-head checkpoints
- PMLR: Fast inference from Transformers via speculative decoding (Leviathan, Kalman and Matias)