Home / AI Architecture & System Design / AI System Design

AI System DesignSeniorQuestion 15 of 20

Design a ChatGPT-style conversational assistant for 10 million daily users.

30-second answer

Functional: streaming answers, multi-turn context, history across devices, regenerate and edit (a message tree), sharing, free and paid tiers. Non-functional: TTFT ≤ 1 s p95, resumable streams, no lost messages. ~3,500 messages/s at peak and ~35,000 open streams; model serving is ~99% of cost. Design: save the user message first; build context from the current branch within a token budget (recent turns verbatim, older ones summarized), keeping the prefix stable; route with conversation affinity so the prefix cache hits; write tokens to a stream buffer that clients read with Last-Event-ID; write the final message back. Overload: degrade the free tier first and route easy messages to smaller models.

Try answering out loud before reading on. The walkthrough below is paced for a 40-minute interview round.

New to these terms? 14 terms on this page are explained in the glossary

0–5 min Functional requirements

"Design ChatGPT" sounds huge. Narrow it to the chat product itself: conversations, streaming answers and history. The model is a dependency you call, not something you design here.

You Is the focus the consumer chat product, meaning conversations, streaming and history, or the model training behind it?

Interviewer The product. Assume you have models served behind an internal inference API.

You What does a user do? Start a conversation, send messages, see answers stream in, come back to old conversations later?

Interviewer Yes. Also regenerate an answer, edit an earlier message, and share a conversation by link.

You Any tools, like web search, file upload or image generation?

Interviewer Leave those as extensions. Mention where they'd plug in.

You Free and paid tiers with different models and limits?

Interviewer Yes, two tiers.

# Functional requirement Why it matters
F1 Send a message and see the answer stream token by token Responsiveness is the product
F2 Multi-turn context: the model sees earlier messages in the conversation "Turn that into a table" must work
F3 Conversation list and history across devices Users come back to old chats
F4 Regenerate an answer and edit an earlier message (creates a branch) Core chat behaviours
F5 Share a read-only snapshot of a conversation by link Common growth feature
F6 Tiers: model choice, message limits, context size Business model and capacity control
F7 Safety: input and output moderation, abuse rate limits Consumer product at scale

Out of scope: model training, tools (web search, code execution, file upload), voice, long-term memory across conversations (a separate design).

5–10 min Non-functional requirements and estimates

You I'll assume 10 million daily active users sending 10 messages each. Does that fit?

Interviewer Fine.

Requirement Target What it forces
Time to first token ≤ 1 s p95 (≤ 2 s on free tier at peak) Prefix caching, conversation-affinity routing, admission control
Streaming speed ≥ 30 tokens/s Caps decode batch size; costs GPUs
Availability 99.9% for sending messages; history readable even if models are down Separate read path from the model path
Durability No lost messages once acknowledged Write the user message before calling the model
Stream resilience A dropped connection resumes, it doesn't restart Server-side stream buffer with event IDs
Consistency A conversation appears on all devices within seconds Single source of truth per conversation
Cost Per-message cost tracked by tier Routing to cheaper models, caching, limits

Back-of-envelope estimates:

  • Messages: 10M users × 10 = 100M messages/day ≈ 1,160/s on average. Assume peak is 3× → ~3,500 messages/s.
  • Tokens per message: ~1,000 system prompt + ~2,000 history + new message ≈ 3,000 input tokens; ~350 output tokens.
  • Output at peak: 3,500 × 350 ≈ 1.2M output tokens/s. If one 8-GPU node serves ~6,000 tokens/s of a 70B-class model within the speed target, that's ~200 nodes for decode alone. Prefill is 10.5M input tokens/s; with ~70% of each prompt cached (the history was already processed last turn), ~3M new tokens/s × 1.4e11 FLOPs ≈ 4.4e17 FLOP/s, another ~110 nodes. Model serving dominates everything else by orders of magnitude, which is why routing easy messages to a smaller model matters.
  • Concurrent streams: an answer streams for ~350 × 30 ms ≈ 10 s, so at peak ~3,500 × 10 ≈ 35,000 open streams.
  • Storage: 200M messages/day (user plus assistant) × ~1.5 KB ≈ 300 GB/day, ~110 TB/year before compression. Reads are dominated by "open the conversation list" and "open one conversation".

10–18 min High-level design

You Two paths. The read path (list conversations, open one) is ordinary web infrastructure. The write path (send a message) stores the message, builds the prompt, calls the model and streams the answer through a buffer that survives disconnects.

Scroll sideways to see the whole diagram.

ChatGPT-style conversational assistantComponents: Web / mobile app (sidebar · chat view); API gateway (auth · tier limits); Chat service (message lifecycle); Moderation (input · output stream); Context builder (branch · budget · summary); Model router (auto model · affinity); Inference fleet (batching · prefix cache); Connection servers (SSE · Last-Event-ID); Stream buffer (per message · TTL); Conversation store (messages as a tree); Async workers (titles · shares · usage). Flow: Web / mobile app to API gateway; API gateway to Chat service; Chat service to Model router; Model router to Inference fleet; Chat service to Moderation; Chat service to Context builder; Inference fleet to Stream buffer (tokens); Stream buffer to Connection servers (resume from event ID); Connection servers to Web / mobile app (SSE); Chat service to Conversation store (save first); Conversation store to Async workers.Web / mobile appsidebar · chat viewAPI gatewayauth · tier limitsChat servicemessage lifecycleModerationinput · output streamContext builderbranch · budget· summaryModel routerauto model · affinityInference fleetbatching · prefix cacheConnection serversSSE · Last-Event-IDStream bufferper message · TTLConversation storemessages as a treeAsync workerstitles · shares · usagetokensresume from event IDSSEsave first
ChatGPT-style conversational assistant. The chat service stores the user's message first, moderates it, builds a prompt from the current branch within the tier's budget and sends it to a replica chosen for prefix-cache affinity. Generation writes tokens to a stream buffer; connection servers read from it, so a dropped connection resumes. The final message is written back to the conversation store.

Components:

  • API gateway: auth, per-user and per-tier rate limits, routes to the chat service.
  • Chat service (stateless): owns the message lifecycle: stores the user message, creates the assistant message in pending state, calls moderation and the context builder, starts generation, and finalizes the message.
  • Conversation store: conversations and messages, partitioned by conversation ID, with a per-user index for the sidebar. Messages form a tree (parent_id) so edits and regenerations create branches.
  • Context builder: turns the conversation into a prompt within the tier's token budget: system prompt, the current branch of history (truncated or summarized), the new message.
  • Model router: picks the model (user choice, or auto by difficulty and tier) and the replica, preferring the replica that served this conversation last so its prefix cache is warm.
  • Inference fleet: GPU pools per model with continuous batching and prefix caching (see the inference service design).
  • Stream buffer: each generation writes tokens to a short-lived stream keyed by message ID; client connections read from it, so a reconnect resumes at the last event ID.
  • Moderation: fast classifiers on input and on the output stream.
  • Async workers: title generation, share snapshots, analytics, feedback.

One message:

Scroll sideways to see the whole diagram.

One chat message, end to endBrowser → Chat service: POST message; Chat service → Conversation store: save m_42 + m_43 pending; Chat service → Browser: 202 {m_43}; Browser → Stream buffer: GET stream (SSE); Chat service: moderate · build context; Chat service → Model replica: prompt, 3,219 tokens; Model replica → Stream buffer: tokens 1 … 286; Stream buffer → Browser: events with IDs; Browser → Stream buffer: reconnect, Last-Event-ID; Model replica → Chat service: done + usage; Chat service → Conversation store: m_43 complete.BrowserChat serviceConversation storeModel replicaprefix cachedStream bufferPOST messagesave m_42 + m_43 pending202 {m_43}GET stream (SSE)moderate · build contextprompt, 3,219 tokenstokens 1 … 286events with IDsreconnect, Last-Event-IDdone + usagem_43 complete
One chat message, end to end. The user's message and an empty assistant message are saved before any model work, so nothing is lost. Generation writes to a stream buffer that the browser reads from; a reconnect resumes at the last event ID. The final message is written back as the source of truth.

API sketch:

POST /v1/conversations/{id}/messages   { content, parent_message_id, model } → 202 { user_message_id, assistant_message_id }
GET  /v1/messages/{id}/stream          (SSE; Last-Event-ID resumes) → delta … | done | error
GET  /v1/conversations?cursor=…        → sidebar page
GET  /v1/conversations/{id}            → messages on the current branch
POST /v1/messages/{id}/regenerate      → new assistant message, same parent

How it works: a worked example

A study aid: one message traced through the system, with real payloads, token counts and timings.

The situation. Priya is on her sixth turn in conversation c_8f2. Her last message asked for a comparison of three laptops; the assistant answered in prose. Now she types "Can you turn that into a table?"

1. Send (~40 ms). The browser posts:

POST /v1/conversations/c_8f2/messages
{ "content": "Can you turn that into a table?", "parent_message_id": "m_41", "model": "auto" }

The chat service checks her tier limit (paid: 160 messages per 3 hours; she's used 12), writes m_42 (role user) and m_43 (role assistant, status pending) in one transaction, and returns 202 { assistant_message_id: "m_43" }. Her message is now durable: if anything later fails, she sees it with a "retry" button rather than losing it.

2. Moderation (~20 ms). A small classifier scores the new message. Clean, so generation proceeds.

3. Context (~10 ms). The builder walks the branch from m_42 back to the root:

system prompt (product rules, date, tier)          950 tokens
turns 1–5 (user + assistant, current branch)     2,260 tokens
new user message                                     9 tokens
total                                            3,219 tokens   (budget for this tier: 32k → no truncation)

4. Routing (~2 ms). auto sends formatting and rewriting requests to the mid-size model. The router hashes c_8f2 and finds that replica mid-r117 served turn 5 ninety seconds ago, so the prefix (system prompt plus turns 1–5) is probably still in its cache. That replica is under its load bound, so it gets the request.

5. Generation. On mid-r117, 3,200 of the 3,219 tokens hit the prefix cache, so prefill covers only ~19 tokens. First token arrives ~180 ms after the router dispatched. Each token is appended to the stream buffer:

XADD stream:m_43 * seq 1 delta "| Laptop "
XADD stream:m_43 * seq 2 delta "| Weight |"
...

6. Streaming to the browser. The browser opened GET /v1/messages/m_43/stream right after the 202. The connection server reads from stream:m_43 and forwards SSE events with id: <seq>. At event 120 Priya's laptop switches Wi-Fi; the browser reconnects with Last-Event-ID: 120 and the server replays from 121. She sees a brief pause, not a restart.

7. Output moderation. Every ~200 tokens, the accumulated text goes to the output classifier in parallel with generation. A table of laptop specs passes.

8. Finalize. After 286 tokens (~8.6 s at 30 ms each) the model stops. The chat service updates m_43: status=complete, full content, model=mid@v12, tokens_in=3,219, cached_in=3,200, tokens_out=286. The stream buffer key expires after 5 minutes. A usage event goes to the metering pipeline.

What it cost. At illustrative prices for the mid model ($0.50 per million input tokens, a 90% discount on cached input, $2 per million output tokens): uncached input 19 tokens ≈ $0.00001, cached 3,200 × $0.05/M ≈ $0.00016, output 286 × $2/M ≈ $0.00057. About $0.0007, three-quarters of it output. Without the prefix cache, input alone would have been $0.0016, roughly tripling the cost of the message.

If she clicks Regenerate. A new assistant message m_44 is created with the same parent m_42. Both versions stay in the tree; the UI shows "2/2" and the context builder follows whichever branch is selected.

Where each piece runs:

Component Runs as Example technology If it fails
Gateway Stateless edge service Envoy, Cloudflare Regional failover
Chat service Stateless pods Go/Python service on Kubernetes Retry; message stays pending, then failed with a retry button
Conversation store Sharded database Postgres (Citus), DynamoDB, Spanner History unavailable; sending blocked (writes must be durable)
Stream buffer In-memory streams with TTL Redis Streams Live answers can't resume after disconnect; fall back to fetching the final message
Connection servers Long-lived SSE/WebSocket pods Node or Go Client reconnects to another pod and resumes from the buffer
Model router + fleet GPU pools vLLM/TensorRT-LLM behind an internal gateway Fall back to another model; at overload, queue or reject free tier first
Moderation Small classifier service on GPUs Fine-tuned encoder Fail closed on free tier input, fail open with async review on output (policy choice)
Async workers Queue consumers Kafka/SQS + workers Titles appear late

18–32 min Deep dive

You I'd go deeper on context management, streaming reliability, the data model, and handling overload.

Deep dive 1 · Context management

  • Budget per tier: the context builder fills the window in priority order: system prompt, the new message, then history from newest to oldest until the budget is reached.
  • Long conversations: once history exceeds the budget, replace the oldest turns with a running summary (generated asynchronously by a small model every N turns and stored on the conversation). Keep the most recent turns verbatim, because users refer back to them ("the second option").
  • Keep the prefix stable: prefix caching only works if the start of the prompt is byte-identical between turns. So don't put the current time to the second at the top of the system prompt, and update the summary rarely (each update invalidates the cache for that conversation).
  • Branches: the context is the path from the selected leaf to the root, not "all messages in the conversation". An edited message starts a new branch; its sibling's answers must not leak into context.

Deep dive 2 · Streaming and the message state machine

pending ──► streaming ──► complete
   │            │
   └──► failed ◄┘        (moderation block, model error, timeout)
  • Decouple generation from the connection. Generation runs whether or not the browser is connected; it writes to the stream buffer. The browser is just a reader. This gives resumable streams and lets the user switch devices mid-answer.
  • Stop button: sets a cancel flag the generation worker checks between tokens; the message is saved as complete with what was generated so far, marked stopped.
  • Exactly-once display: events carry a sequence number and the client ignores duplicates after replay.
  • Final write is the source of truth. The stream buffer is ephemeral. If it's lost, clients fetch the final message from the conversation store.
  • Idempotent sends: the client includes a client_message_id; a retried POST after a network error returns the same IDs instead of creating a second message.

Deep dive 3 · Data model and storage

conversations   (user_id, conversation_id, title, updated_at, current_leaf_id, summary, share_id)
                partition by user_id; index on (user_id, updated_at desc) for the sidebar
messages        (conversation_id, message_id, parent_id, role, content, status, model,
                 tokens_in, tokens_out, created_at)
                partition by conversation_id; a conversation's messages live together
  • Access patterns: sidebar (one user's recent conversations, paginated) and open conversation (all messages of one conversation). Both are single-partition reads.
  • Hot users: a power user with 50,000 conversations is still small per partition; no fan-out problems.
  • Large content: messages above a size threshold (pasted documents) go to object storage with a pointer.
  • Sharing: "share" copies the current branch into an immutable snapshot with its own ID, so later edits don't change what was shared and the snapshot can be served from a CDN.
  • Deletion: deleting a conversation removes messages and snapshots, and a retention job removes it from analytics stores within the stated period.

Deep dive 4 · Overload, routing and cost

  • Model routing: auto uses a small classifier to send simple messages (greetings, rewrites, short facts) to a small model and hard ones (reasoning, code) to the large model. If 60% of traffic goes to a model that's 10× cheaper, serving cost falls by more than half.
  • Admission control: each pool reports queue time. When it exceeds the TTFT target, the router (in order) sends auto traffic to a smaller model, queues free-tier requests with a visible "high demand" message, and finally rejects free-tier requests. Paid traffic keeps its target.
  • Tier limits: a sliding-window counter per user (e.g. messages per 3 hours) in Redis, checked before any GPU work.
  • Regional capacity: route to the nearest region with capacity; conversation data is global (or per-region with replication), while inference is stateless apart from the cache.

Deep dive 5 · Safety and abuse

  • Input: fast classifier for clearly disallowed content and jailbreak patterns; the model's own training handles the rest.
  • Output: classifier on the accumulating stream; on a severe hit, stop generation, replace the visible text, and mark the message.
  • Abuse: rate limits per account, device and IP; signup friction for the free tier; anomaly detection for scripted use (identical prompts, 24/7 traffic).
  • Privacy: conversation content is excluded from logs by default; training use follows the user's setting.

32–37 min Trade-offs

Decision Chosen Alternative Why
Streaming Generation writes to a buffer; clients read with resume Pipe tokens straight from the model to the socket Survives disconnects and device switches; small extra latency
Context for long chats Recent turns verbatim + summary of older ones Truncate only Keeps early facts available at low token cost; summaries lose detail
Routing Conversation affinity for cache hits, with load bounds Pure least-loaded Large prefill and cost savings on multi-turn chats
History model Message tree with parent IDs Flat list Supports edit and regenerate without losing versions
Overload Degrade free tier first Equal degradation Protects paying users and the core experience
Store Partition by conversation, index by user One table keyed by user Each read hits one partition; conversations can be large

Build first: chat service, conversation store, direct streaming, a single model. Then the resumable stream buffer, context summarization, the router with affinity, tiers and overload handling.

37–40 min Wrap-up and likely follow-ups

Close with: "The user's message is stored first, so nothing is lost. The chat service builds a prompt from the current branch within the tier's budget and routes it to a replica that probably has the conversation cached. Tokens stream through a resumable buffer, and the final message is written back as the source of truth. Model serving is ~99% of the cost, so routing, prefix caching and tiered overload handling are where the design pays off."

Likely follow-ups:

  • How do you add web search or tools? The chat service becomes an agent loop: the model can emit tool calls, the service runs them and streams intermediate status events (searching…) on the same stream.
  • How do you add file uploads? Files go to object storage, are parsed and chunked, and either inserted into context (small files) or retrieved per turn (large ones).
  • How do you add memory across conversations? See the long-term memory design: extract facts asynchronously and retrieve them into the system prompt.
  • How would you test a new system prompt? Offline eval set plus an A/B test on a small share of traffic, watching regenerate rate, thumbs-down rate and conversation length.

Further reading

What interviewers listen for

  • Separating the durable message store from the ephemeral stream.
  • A real answer to "the connection dropped mid-answer".
  • Context assembly from a branch, within a budget, keeping the prefix cacheable.
  • Cost estimates that show model serving dominating, and routing as the lever.
  • Overload handling by tier rather than failing for everyone.

Red flags

  • Treating the model call as a normal 200 ms RPC.
  • Sending the entire conversation history forever with no budget.
  • Losing the user's message when generation fails.
  • No plan for 35,000 concurrent streaming connections.

Discussion

Help us improve our content — give feedback. Spotted an error, have a better explanation, or got asked a follow-up in a real interview? Share it here.