SYSTEM DESIGN · DESIGN PROBLEMS · AI SYSTEMS · MEDIUM · 52 OF 57

Design ChatGPT: Streaming Chat, Context, Cost and Safety at Scale

A LADDER walkthrough of a consumer chat assistant: scale math for 10 million daily users in tokens, concurrent streams and dollars a day, the API and message tree, streaming over SSE with stop and resume, context assembly under a token budget, prompt caching, file retrieval, model routing with fallbacks, plan quotas, moderation and cost per user.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
1 / 21

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • SSE with resume
  • token-budget context
  • prompt caching
  • model routing and fallbacks
  • quotas
  • inline safety

Notes

Listen

Listen first. Users create conversations, send a message and watch the answer stream in, token by token. They can stop an answer, regenerate it, or edit an earlier message, which branches the conversation. They can pick a model or let us choose, upload files and ask about them, and the assistant can remember facts across conversations. There are free and paid plans with different limits.

The qualities. Time to first token under a second, because that is what feels fast. A dropped connection must not lose the answer. A sent message is never lost. Input and output are checked for safety, and one user can never see another user's data. Cost matters more than usual, since free users get answers for nothing. Out of scope: training models, images, voice and browsing agents.

Functional
  • conversations: list, rename, delete, continue later
  • answers stream token by token
  • stop, regenerate, edit a message and branch
  • pick a model, or let us pick
  • upload files, ask about them
  • memory across conversations
  • free and paid plans, quotas
Non-functional + scope
  • time to first token < 1 s
  • a stream survives a reconnect
  • never lose a sent message
  • safe input and output
  • cost per free user tiny
  • private: no data across users
  • out of scope: training models, image generation, voice, agents with browsing

Ask scale

Ask about scale. Ten million daily users sending ten messages each is a hundred million messages a day, about twelve hundred a second, thirty-five hundred at peak. An answer of four hundred tokens at fifty tokens a second streams for about ten seconds. By Little's law, that is thirty-five thousand streams open at once. Storing a question and answer at about three kilobytes is three hundred gigabytes a day.

Now tokens. With history, each request sends about two thousand input tokens and gets four hundred back: two hundred billion in and forty billion out a day. Send eighty percent to a small model and twenty to a frontier model. At example list prices that is about two hundred eighty-five thousand dollars a day, three cents per user. Input dominates, so prompt caching matters. Self-hosting the small model at about twenty-five hundred tokens a second per GPU needs roughly four hundred fifty GPUs at peak.

Traffic and streams
10M daily users × 10 messages
  = 100M messages/day
  ≈ 1,200/s avg, peak ×3 ≈ 3,500/s

answer ≈ 400 tokens at ~50 tok/s
  ≈ 8 s, ~10 s with first token
concurrent streams (Little):
  3,500/s × 10 s ≈ 35,000 open

store: 100M × 3 KB ≈ 300 GB/day
  ≈ 110 TB/yr before replicas
Tokens and dollars
input ≈ 2,000 tok, output ≈ 400
  in:  100M × 2k  = 200B tok/day
  out: 100M × 400 = 40B tok/day
  ≈ 460k out tok/s, peak ~1.4M
route 80% small, 20% frontier
example list price per 1M tok:
frontier 40B×$3 + 8B×$15 = $240k
small 160B×$0.15 + 32B×$0.6 = $43k
≈ $285k/day ≈ 3 cents/user/day
prompt cache hits save ~$60k
self-host small: ~450 GPUs peak

Define API

Define the API. Create and list conversations with cursor pagination. Sending a message takes the parent message, the content, an optional model, attached file ids and an idempotency key, so a retried send never runs the model twice. It answers with an event stream. A separate GET resumes a stream from the last event the client saw, and a stop endpoint cancels generation. Files upload to object storage with a presigned URL.

API
POST /v1/conversations → { id }
GET  /v1/conversations?cursor=
GET  /v1/conversations/{id}

POST /v1/conversations/{id}/messages
  { parent_id, content, model?,
    file_ids, idempotency_key }
  → text/event-stream
GET  /v1/messages/{id}/stream
  Last-Event-ID: 212 (resume)
POST /v1/messages/{id}/stop

Data model

The data model. Conversations are listed by user and point at the current leaf message. Messages are keyed by conversation id, and each has a parent id, so the conversation is a tree, not a list. That makes regenerate and edit simple. Each message keeps its status, the model used, and token counts and cost. At a hundred terabytes a year of append-mostly data read by conversation, a wide-column store partitioned by conversation id fits well.

Data model
conversations (by user_id)
  id, user_id, title, current_leaf,
  summary, summary_upto, updated
messages (by conversation_id)
  id, conv_id, parent_id, role,
  content, status, model,
  tokens_in, tokens_out, cost

files, chunks (user_id scoped)
memories: user_id, fact
→ wide-column store, ~110 TB/yr

High-level design

The high-level design. The client posts a message to the gateway, which authenticates, checks the rate limit and plan quota in Redis, and holds the event stream open. The chat service saves the user message first, so it is never lost, then assembles the prompt from the conversation. The model router picks a model and provider, and the call starts streaming tokens back.

On the way back, the chat service appends each token batch to a short-lived stream in Redis, and the gateway forwards it to the browser as server-sent events. When the answer completes, the full message is saved with its token counts, and a usage event goes to Kafka for billing, cost dashboards and traces. Note the split: the worker talking to the model is not the connection talking to the user.

Deep dive: streaming

Deep dive one: streaming. Server-sent events fit: the answer flows one way, it is plain HTTP that passes proxies, and every event carries an id. WebSockets are only needed for two-way traffic such as voice. The key decision is decoupling. The worker calling the model writes tokens to a Redis stream per message, and the gateway just tails it. Thirty-five thousand mostly idle streams fit on a handful of gateway nodes.

Now stop and resume. Phones drop connections. The client reconnects with the last event id it saw, say two twelve, and the gateway replays from two thirteen out of Redis, then keeps tailing. After the answer finishes, the stream expires and reads go to the store. Stop is a separate call: it sets a cancel flag, the worker aborts the provider request so we stop paying for tokens, and saves the partial answer marked stopped.

Why SSE, why decouple
  • SSE: one-way, plain HTTP, works through proxies and CDNs, built-in event ids
  • WebSocket only if we need two-way (voice, live tools)
  • worker writes tokens to a Redis stream per message
  • gateway reads and forwards
  • 35k streams ÷ ~10k per node → 4 nodes, run 8 for spare
Resume and stop
  • reconnect: Last-Event-ID 212 → replay 213.. then tail
  • stream key TTL ~10 min after done, then read the store
  • tab closed: keep generating, save the full answer
  • stop: set cancel flag, worker aborts the provider call (stops paying for tokens), saves partial, stopped

Deep dive: context

Deep dive two: context. The model only sees what we send, and every token costs money, so give each request a budget, say eight thousand tokens, even if the model accepts far more. Fill it in order: the system prompt, a few memories, retrieved file chunks, a running summary of older turns, then recent turns walked from the current leaf up the parent chain, newest first, until the budget is full. Always reserve room for the answer.

Order matters because of prompt caching. Providers and serving engines reuse work for a prompt prefix they have seen, often at a tenth of the input price and with a faster first token. So place stable text first: the system prompt, tools and memories, then history, which only grows at the end. Do not rewrite the summary every turn, or you break the cache; refresh it in the background every twenty turns or so, and keep a conversation on the same model and region.

Context assembly, 8k budget
1 system prompt + tools     ~800
2 user memories             ~300
3 file chunks (top 5)     ~2,000
4 running summary of old    ~500
5 recent turns, newest first,
  until the budget is full ~3,000
6 the new user message
7 reserve for the answer  ~1,000

walk leaf → root by parent_id,
  count with the model tokenizer
Prompt caching + summaries
  • providers cache a shared prompt prefix: cached input is ~10% of the normal price and cuts time to first token
  • so: stable parts first system, tools, memory then history, append-only summary: refresh every ~20 turns, in the background
  • route a conversation to the same model and region

Deep dive: files

Files. The client uploads straight to object storage with a presigned URL. An ingestion worker extracts the text. A small file just goes into the context whole. A large one is split into chunks of about five hundred tokens with some overlap, embedded, and stored in a vector index. At question time, run hybrid search, vectors plus keywords, rerank, and keep the top five. Every search filters by user id. And file text is data, never instructions, which limits prompt injection.

Files and retrieval
  • small file: put it all in context, skip retrieval
  • large: extract text, split into ~500-token chunks with overlap, embed each query: hybrid search, vector + keyword, then a reranker
  • always filter by user_id and file_ids: tenancy
  • file text is data, never instructions (injection)

Deep dive: routing

Deep dive three: routing. The router takes the user's choice, their plan and remaining quota, and a tiny classifier that guesses whether the request is easy or hard. Easy chat goes to the small model; code, math and long documents go to the frontier model. Each target has a fallback chain: another region, then another provider, then a smaller model. Circuit breakers skip a failing provider. Fail over only before the first token; after that, show an error and offer regenerate.

Model routing
  • inputs: user choice, plan, quota left, a tiny classifier for hard vs easy, files
  • easy chat → small model
  • code, math, long docs → frontier model
  • fallback chain: same model in another region → provider B → smaller model, with a note
  • circuit breaker per provider
  • retry only before first token

Deep dive: quotas

Quotas work at three levels. Per user, a token bucket in Redis stops bursts and scripts, say twenty messages a minute. Per plan, a quota counts frontier messages in a rolling window; a free user who runs out is downgraded to the small model instead of blocked. Meter tokens, not just requests: reserve an estimate up front and reconcile after. Per provider, cap concurrency, and when capacity is short, shed free traffic first.

Limits at three levels
  • per user: token bucket in Redis, e.g. 20 msgs/min
  • per plan: frontier messages per rolling window, e.g. free 10 per 5 h, then small
  • meter tokens, not requests: reserve estimate, reconcile with the real count at end
  • per provider: concurrency cap; overload sheds free tier first, paid keeps going

Deep dive: safety

Safety. Run a fast input classifier in parallel with the model call, not before it, so it adds no latency; if the input is flagged, cancel the call before anything is shown. For output, buffer about a sentence, check it, then release it to the stream. If it is flagged, stop and replace the answer. Log every flag, sample for human review, and tighten limits for accounts that keep abusing the system.

Moderation
  • input: fast classifier runs in parallel with the model call; flagged → cancel it
  • output: buffer ~1 sentence, check, then release flagged → stop, replace
  • the system prompt sets policy
  • log flags, sample for review
  • repeat abuse → tighter limits

Trade-offs

Trade-offs. A tight context budget is cheaper and faster but forgets detail, so the summary and retrieval must cover it. Routing saves a lot of money, but a wrong guess hurts quality, so measure it. If a provider fails, the fallback chain keeps chat working, perhaps on a smaller model. If Redis fails, stream directly and lose resume for a while. If the store fails, reject new sends rather than produce answers we cannot save.

Observability. Trace each request: the router's choice, cache hits, time to first token, tokens per second, input and output tokens and cost. Roll cost up per user, plan and model, and alert on outliers, because a single script can burn thousands of dollars. For quality, watch thumbs, the regenerate rate and the stop rate. Run an offline eval set before any prompt or routing change. And support deleting a user's data everywhere, including the vector index.

Trade-offs and failures
  • 8k budget: cheaper, faster, but forgets detail → summary and retrieval cover it
  • router: big savings, but a wrong guess hurts quality
  • provider outage → fallback chain, maybe smaller model
  • Redis down → no resume; send tokens direct, quotas fail open for paid users
  • store down → reject sends
Observability and evals
  • trace per request: router choice, cache hits, TTFT, tokens/s, in, out, cost
  • roll up cost per user, plan, model; alert on outliers
  • quality: thumbs, regenerate rate, stop rate
  • offline evals before any prompt or routing change
  • privacy: per-user delete, opt out of training

Interview summary

The thirty-second summary. A hundred million messages a day, thirty-five thousand streams at peak, and about two hundred eighty-five thousand dollars a day in tokens. Messages form a tree, so edits and regenerations are branches. Answers stream over SSE from a Redis buffer, so clients can resume, and stop cancels the provider call. Context fills a fixed budget with a stable prefix for caching. A router with fallbacks and quotas controls cost, and safety checks run inline.

Interview summary
  • 100M msgs/day, 35k streams, 200B input tokens, ~$285k/day
  • messages as a tree by parent
  • SSE from a Redis stream: resume by event id, stop cancels the provider call
  • context: fixed budget, stable prefix for prompt caching
  • files: chunk, hybrid, rerank
  • router + fallbacks + quotas
  • safety in parallel and chunks

Interview questions

Q1Why SSE instead of WebSockets for streaming answers?

The answer flows one way from server to client, and SSE is plain HTTP that works through proxies and load balancers, reconnects natively and carries event ids for resume. WebSockets are worth it only for two-way traffic such as voice or live tool interaction.

Q2How does a client resume a stream after its connection drops?

The generation runs in a worker that appends numbered token events to a short-lived Redis stream per message. The client reconnects with Last-Event-ID, the gateway replays everything after that id and then tails the stream; once the answer is complete, it is read from the conversation store.

Q3What happens when the user presses stop?

A stop call sets a cancel flag for the message; the worker sees it, aborts the provider request so no more output tokens are billed, saves the partial answer with status stopped, and closes the stream.

Q4How do you fit a long conversation into the context window?

Set a token budget below the model maximum and fill it by priority: system prompt, memories, retrieved chunks, a running summary of older turns, then recent turns newest first, reserving room for the answer. Count with the model tokenizer.

Q5How does prompt caching change the design?

Providers reuse a prompt prefix they have already processed at a fraction of the price and with a faster first token, so put stable content first, keep history append-only, refresh summaries rarely, and keep a conversation on the same model and region.

Q6How do you model regenerate and edit?

Each message stores a parent id, so the conversation is a tree. Regenerate adds a sibling assistant reply under the same user message, edit adds a sibling user message that starts a new branch, and the conversation points at its current leaf.

Q7How do you route between a small and a frontier model?

Combine the user choice, plan and remaining quota with a cheap classifier that predicts difficulty; easy chat goes to the small model and hard tasks to the frontier one, with a fallback chain across regions and providers guarded by circuit breakers.

Q8Can you fail over to another provider in the middle of an answer?

Not cleanly: once tokens are shown, a different model would continue inconsistently. Retry and fail over only before the first token; after that, end the stream with an error and let the user regenerate.

Q9How do you enforce limits for free and paid plans?

A per-user token bucket stops bursts, a per-plan quota counts frontier messages or tokens in a rolling window and downgrades to a small model when exhausted, and per-provider concurrency caps shed free traffic first under overload.

Q10How do you moderate without slowing the first token?

Run the input classifier in parallel with the model call and cancel if it flags, and check output in sentence-sized chunks before releasing them, stopping and replacing the answer if a chunk is flagged.