Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← AI system designAI guideAdvanced#system-design#llm-serving#streaming#case-study
Frame · ai-engineering / case-studies / 01-chat-assistant-at-scale.mdGuide 092 / 103

Design a ChatGPT-style chat assistant at scale

This is the classic opener in AI system design interviews: "design ChatGPT." It looks like a chat app with a model behind it, but the interesting parts are the ones a normal chat app never has to think about: requests that take 10 to 60 seconds, a backend that is bottlenecked on GPUs instead of CPUs, and costs that scale with tokens rather than requests. I'll walk through it the way I would at a whiteboard.

Requirements

Functional

  • Users create conversations, send messages, and see the reply stream in token by token.
  • Conversation history persists and is searchable; users can regenerate, edit a previous message (branching), and delete chats.
  • File and image uploads, plus a small set of tools (web search, code execution) the model can call.
  • Plan tiers (free, paid, team) with different models and usage limits.

Non-functional

  • Time to first token (TTFT) under roughly 1 second at p50 for the default model; the stream must not stall.
  • High availability for the chat path; a model outage should degrade to another model, not a blank screen.
  • Conversations are durable (no lost messages) and private; deletions must actually delete.
  • Abuse resistance: rate limits, safety classifiers, and protection against cost attacks.

Scale estimates (all assumptions, for sizing only)

QuantityAssumptionResult
Daily active users50M
Messages per user per day10500M messages/day, about 5,800/s average
Peak factor3xabout 17,000 messages/s at peak
Output tokens per reply400about 7M output tokens/s at peak
Average prompt (history + system)3,000 tokensprefill dominates input volume
Stored text per message2 KBabout 1 TB/day of raw conversation text

The punchline of the estimate: storage and web traffic are ordinary; GPU capacity for decoding millions of tokens per second is the whole game. Everything else is designed around keeping GPUs busy and not wasting them.

High-level architecture

Rendering diagram…

The chat orchestrator is the brain: it loads context, assembles the prompt, calls the model router, handles tool calls in a loop, and streams tokens back. The inference pools are fleets of GPU servers running an engine like vLLM, SGLang or TensorRT-LLM with continuous batching. Everything else is supporting cast.

Request flow

Rendering diagram…

Two details matter here. First, the user message is persisted before generation starts, so a crash mid-stream never loses what the user typed. Second, the assistant message is written at the end (with periodic checkpoints for long replies) along with token counts for billing.

Components

ComponentResponsibilityNotes
API gatewayTLS, auth, per-user and per-IP rate limits, request size capsToken-bucket limits keyed by user and tier; reject early, before GPUs are touched
Chat orchestratorPrompt assembly, tool loop, streaming, retries, fallbackStateless; long-lived connections, so scale on concurrent streams, not RPS
Conversation serviceCRUD for conversations and messages, branching, searchPartitioned by user id; the read pattern is "load one conversation"
Model routerChooses model and replica; handles failoverPrefix-aware routing to maximize KV cache hits
Inference poolsRun the models with continuous batchingSeparate pools per model; autoscale on queue depth and KV cache usage
Safety classifiersInput and output moderationSmall fast models; run on input in parallel with prefill
Tool runtimeWeb search, sandboxed code execution, file parsingIsolated from the orchestrator; strict timeouts
Usage meteringCounts tokens per user for limits and billingAsync via event bus; limits use a fast counter store

Data model

A conversation is a tree, not a list, because editing an earlier message creates a branch.

CREATE TABLE conversations (
  id            UUID PRIMARY KEY,
  user_id       UUID NOT NULL,
  title         TEXT,
  current_leaf  UUID,            -- tip of the visible branch
  created_at    TIMESTAMPTZ,
  updated_at    TIMESTAMPTZ,
  deleted_at    TIMESTAMPTZ
);

CREATE TABLE messages (
  id              UUID PRIMARY KEY,
  conversation_id UUID NOT NULL,
  parent_id       UUID,          -- null for the root
  role            TEXT,          -- user | assistant | tool | system
  content         JSONB,         -- text parts, attachments, tool calls
  model           TEXT,
  input_tokens    INT,
  output_tokens   INT,
  created_at      TIMESTAMPTZ
);

To render a chat you walk from current_leaf up through parent_id. At this scale I would put messages in a horizontally scalable store (a sharded Postgres such as Citus, or a wide-column store like Cassandra or DynamoDB) keyed by (user_id, conversation_id) so one conversation lives on one shard. Attachments go to object storage with only references in the message.

Deep dives

Streaming and long-lived connections

Server-Sent Events over HTTP is the usual choice: one-directional, works through proxies, and reconnects cleanly. Each event carries a sequence number so a client that reconnects can say "resume from token 212." To support that, the orchestrator writes the in-progress reply to a short-lived buffer (Redis streams work well) keyed by message id. Load balancers need generous idle timeouts, and deploys must drain connections rather than kill them.

GPU serving and batching

Decoding is memory-bandwidth bound, so serving engines batch many sequences together. Continuous batching lets new requests join a running batch at each step instead of waiting for the whole batch to finish. PagedAttention (from the vLLM paper) stores the KV cache in fixed-size blocks so memory is not wasted on fragmentation. The metrics I would autoscale on are queue wait time and KV cache utilization, not CPU.

Many production stacks also split prefill (processing the prompt, compute bound) and decode (generating tokens, bandwidth bound) onto different GPU groups, called disaggregated serving, so long prompts do not stall everyone else's token stream.

Prompt caching and prefix-aware routing

Every turn re-sends the entire history. With a 3,000 token average prompt, recomputing that each time is the biggest waste in the system. Engines with automatic prefix caching reuse the KV blocks for a shared prefix (system prompt plus earlier turns). That only helps if the next turn lands on the same replica, so the router hashes conversation_id (or the prefix) to a preferred replica, falling back to the least-loaded one when it is hot. Keep the system prompt stable and put volatile content (timestamps, retrieved snippets) at the end so the prefix stays cacheable.

Context management

Long conversations eventually exceed the context window and cost too much anyway. Options, in order of simplicity: truncate the oldest turns, summarize older turns into a running summary stored on the conversation, or retrieve relevant older turns by embedding. Memory across conversations ("remember that I'm vegetarian") is a separate, user-visible store of facts the user can view and delete.

Rate limits and cost protection

Limits are expressed in tokens and messages per window per tier, checked at the gateway with a fast counter (Redis or a dedicated limiter). Because you only know output length after generation, reserve an estimate up front and settle the difference afterwards. Cap max_tokens per tier. Watch for cost attacks: huge pasted inputs, scripted accounts, and prompts engineered to produce maximum-length output.

Graceful degradation

When the large model pool is saturated, options are: queue with a visible wait, route paid users first, fall back to a smaller model with a banner, or disable expensive tools. Decide this policy in advance; doing it ad hoc during an incident is how you end up giving free users priority over paying ones.

Trade-offs and pitfalls

  • Sticky routing vs load balance. Prefix affinity improves cache hits but creates hot spots. Use bounded-load consistent hashing so a replica can refuse when it is overloaded.
  • Persisting partial replies. Writing every token is too expensive; writing only at the end loses work on crash. Checkpoint every few hundred tokens.
  • Safety latency. Blocking on an input classifier adds TTFT. Run it in parallel with prefill and cancel generation if it flags.
  • Deletion is hard. A deleted conversation lives in the primary store, caches, analytics events, backups and possibly eval datasets. Design data lineage from day one.
  • Tool loops. A model calling search ten times in a row burns money and time. Cap tool iterations per turn.
  • Measuring the wrong latency. Request latency is meaningless for streams; track TTFT, inter-token latency and stall rate.

Checklist

  • Back-of-envelope shows GPU decode throughput as the main constraint, and the design addresses it.
  • User message is persisted before generation; replies stream over SSE with resumable sequence numbers.
  • Router uses prefix-aware affinity so prompt caching actually hits.
  • Rate limits are token-based, per tier, and enforced before touching GPUs.
  • Context window strategy (truncate, summarize, retrieve) is explicit.
  • There is a written degradation policy for model or capacity outages.
  • Safety classifiers run without adding serial latency.
  • Deletion covers every copy of conversation data.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.