LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changes
How to design a ChatGPT-style LLM serving platform in real interview order: the numbers in tokens, a streaming API with token-based limits, a router that picks model, version and a replica with the conversation's prefix cached, one message end to end, conversations and the KV cache, a lab on GPUs, batching and cost per request, a lab on bursts and admission control when GPUs take minutes to add, evals, LLM judges, canary rollouts and guardrails, and what happens when each part fails.
The 1-minute answer
How this page follows the interview
Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.
New to tokens, prefill, decode and the KV cache? Foundations F18 (AI foundations: inference, RAG and agents) explains them on one GPU; this page builds the platform around them.
Requirements and numbers
Agree the product, the tiers and two latency numbers, then size it in tokens, not requests. Change any input: each number comes with the decision it forces, and those decisions come back in the design and the deep dives.
Functional
- Send a message, get the answer streamed word by word
- Conversations with history; come back to old chats
- Several models (fast and smart) and tiers (free, paid, API)
- Stop generating, regenerate, thumbs up / down
- Safety filters on what goes in and what comes out
Non-functional
- First token (TTFT) under 1 s at p95 for paid chat
- Then ~20 tokens/s: time per token under 50 ms
- 99.9% of streams finish without an error
- Cost per request is a goal, tracked per model
- A heavy user or tenant can't slow everyone else
Out of scope (say it)
Training and fine-tuning runs, tool use and browsing, images and voice, search over old chats, sharing. RAG and agents have their own parts in this track.
Capacity calculator
Every input is an assumption 🔶: say it out loud. Third-party prep guides assume about 200 million daily users and ~20,000 prompts/s at peak for a ChatGPT-scale question. Mooncake's real Kimi trace averaged 7,955 input and 194 output tokens per request. ✅ Mooncake 2024 160 KB/token is a Llama-3-70B-shaped model with an 8-bit KV cache (2 × 80 layers × 8 KV heads × 128 × 1 byte). 1,000 tokens/s per GPU sits between the fleet lab's first two presets.
- A day is 86,400 seconds; size for the busiest hour, not the average.
- Output tokens set the GPUs. Each one is a decode step; prompt tokens are processed in parallel and are cheaper per token.
- Little's law for streams. Open streams = messages/s × seconds per answer.
Core entities and the API
A conversation holds messages; a message's answer is generated by one model version on one replica. What they listen for: streaming with event ids, an Idempotency-Key on send, cancel that reaches the GPU, and usage in tokens.
| Entity | Key fields | Note |
|---|
Token limits: why max_output_tokens matters
A limiter can't know how long an answer will be, so it reserves prompt + max_output_tokens when the request starts and refunds the rest at the end. Change the numbers and watch how many requests fit in a minute.
How real APIs do it
- Two limits, whichever runs out first: requests per minute and tokens per minute (plus per-day limits). ✅ OpenAI docs
- Reserve the maximum: the limit counts the larger of max_tokens and the estimated tokens; set max_tokens close to the expected answer. ✅ OpenAI docs
- Tell clients when to come back: 429 with Retry-After and x-ratelimit-remaining-tokens headers; failed requests still count. ✅ OpenAI docs
- Where I'd keep the buckets: Redis, per key and per org, checked in under a millisecond. 🧭
The same idea protects the GPUs: admission charges a request for the tokens it might generate, not the ones it will.
High-level design
Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.
Walk one message, box by box
From "send" to a saved answer, then an overload, a replica that dies mid-answer and a canary that gets rolled back. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.
Arrows show who calls whom, and the numbers give the order. Replies go back along the same line.
Keeping a stream alive
An answer is a connection that stays open for seconds to minutes, across phone networks and deploys. These six details are what separates a demo from a product.
Data and database choices
Conversations are a simple, huge append-and-read-the-tail workload; limits must answer in under a millisecond; the KV cache is a cache of computation, not data; billing must never block a stream.
| Data | Pick | Considered | Why not those |
|---|
The one rule to know: picking a replica
# For one request: pick a replica of the chosen model version.
# Illustrative scoring; real pickers (SGLang, Gateway API endpoint
# pickers, llm-d) use variations of the same signals.
def pick(req, replicas):
blocks = prefix_block_hashes(req.prompt_ids) # 16-token blocks
best, best_score = None, -inf
for r in replicas:
if r.kv_used > 0.90 and req.priority == "sheddable":
continue # protect hot replicas
cached = r.longest_cached_prefix(blocks) # tokens we can skip
wait = r.queued_tokens / r.prefill_rate # seconds of queue
score = cached / r.prefill_rate - wait # seconds saved - waited
if score > best_score:
best, best_score = r, score
if best is None or -best_score > req.wait_budget_s:
return reject(429, retry_after=estimate_wait())
return bestIllustrative. SGLang orders waiting requests by matched prefix; the Gateway API endpoint picker filters on queue length and KV use. ✅ SGLang · CNCF 2025
Why cache affinity matters
- Chats repeat themselves. Every turn re-sends the system prompt and the history. 73% of ShareGPT conversations have more than one turn. ✅ CachedAttention 2024
- Hits are per replica. A prefix cached on replica 17 doesn't help replica 4. Send the conversation back where its prefix lives. 🧭
- But not blindly. A replica with the prefix and a long queue can be slower than one without it. Score seconds saved minus seconds waited. 🧭
- Real hit rates: 52–74% in Chatbot Arena with SGLang; about 50% on Kimi's real trace. ✅ SGLang · Mooncake
More database questions
Deep dive: GPUs, batching and cost per request
The fleet's size comes from one question per pool: how many requests can one copy run at once before memory runs out or time per token passes the target? The chart shows time per token for the large model as the batch grows. Pick a preset, then change the numbers.
Teal: time per token for the 70B pool as more requests share each step. Dashed: your target. Red: the most that fit in memory. The dot is the batch the fleet runs. Roofline model on H100s with 8-bit weights and KV; rounded teaching numbers. 🧭
| Per pool | 70B · 2 GPUs a copy | 8B · 1 GPU a copy |
|---|
The rules this lab teaches
- Batch until the latency target says stop. Decode reads every weight once per step, however many requests share it. Continuous batching (Orca) made this practical. ✅ Orca 2022
- Memory caps the batch. Each request holds its KV cache for its whole life; long prompts, not users, fill the GPU. ✅ vLLM 2023
- Prefill steals decode time. Every new request's prompt runs inside everyone's steps. Prefix caching and chunked prefill shrink the theft. ✅ vLLM docs
- The cheapest GPU is the one you don't need: route easy requests to a small model, verified on evals. 🧭
Real numbers to quote
Orca: 36.9× the throughput of FasterTransformer at the same latency (GPT-3 175B). ✅ OSDI 2022
SGLang: up to 6.4× throughput from prefix reuse and cache-aware scheduling. ✅ 2024
CachedAttention: reusing KV across turns cut TTFT by up to 87% and cost by up to 70%. ✅ 2024
Deep dive: bursts, admission control and slow GPUs
A web tier adds servers in seconds. A model copy needs a GPU node and tens of GB of weights: minutes. Until it arrives, someone waits or someone is told no. The chart shows arrivals against capacity, and the queue wait it causes. Pick a preset, then change the numbers.
Top: requests/s arriving (dashed) and capacity (teal). Bottom: seconds a new request waits for a slot (apricot); the line is your wait budget. Fluid-queue model in 1-second steps; teaching numbers. 🧭
Three levers, in order
- Say no early. Reject what can't start within the wait budget, with Retry-After. Mooncake rejects early under overload rather than let queues grow. ✅ Mooncake 2024
- Choose who waits. Free and batch traffic is "sheddable"; paid and critical traffic is protected. The Gateway API endpoint picker has exactly these two classes. ✅ CNCF 2025
- Buy time ahead, not during. Pre-warm before known launches; scale on queue wait and KV use, on a schedule for daily peaks. 🧭
Why GPUs are slow to add
AWS, Llama 3.1 70B: about 5–7 minutes end to end to bring up a new copy on a new instance; downloading weights alone took 127–602 s before their fast loader. ✅ AWS Dec 2024
Degrade, don't just drop: send some traffic to the small model and cap output length for free users while capacity arrives. 🧭
Deep dive: changing models and prompts safely
A new model, system prompt or engine setting can be faster and worse, and latency graphs won't show it. Ship quality changes like risky deploys: measured offline, tried on a few users, and reversible in seconds.
The rollout ladder
LLM-as-judge: useful, with known limits
Prompt, RAG or fine-tune?
Tick what's true for the feature.
OpenAI's guide: prompting "may be all you need"; fine-tuning helps formats and "smaller, cheaper, faster" models. Its page now says the fine-tuning platform is winding down for new users. ✅ OpenAI docs, Oct 2026
What happened when it went wrong
OpenAI, April 2025: a GPT-4o update passed offline evals and a small A/B test, then turned out sycophantic. They rolled it back (about 24 hours to complete) and committed to block launches on qualitative signals even when A/B metrics look good. ✅ OpenAI May 2025
Anthropic, Aug–Sep 2025: three infrastructure bugs (a context-window routing error, a TPU misconfiguration, a compiler bug) degraded some answers; the routing bug hit 16% of Sonnet 4 requests at its worst hour. None came from load. ✅ via InfoQ, Oct 2025
Guardrails, in layers
- Input: a fast policy classifier; Llama Guard classifies both prompts and responses against a taxonomy. ✅ Llama Guard 2023
- Output: check the stream every few dozen tokens; streaming makes moderation harder because partial text is harder to judge. ✅ OpenAI docs
- Tools and data: least privilege, so a fooled model can't do much. 🧭
- Fail mode decided ahead, per surface. 🧭
A request's lifecycle
Inside the engine every request is a small state machine. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.
Edge cases interviewers love
Failure, monitoring and recovery
An LLM platform fails in two ways: loudly (errors, timeouts, 429s) and quietly (worse answers with green graphs). Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.
Tracing it back: a healthy message vs one under KV pressure
Every span carries the request id, model version and replica. Times are seconds from arrival. In the bad trace, every replica is near full: the request waits, gets no cached prefix, is preempted mid-answer and recomputes its prompt.
How one failure becomes three
What you'd alert on (SLOs)
| Signal | Target | Alert |
|---|
Incident playbook
The toolkit
Name the technique, then say where it goes in this design.
Making it fast, and who owns what
Everything before the GPU takes tens of milliseconds; prefill sets the first token, decode sets the rest, and capacity takes minutes. Bars are sizing estimates, not measured figures.
| Team | Owns | Paged when… |
|---|
Senior follow-ups beyond the happy path
Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.
Practice ladder
Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.
Sources
- Orca: A Distributed Serving System for Transformer-Based Generative Models, Yu et al., OSDI (2022)
- Efficient Memory Management for Large Language Model Serving with PagedAttention, Kwon et al., SOSP (2023)
- DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM Serving, Zhong et al., OSDI (2024)
- Mooncake: A KVCache-centric Disaggregated Architecture for LLM Serving, Moonshot AI and Tsinghua (Jul 2024)
- SGLang: Efficient Execution of Structured Language Model Programs (RadixAttention), Zheng et al. (Jun 2024)
- Cost-Efficient LLM Serving for Multi-turn Conversations with CachedAttention, Gao et al. (Jun 2024)
- The Llama 3 Herd of Models, Meta (Jul 2024)
- NVIDIA H100 Tensor Core GPU specifications (checked Oct 2026)
- Optimization and tuning (preemption, chunked prefill), vLLM docs (checked Oct 2026)
- Production metrics, vLLM docs (checked Oct 2026)
- Introducing the Gateway API Inference Extension, Kubernetes blog (Jun 2025)
- Deep dive into the Gateway API Inference Extension, CNCF blog (Apr 2025)
- Introducing Fast Model Loader in SageMaker Inference, AWS Machine Learning blog (Dec 2024)
- Rate limits, OpenAI API docs (checked Oct 2026)
- Prompt caching, OpenAI API docs (checked Oct 2026)
- Streaming API responses, OpenAI API docs (checked Oct 2026)
- Batch API FAQ, OpenAI Help Center (checked Oct 2026)
- Model optimization, OpenAI API docs (checked Oct 2026)
- Expanding on what we missed with sycophancy, OpenAI (2 May 2025)
- Anthropic reveals three infrastructure bugs behind Claude performance issues, InfoQ (3 Oct 2025)
- Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena, Zheng et al., NeurIPS (2023)
- Llama Guard: LLM-based Input-Output Safeguard for Human-AI Conversations, Inan et al. (Dec 2023)
- ChatGPT problem breakdown, Hello Interview (third party, used to cross-check interview expectations)
Checked October 2026. Mechanisms come from papers (Orca 2022, vLLM/PagedAttention 2023, DistServe 2024, Mooncake 2024, SGLang 2024, CachedAttention 2024, LLM-as-a-judge 2023, Llama Guard 2023, Llama 3 2024) and official docs (vLLM optimization and metrics, OpenAI rate limits, prompt caching, streaming, Batch API and model optimization guides, NVIDIA H100 datasheet). Incidents are as published: OpenAI's sycophancy postmortem (May 2025) and Anthropic's August–September 2025 bugs as reported by InfoQ (Oct 2025; Anthropic's own post couldn't be fetched for this run). The Gateway API endpoint-picker thresholds are from a CNCF post (Apr 2025) about an early version and may have changed. Hello Interview is a third-party prep site, used only to cross-check what interviewers expect. Both labs use rounded teaching values on H100-class GPUs with Llama-3-shaped models, not benchmarks; providers' real configurations aren't public.
System Design Mastermind · AI / ML systems
Series homeAll of AI / ML systems
8 published · 1 comingLLM and ML systems, where interviews are heading.
LLM serving platform system design (ChatGPT-style): tokens, GPUs and safe model changes
Chat API (auth, token limits, history, safety, SSE with resumable event ids) → router picks model (easy turns to a small one), version (registry canary split) and a replica with the prefix cached → vLLM-style engines batch continuously up to the time-per-token target. Admit by priority because GPUs take minutes to add; ship every model change through evals, shadow and canary, with rollback by one number.
RAG assistant over company docs system design: retrieval, permissions and answers you can trust
Ingestion (change events + full sync → parse → chunk with a context line → embed only changed chunks) fills a versioned index of keywords, vectors and allowed principals. Serving rewrites the question, runs hybrid search with the permission filter inside it, reranks 150 → 8, answers only from numbered sources, checks grounding and re-checks cited docs. A golden set gates every change.
AI agent platform system design: tools, durable runs, approvals and agents you can trust
A durable orchestrator runs each agent as workflow code: pin the version, call the model through a caching gateway, record every step so crashes resume. The model only proposes tool calls; a tool gateway validates, authorizes with the user's own token, adds idempotency keys and parks irreversible steps for approval. Budgets stop runaways; end-state evals with k tries gate every release.
Offline GPU batch inference system design: millions of LLM calls by a deadline, on GPUs that can vanish
Validate the file, split it into ~20-minute shards, lease them to GPU workers on spot that load the model once and run hundreds of rows at a time with the shared prompt cached. Each attempt writes its own file; one conditional commit per shard makes output exactly-once. Golden set and canary shard gate every new version.
Content moderation pipeline system design: hash matching, classifiers, LLM checks and human review at a billion items a day
Hash at upload against known-bad lists, score every policy with small classifiers in ~50 ms, two lines per policy: remove above, allow below, and the band between goes to an LLM that reads the policy, then a review queue ordered by severity × reach × likelihood. Every decision logged with a reason, appealable, and gated by golden set → shadow → canary.
Recommendation system design (TikTok-style For You feed): candidates, ranking, freshness and A/B tests
Several sources (two-tower ANN search, like-your-likes, trending, a fresh pool) retrieve a few thousand items; a light ranker keeps a few hundred; a heavy multi-task ranker predicts finish, like, share and skip; a value model and re-rank add diversity, in ~200 ms. Events stream back to features in seconds and to incremental training in minutes; models ship via interleaving and A/B tests.
LLM evaluation and guardrails platform system design: judges, guard latency, paired eval gates and safe rollouts
Every product calls an AI gateway: versioned config, input guards (PII mask, a small injection classifier, an LLM judge only when unsure), output guards on streamed chunks, a trace per request. Off the path: sampled traces judged online, people calibrating the judges, failures turned into regression tests, and every change gated by a paired eval with error bars, then shadow, canary and A/B.
AI coding agent system design (Claude Code, Cursor, Codex): context, edits, sandboxes and evals
Three shapes, one backend: a small self-served Tab model per keystroke; an agent loop with a context engine (grep plus an optional index), a cached prompt to a frontier model, text-anchored edits or a fast apply model, permissions and an OS sandbox; and background agents in a container per task that open a PR. An eval harness gates every change on pass^k.