Skip to content

How to design ChatGPT

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Practice this question

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

AskWhy it mattersA 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.

The requirements menu

RequirementScopeWhy

Send a prompt in a chat and get the answer streamed back token by token

Core

The product. It fixes the shape of the whole read path: prompt in, tokens out while they are produced.

See past chats and continue one, with its earlier turns as context

Core

Conversations and messages have to be stored, and each new turn has to be built from them, which is where the long-chat cost comes from.

A free tier with limits, and paid tiers with more

Core

GPU time is the budget. Tiers decide who is limited at the gateway and who is served first when the GPUs are full.

Stop an answer halfway

Core

A stop that reaches the GPU returns memory and compute to other users; a stop that just closes the tab wastes both.

Rename or delete a chat

Optional

Ordinary CRUD on the conversation row. Worth a sentence if asked; it tests nothing the core path doesn't.

Regenerate the last answer

Optional

Tempting because it reuses the run machinery as is: a new run on the same prompt. Take it if time allows; the one new question is whether both answers are kept.

Pick a model per message

Optional

Useful for the overload story, since a smaller model pool already exists in the design. Leave it unless asked: it adds a routing dimension to the scheduler.

Moderate prompts and answers for policy

Optional

If the product wants it, it fits as a step at the gateway or alongside the stream. Mention where it would sit and move on; the classifier is its own system.

Training the model and its internals

Out of scope

The model is a black box this round. Spend the time on the serving system that surrounds it.

Images, audio and video

Out of scope

Each is an upload pipeline and a different model. Name them and park them.

Editing or branching messages, and sharing chats

Out of scope

Branching turns the conversation into a tree, and sharing adds authorization. Both are storage-model changes with no bearing on GPUs or streaming.

Tools, browsing and custom assistants

Out of scope

Tool calls make a run a loop of model steps and external calls. It is a worthy follow-up design, not this one.

Full-text search over chat history

Out of scope

A search index fed from the messages table. Say that much and leave it.

Non-functional requirements

RequirementWhat 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

QuantityWorkingResultWhat 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 LLaMA-13B, and one write-up of its internals puts that at roughly 30 sequences per GPU before memory runs out. 120,000 concurrent answers ÷ 30 = 4,000 GPUs at the 20,000-a-second peak. Noon doubles prompts to 40,000 a second and open answers to 240,000, so 240,000 ÷ 30 = 8,000 GPUs; 8,000 × $2 an hour = $16,000 an hour

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 GPT-5.6 and later models (earlier models vary with request settings), bills cached input at up to 95% off, and expires entries after a period of inactivity that depends on the model and its retention setting. A 1,024-token system prompt in front of 20,000 prompts a second is 1,024 × 20,000 ≈ 20.5 million prefix tokens a second that a prefix cache can avoid recomputing

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

EntityWhat 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

EndpointNotes

POST /conversations/{id}/messages { content } → token stream over SSE

Stores the user message, creates a run, enqueues it and answers with text/event-stream. Each event carries an id (the buffer entry id) and a delta; a terminal event says done, stopped or failed. The response also names the run id early so the client can cancel. Rate limits are checked before the run exists; a refused call gets HTTP 429, and in this design the gateway adds a Retry-After header with the time left in the window.

GET /conversations → [{ id, title }]

The owner's chats, newest first, paginated. Served from the conversations table by user_id; no GPU involved.

GET /conversations/{id}/messages?after=… → messages

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.

POST /runs/{id}/cancel

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

prompthistoryprompttokensBrowserAPI gatewayChat serviceConversationsGPU worker

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.

promptcheckhistoryenqueuebatchreusetokensSSEBrowserAPI gatewayRate limitsChat serviceConversationsSchedulerGPU workerPrefix cacheToken bufferStream servers
The whole design

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.

A concept that helps here: Streaming LLM tokensA concept that helps here: WebSockets, server-sent events and pollingA concept that helps here: Queues and logs

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?

A concept that helps here: GPU batching and schedulingA concept that helps here: Fair queuing across tenantsA concept that helps here: Backpressure and load shedding

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: Retrieval-augmented generationA concept that helps here: Caching strategies

Cancelling 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?

A concept that helps here: Idempotency keysA concept that helps here: State machines in database rowsA concept that helps here: Routing messages between stateful servers

Concepts this guide uses

Sources

  1. MDN: Using server-sent events
  2. HTML Living Standard: Server-sent events
  3. server-sent-events.com: Replaying missed events with Redis Streams
  4. OneUptime: How to use XREAD in Redis Streams to read messages
  5. Anyscale blog: continuous batching for LLM inference
  6. USENIX OSDI: Orca, a distributed serving system for Transformer-based generative models
  7. vLLM blog: Easy, fast, and cheap LLM serving with PagedAttention
  8. How vLLM works internally: a deep dive (Varun K)
  9. arXiv: DistServe, disaggregating prefill and decoding for goodput-optimized LLM serving
  10. OpenAI API documentation: Prompt caching
  11. OpenAI API documentation: Rate limits
  12. OpenAI API documentation: Background mode
  13. Microsoft Foundry API reference: Cancel a model response
  14. Reading notes on Ainslie et al., GQA: Training generalized multi-query Transformer models from multi-head checkpoints
  15. PMLR: Fast inference from Transformers via speculative decoding (Leviathan, Kalman and Matias)
Sign in to report a mistake