All posts
System Design Mastermind · Part 22
  • System design
  • Interview prep
  • LLM inference
  • AI/ML systems
  • GPU serving

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.

23 Oct 2026 · 34 min read · interactive

Share

The 1-minute answer

It's two systems. A normal chat product: an API that authenticates, enforces limits in tokens (not just requests), loads the conversation's history, runs a safety check, and streams the answer over server-sent events with event ids so a dropped connection can resume. Behind it, a GPU fleet with unusual numbers. A router picks the model (easy turns to a small model), the version (a registry holds the canary split) and the replica (one that already has this conversation's prefix in its KV cache and has room). Each replica runs an engine like vLLM with continuous batching and a paged KV cache: one read of the weights serves many conversations, so you batch until the time-per-token target says stop. GPU memory (weights plus every request's KV cache) and that target set capacity; output tokens per second set the bill. GPUs take minutes to add, so keep headroom, pre-warm for launches, and admit by priority: 429 with Retry-After for what can't start in time, free tier first. Every model or prompt change passes offline evals (with LLM judges you've checked against humans), then shadow and canary traffic watched on quality as well as latency, and rolls back by changing one number.

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.

✅ Seen: said publicly (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

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.

Three rules for this estimate
  1. A day is 86,400 seconds; size for the busiest hour, not the average.
  2. Output tokens set the GPUs. Each one is a decode step; prompt tokens are processed in parallel and are cheaper per token.
  3. Little's law for streams. Open streams = messages/s × seconds per answer.
They'll push on thisAnswer out loud, then open.

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.

EntityKey fieldsNote
Request
Response

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.

They'll push on thisAnswer out loud, then open.

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.

They'll push on thisAnswer out loud, then open.

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.

On the wire

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.

    DataPickConsideredWhy 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 best

    Illustrative. 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

    1. Chats repeat themselves. Every turn re-sends the system prompt and the history. 73% of ShareGPT conversations have more than one turn. ✅ CachedAttention 2024
    2. Hits are per replica. A prefix cached on replica 17 doesn't help replica 4. Send the conversation back where its prefix lives. 🧭
    3. 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. 🧭
    4. Real hit rates: 52–74% in Chatbot Arena with SGLang; about 50% on Kimi's real trace. ✅ SGLang · Mooncake

    More database questions

    They'll push on thisAnswer out loud, then open.

    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 pool70B · 2 GPUs a copy8B · 1 GPU a copy

    The rules this lab teaches

    1. 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
    2. Memory caps the batch. Each request holds its KV cache for its whole life; long prompts, not users, fill the GPU. ✅ vLLM 2023
    3. Prefill steals decode time. Every new request's prompt runs inside everyone's steps. Prefix caching and chunked prefill shrink the theft. ✅ vLLM docs
    4. 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

    They'll push on thisAnswer out loud, then open.

    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

    1. 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
    2. 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
    3. 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. 🧭

    They'll push on thisAnswer out loud, then open.

    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

      1. Input: a fast policy classifier; Llama Guard classifies both prompts and responses against a taxonomy. ✅ Llama Guard 2023
      2. Output: check the stream every few dozen tokens; streaming makes moderation harder because partial text is harder to judge. ✅ OpenAI docs
      3. Tools and data: least privilege, so a fooled model can't do much. 🧭
      4. Fail mode decided ahead, per surface. 🧭
      They'll push on thisAnswer out loud, then open.

      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.

      NormalSomething went wrongGreyed out: not possible from the current state.

      Edge cases interviewers love

      They'll push on thisAnswer out loud, then open.

      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)

      SignalTargetAlert

      Incident playbook

        The toolkit

        Name the technique, then say where it goes in this design.

        They'll push on thisAnswer out loud, then open.

        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.

        TeamOwnsPaged 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

        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 home

        All of AI / ML systems

        8 published · 1 comingLLM and ML systems, where interviews are heading.

        22

        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.

        You're reading this Preview
        25

        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.

        34 min · interactive Preview
        28

        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.

        35 min · interactive Preview
        31

        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.

        34 min · interactive Preview
        34

        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.

        34 min · interactive Preview
        35

        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.

        34 min · interactive Preview
        36

        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.

        33 min · interactive Preview
        37

        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.

        34 min · interactive Preview
        ··

        Feature store and training platform

        Coming next

        More posts