Fig. 1 draws that loop: training and serving are two lanes of one loop, and most failures live where the lanes meet. Numbers in the figure are this page's sections.
The running example is a support assistant sold to 10,000 business tenants: an LLM answers customers' tickets, and a small classifier, the escalation model, decides which tickets a human should take. Its latency figures use the parent topic's chat-assistant shape (1,000 input and 400 output tokens per reply, from the Scale simulator); its cost figures use the support shape of section 6.
You need the general design method (requirements, estimates, high-level design, deep dives) from the parent's Step 6, Topic: swe-and-system-design. Each component's insides are owned elsewhere and linked where they come up: feature stores on ML platforms and workflows, serving engines on Topic: inference-and-serving, retrieval on Topic: rag-and-retrieval, evaluation on Topic: evaluation-and-llm-judges, whole worked designs on System design case studies.
Before any model: what decision is being automated, how will anyone know it got better, and what is the cheapest thing that already does it? For the support assistant the decision is "answer this ticket, or hand it to a human". Every metric the system will ever report sits on one ladder under that decision.
Chip Huyen's booklet uses project setup, data pipeline, modelling and serving (Machine Learning Systems Design); Aminian and Xu's Machine Learning System Design Interview (ByteByteGo, 2023) is commonly summarised as seven steps (clarify requirements, frame as an ML task, data, model, evaluation, deployment and serving, monitoring; the course page is behind a login, so that list is unconfirmed here). Both start where this section does. The deeper warning behind "get the infrastructure right" is Sculley et al.'s "Hidden Technical Debt in Machine Learning Systems": a mature system might be "(at most) 5% machine learning code and (at least) 95% glue code", and "Changing Anything Changes Everything" (NeurIPS 2015).
The support assistant's ladder. A model can climb the offline metric while the objective falls: an assistant that answers more tickets alone scores well on "resolved without escalation" and badly on wrong answers, which is why guard metrics sit beside the online metric. System metrics (latency, cost) are requirements, not goals; section 4 sets their budget.
The escalation model reads features, numbers computed from data such as "tickets this customer opened in the last 7 days". Each feature is computed twice: offline, for every historical training row, from the warehouse; and online, for the live ticket, in milliseconds. Uber's Michelangelo is the reference picture of the two paths: online features "precomputed and stored in Cassandra where they can be read at low latency", serving at "P95 latency of less than 5 milliseconds" without stored features and "less than 10ms" with them (Uber Engineering, Meet Michelangelo, 5 Sep 2017). Two code paths for one number is where the classic ML bug lives.
Fig. 2 follows one feature, "tickets this customer opened in the last 7 days", for one live ticket. Illustrative ticket times; the two definitions differ the way real ones do: a calendar-day window in UTC against a rolling 168 hours, and a nightly job that has not yet seen today.
Google's Rules of ML define training-serving skew as "a difference between performance during training and performance during serving", caused by "A discrepancy between how you handle data in the training and serving pipelines", "A change in the data between when you train and when you serve", or "A feedback loop between your model and your algorithm" (the last is section 5). Three rules fix the first two causes (Rules of ML):
A feature store productises Rule #32: features are defined once, computed into an offline store for training and an online store for serving, and read through one API. Its key guarantee is point-in-time correctness: a training example labelled at 8:50 must only see feature values known at 8:50, not ones computed at 8:52, or the model learns from the future and disappoints in production (Databricks docs, point-in-time joins). How feature stores work (Feast's offline and online calls, materialisation, the point-in-time join) is owned by ML platforms and workflows, section 9; a point-in-time join measured in DuckDB, with the leak it prevents, is section 11 of Analytics: columnar engines, DuckDB and the lakehouse.
LLM products have skew too, with prompts in place of features: a prompt template assembled differently in the evaluation harness and in production, a retrieval index rebuilt between evaluation and launch, a tokenizer or chat-template version mismatch. Rule #29 transfers directly: log the exact prompt the model saw, and evaluate on logged prompts.
Michelangelo in 2017 had "approximately 10,000 features in Feature Store", "the highest traffic models right now serving more than 250,000 predictions per second", and offline models wrote predictions "back to Hive" for other jobs to read. By 2024 there were "more than 5K models in production, serving 10 million real-time predictions per second at peak", and the platform had added a Gen AI Gateway with logging, cost attribution and PII redaction (Uber, From predictive to generative AI, 2 May 2024).
Airbnb's Chronon (open-sourced 2024 with Stripe as co-maintainer) lets teams "define their features only once, powering both offline flows for model training as well as online flows for model inference", and measures consistency by comparing logged online fetches with backfilled values (Airbnb Engineering): Rule #37's third gap (section 3), measured per feature. Feast (v0.66.0) likewise "ensures point-in-time correctness so future feature values do not leak to models" (Feast quickstart).
An offline score is measured on stored data; the decision to ship is about live traffic. Rules of ML, Rule #37 ("Measure Training/Serving Skew"), splits the distance between them into gaps, each with its own meaning. Adding the gap to the product goal from section 1 gives four.
For an LLM the offline set is a set of past tickets scored by tests, graders or judges, and it is a statistic, not a test suite: models sample, and even at temperature zero serving engines are not deterministic, because the numerical result of a matrix multiplication depends on how many other requests share the batch. Thinking Machines sampled the same prompt 1,000 times at temperature 0 from Qwen3-235B and got 80 different completions; with batch-invariant kernels all 1,000 were identical, at a cost in speed (Thinking Machines, 10 Sep 2025).
Quotes from Rules of ML, Rule #37. Bar heights are schematic: the rule names the gaps, not their sizes.
So a change ships in stages, each answering a question the one before cannot. A "change" is any of: a new model or provider version, a prompt, sampling parameters, an engine version or GPU type (Anthropic's postmortem shows the same model behaving differently on different hardware stacks), or a router.
The statistics of each stage (how much traffic, for how long, which test) and golden sets and CI gates are owned by Production eval engineering; the offline regression suite by the sibling Testing and quality. Staged rollout costs days instead of minutes per change, shadow compute, and two versions in production at once (two prompt caches, two sets of GPUs if self-hosted); internal tools and prototypes can switch at once behind a flag, anything customers depend on cannot.
The machinery (Istio mirroring with mirrorPercentage, KServe's canaryTrafficPercent, Argo Rollouts' analysis steps) is on Production eval engineering, section 8. Two design rules stay here: shadowing doubles model cost for the mirrored share, so mirror a sample and never mirror requests with side effects (tool calls that send email or charge cards); and key the canary split by user or tenant so one conversation stays on one version.
Pinning. Use a dated model snapshot, not an alias the provider moves: otherwise quality changes overnight with no deploy to roll back.
The serving shape follows from one question: who waits for the prediction, and how long? Splitting traffic by that answer is the biggest cost lever after model choice, because work that can wait can run when hardware is idle or cheap.
| Batch scoring | Online inference (request/response) | Streaming | |
|---|---|---|---|
| What | run the model over every user or item on a schedule; the product reads a table | compute the prediction inside the request, with fresh features | an LLM reply sent token by token as it is generated |
| Examples | daily recommendations, churn scores, nightly embeddings and evaluations; Michelangelo's offline models wrote to Hive | fraud check on a transaction, the escalation model, embedding a query | chat replies, agent steps shown live |
| Who waits | nobody; a deadline in hours | a program, milliseconds to a second | a person, watching tokens arrive |
| Optimise | cost per prediction (tokens per dollar) | end-to-end latency | TTFT, then TPOT |
| Price | stale between runs; wasted on users who never come | fresh features at serving time, so skew risk (section 2) | connections open for minutes through every proxy |
Fig. 3 puts the three shapes side by side; the streamed reply in front is drawn to scale from this page's latency model (below).
Batch through providers costs half: OpenAI's Batch API gives a "50% cost discount compared to synchronous APIs" and each batch "completes within 24 hours (and often more quickly)" (OpenAI Batch API). On your own GPUs, a batch lane at low priority fills the overnight trough of a fleet sized for the busy hour.
A reply is generated one token at a time, so its latency is two numbers. Time to first token (TTFT) covers arrival, waiting in the engine's queue and prefill (reading all input tokens at once); it is what the user feels as "is it working?". Time per output token (TPOT) is the gap between streamed tokens in decode; vLLM defines it per request as "(end-to-end latency - TTFT) / (number of output tokens - 1)" (vLLM metrics design doc, v0.30.0). So end-to-end latency = TTFT + (output tokens − 1) × TPOT.
data: ... lines on one open HTTP response.Predict first: doubling the reply from 400 to 800 tokens, what happens to TTFT and to end-to-end time? Then drag.
Derived for Llama 3.3 70B in FP8 on two H100s, the parent topic's shared figures: about 0.09 s of prefill for 1,000 input tokens (at an illustrative 40% of peak arithmetic) with an empty queue, and 4,418 output tokens a second per two-GPU replica shared by 64 conversations (the batch of 64 is the parent's illustrative engine limit), so 69 tokens a second each and a TPOT of 14.5 ms: 0.09 + 399 × 14.5 ms = 5.9 s. TTFT does not move with reply length; queueing (section 7) is what moves it.
Provider batches. Anthropic's Message Batches: "All usage is charged at 50% of the standard API prices", "most batches finishing in less than 1 hour", a batch holds up to 100,000 requests or 256 MB, unfinished requests expire after 24 hours and are not billed, and the discount stacks with prompt caching (Anthropic batch processing). OpenAI's batches have their own higher rate limits. Between realtime and batch there are speed tiers on the same API: OpenAI's Flex processing trades "slower response times and occasional resource unavailability" for batch prices, and returns a 429 it does not charge for when capacity is short; its premium tier, renamed from Priority processing to Fast mode on 30 July 2026, charges more per token for up to 2.5 times the speed (Flex processing, Fast mode).
A batch lane on your own GPUs needs a priority scheduler in the engine or router (the vLLM production stack router has a priority option; replica routers are compared on LLM serving in production, section 2) and batch jobs that tolerate being paused; a batch job that cannot be paused holds slots during the morning ramp. It is also the natural home for preemptible spot GPUs. If under a tenth of your tokens can wait, the second path is not worth its code.
Long jobs behind a person (generate a report, run an agent for ten minutes) use the parent topic's asynchronous pattern: accept the job, return 202 Accepted with a job id, queue it, and let the client poll or receive a callback. Anthropic advises "the streaming Messages API or Message Batches API for long-running requests, especially those over 10 minutes". Delivery guarantees, retries and dead-letter queues belong to Queues, streams and async work.
Online inference with shadowing. DoorDash's Sibyl prediction service fetched features from Redis per prediction, ran shadow predictions for candidate models on the same inputs, and load-tested at "over 100,000 predictions per second" (DoorDash Engineering, 29 Jun 2020).
Embedding services are a throughput problem: many short inputs, batched by tokens. Hugging Face's Text Embeddings Inference (v1.9.4) has "Token based dynamic batching" with --max-batch-tokens (default 16384; "you could fit 10 queries of total_tokens=100 or a single query of 1000 tokens" for a limit of 1,000) and --max-concurrent-requests (default 512), where "Having a low limit will refuse clients requests instead of having them wait for too long and is usually good to handle backpressure correctly" (TEI CLI arguments). Embeddings from different models live in different spaces, so changing the embedding model means re-embedding the whole corpus (a batch job, usually written to a new index and switched over once complete; reasoning, not a sourced rule), and the model version belongs in every stored vector's metadata. Smaller vectors are a cost lever: a text-embedding-3-large vector "can be shortened to a size of 256 while still outperforming an unshortened text-embedding-ada-002 embedding with a size of 1536" (OpenAI embeddings guide). Embedding models themselves are owned by Topic: rag-and-retrieval.
MLPerf for a reasoning model: DeepSeek-R1 targets are 2,000/80 ms and 1,500/15 ms (same source).
Illustrative scores and labels for 24 tickets; a stepper (each step a still), not a simulation.
A web service is correct until its code changes. A model gets worse while nothing changes, in two ways. Its own actions select its next training data (a feedback loop), and the world moves away from the data it learned from (drift). Sculley et al. name both: "A model may directly influence the selection of its own future training data", and "Experience has shown that the external world is rarely stable" (Hidden Technical Debt in ML Systems, NeurIPS 2015).
The same paper describes the harder case, hidden feedback loops, "in which two systems influence each other indirectly through the world", for example one system choosing products to show and another choosing reviews. Rules of ML adds the most common one in ranking, Rule #36, "Avoid feedback loops with positional features": "The position of content dramatically affects how likely the user is to interact with it", so a model trained on clicks learns its own ranking back. For an LLM product the loop runs through prompts and evaluations: replies rated by users who saw them, and evaluation sets drawn from traffic the current model shaped.
| Layer | Signals | What it catches |
|---|---|---|
| Service | request rate, errors, TTFT and TPOT histograms per model and tenant, queue depth | outages and overload; owned by Observability and section 7 |
| Inputs | feature distributions against training, missing or default values, logged-against-backfilled feature values, prompt length | drift, broken upstream producers, skew (Rule #37's third gap) |
| Predictions | prediction bias, escalation rate, output length, refusal rate | a changed world or a changed model, before labels arrive |
| Outcomes | labels as they arrive, judge scores on sampled traffic, thumbs, re-opened tickets, the online metric | quality loss that returns 200 OK |
Two of Sculley et al.'s checks are cheap and general. Prediction bias: "the distribution of predicted labels is equal to the distribution of observed labels" in a system working as intended; "by no means a comprehensive test", but "a surprisingly useful diagnostic", and slicing it "by various dimensions" isolates issues quickly. Action limits: in systems that act in the world, "set and enforce action limits as a sanity check", which alert when hit. For LLMs the outcome layer is the one that matters most, because failures are fluent: in August 2025 a routing bug sent some Claude Sonnet 4 requests to servers configured for a different context length; at the worst hour 16% of Sonnet 4 requests were affected, error rates stayed normal, and users noticed before the evaluations did. Anthropic's lesson: "The evaluations we ran simply didn't capture the degradation users were reporting", and it now runs quality evaluations "continuously on true production systems" (Anthropic, 17 Sep 2025; the parent topic's Case files, "Three serving bugs quietly made Claude's answers worse"). How to score sampled traffic online is owned by Production eval engineering.
With an LLM the "model" box of the hero is a design of its own. The design question is what the base model lacks for this task, answered with the cheapest rung that supplies it; each rung up adds cost, latency and something new to evaluate.
The baseline is rung 1; the evaluation set of section 3 decides whether a rung earned its cost.
| What is different | Ordinary web request | LLM request | What the design adds |
|---|---|---|---|
| Cost | about $0.0000001 | $0.0004 to $0.006, more for long documents | quotas and cost accounting, routing to cheaper models, caching (section 7) |
| Duration | milliseconds | seconds; the reply streams | streaming paths, per-token latency targets (section 4) |
| Size known in advance | roughly | no: output length is decided by the model | limits and autoscaling on tokens and queues, not requests |
| Same input, same output | yes | no | rollouts judged by evaluations, not by tests passing (section 3) |
| Capacity | small cheap servers, added in seconds | 2 to 8 GPUs per copy of the model, minutes to start | headroom, warm pools, the right autoscaling signals |
| Failure | an error | an error, or a plausible wrong answer | degradation ladders and quality monitoring (sections 5 and 7) |
The cost row, derived. An app server (AWS m7i.xlarge, $0.2016 an hour, the parent topic's figure) at an illustrative 500 requests a second costs $0.2016 ÷ 3,600 ÷ 500 = $0.00000011 a request. One chat reply of 400 output tokens self-hosted, Llama 3.3 70B in FP8 on H100s at $3.99 per GPU-hour (Lambda pricing, read 2026-10-04) producing 2,209 output tokens a second per GPU (TensorRT-LLM perf overview at commit 8a9c66c, vendor benchmark, 1,000 input and 1,000 output tokens) run at half that rate to keep latency acceptable (illustrative derating): $3.99 ÷ 3,600 ÷ (2,209 × 0.5) = $1.00 per million output tokens, so $0.0004 per reply, about 3,600 times the web request. Through an API, Claude Sonnet 5.5 at $2 per million input and $10 per million output tokens (Anthropic pricing, the knowledge base's price snapshot of 2026-10-01): 1,000 × $2 + 400 × $10, per million, = $0.006, about 54,000 times. That is 3.6 to 4.7 orders of magnitude (a 100,000-token document to a frontier model reaches 6), so cost is an architecture problem: who may spend how much, which model a request deserves and which work need not be done twice are designed up front. Count tokens, not requests: two requests can differ in tokens by a factor of a thousand.
Illustrative inputs: 500 messages per tenant per day, busy hour 3 times the average, 3,000 input tokens (instructions plus retrieved documents) and 300 output tokens per message, 70% of input tokens a cached prefix.
The API costs six to ten times the self-hosted fleet at this volume (with and without caching), but buys a stronger model, no capacity risk and no GPU team; a router that sends easy tickets to a small tier and caching change the ratio, and the self-hosted fleet sized for the peak is mostly idle at night unless batch work fills it. "Prefix caching cuts the cost per message by about 40% here because 70% of each prompt is static" is the kind of quantified trade-off a design review wants. Checked in src/recompute.py. Move these levers yourself in the Cost-quality lab.
The prefix cache is the cheapest lever and the easiest to lose: it keeps the computed state of a prompt's beginning so the next request with the same beginning skips that part of prefill. It never changes the answer, only speed and price, and it matches from the first token, so prompt layout decides whether it works.
Six turns of a chat in the figure; each request holds a 2,000-token system prompt (instructions and tool definitions), the conversation so far, and the new message, which includes a 30-token line with the current time and user context. Only the order changes between the two layouts. Predict first: how much of turn 6 can come from the cache in each layout?
Prices: Claude Sonnet 5.5, $2 per million input tokens, $2.50 cache write (5-minute), $0.20 cache read, $10 output (Anthropic prompt caching, read 2026-10-04). Over six turns the "after" layout costs $0.0391 against $0.0655 (input alone: $0.0151 against $0.0415, 64% less), and the model processes 4,780 input tokens instead of 20,730. Illustrative token counts; checked in src/recompute.py. Caveats: a cache entry lives 5 minutes unless used (or 1 hour at a higher write price), there is a minimum cacheable length (512 to 4,096 tokens by model on Anthropic), and an entry "only becomes available after the first response begins", so parallel requests sent at once all miss.
The rule: prompts are append-only; anything that changes per request (time, user name, retrieved documents, a shuffled tool list) goes after everything that does not. And the request must reach a machine that has the prefix: provider caches live on individual machines (OpenAI: traffic "above 15 requests per minute" on one prefix "can lead to overflow routing"; a prompt_cache_key helps it route), and self-hosted pools need a prefix-aware router (LLM serving in production, section 2); Character.AI's sticky sessions reached a "95% cache rate" (parent's Case files). How engines keep the prefix is owned by Batching, KV cache and scheduling in depth.
Anthropic says prompt caching reduces "costs by up to 90% and latency by up to 85% for long prompts" (Anthropic; vendor figure). OpenAI applies it automatically to long prompts and advises putting "stable developer instructions and shared reference material first" (OpenAI docs). Both say the same thing as the animation above: what never changes goes first.
Serving the model behind one endpoint is where section 6 ends. Serving it to many tenants adds a layer of components between the app and the GPUs, each with a decision that stays with the system designer and internals owned by another page.
Fig. 4 follows the chat assistant's requests through that layer, priced by the Cost-quality lab's model at its defaults (1,000 input and 400 output tokens, 60% easy requests, a router that is right 90% of the time; every latency there is illustrative). Letters match the table below.
RateLimitError and gpt-4o served it, 3.41 s measured, of which 0.5 s is a pause the script adds, so about 2.9 s in the router; a ContextWindowExceededError on claude-haiku-4-5 went to the long-context model at once (0.521 s measured, about 0.02 s in the router). Retries, cooldowns and fallbacks call by call are on Gateways and routing.| Component | The design decision that stays here | Internals owned by | |
|---|---|---|---|
| A | LLM gateway, rate limits and quotas | one front door for every model call, for control not throughput (Uber's served a peak of 25 queries a second); limits count tokens, not requests, and cap concurrent streams per tenant; decide whether it fails open or closed when its own counters are unreachable | Gateways and routing; the token bucket on Reliability engineering |
| B | Router and fallbacks | a tier router is a classifier: measure it on labelled traffic, because a misrouted hard question is a worse answer no error counter sees; a fallback needs standing capacity elsewhere and the same prompt and tool format | model choice: Gateways and routing; replica choice: LLM serving in production |
| C | Tenants | isolate capacity, data, cost and customisation; the tenant id goes in every cache key and usage event | this page (closed block below) |
| D | Realtime, streaming and batch lanes | section 4's split, with batch on idle or spot capacity at low priority | this page, section 4 |
| E | Autoscaling | scale on queue depth and KV cache use, not CPU or GPU utilisation; keep headroom for growth during one cold start (minutes); with steady traffic, fixed capacity plus load shedding is simpler | LLM serving in production, sections 2 and 3 |
| F | Caches | exact, semantic, prefix and retrieval caches differ in what counts as "the same"; semantic caches return wrong answers | Caching: every layer, eviction, invalidation, and the LLM caches, section 11 |
| G | Rollout control | pinned versions and canary weights (section 3) | Production eval engineering |
| H | Usage events, metrics, quality | one usage event per request; quality sampled continuously (section 5) | LLM observability; Observability |
Never queue without a bound in front of a GPU. A queue that grows faster than it drains turns overload into minutes of waiting for everyone, and clients that time out and retry add more load. A bounded queue that refuses early, with 429 or 503 and Retry-After, keeps the requests it accepts fast, and a degradation ladder decided before the incident (second provider, smaller model, less context, cached answer, honest error) serves a worse answer instead of none. Both are in the closed blocks below with their sources.
It streams. Users will not stare at a blank screen for 6 seconds, so the reply is streamed: sent token by token over one open HTTP response. Every layer between the user and the GPU (load balancer, gateway, proxy) must pass the stream through without buffering it, and must allow connections that stay open for minutes.
Its size is unknown until it ends. Input is known; output length is decided by the model, from 1 token to the max_tokens cap. This breaks two web habits: limiting customers by requests per minute (one request can be a thousand times another) and scaling servers on request rate (a pool sized on requests falls behind when replies get longer).
Capacity comes in big blocks that start slowly. The 70B model's FP8 weights are 72.7 GB (model files on Hugging Face; sum of the weight files). One 80 GB H100 holds them with little room left for conversations, so a replica (one running copy of the model) spans two GPUs, and capacity grows two GPUs at a time; AWS rents H100s eight to a machine (p5.48xlarge, $55.04 an hour on demand, Vantage's AWS price mirror, read 2026-10-04). A new replica must get a GPU machine, download its software image, copy 73 GB of weights into GPU memory and warm up before it serves anyone. vLLM's maintainers list what a cold start pays even when weights load instantly: memory allocator setup, recording CUDA graphs, compiling GPU kernels, and first-request warm-up, and put a full model reload at "30-100+ seconds per switch" (vLLM blog, sleep mode, 26 Oct 2025). Add finding and booting a GPU machine and minutes are normal.
Autoscaling signals. CPU utilisation barely moves, GPU utilisation reads near 100% at a tenth of capacity, GPU memory is reserved at start, and requests per second ignores request size; queue depth and KV cache use work. If traffic can grow 20% during one cold start, keep about 20% spare. Spot GPUs, reclaimable with seconds to two minutes of warning, belong first in the batch lane. Set the TTFT target, size headroom from the measured cold start, and keep the metrics plumbing working: an autoscaler reading a renamed metric sees zero (next block).
max_tokens; usage recordedInter-token latency (ITL) is measured gap by gap; it differs from TPOT when a step emits several tokens at once (speculative decoding). In vLLM v0.30.0 (released 2026-09-22) the Prometheus metrics a system designer reads are vllm:num_requests_waiting ("Number of requests waiting to be processed"), vllm:num_requests_running ("Number of requests in model execution batches"), vllm:kv_cache_usage_perc ("KV-cache usage. 1 means 100 percent usage", a fraction despite the name), and the histograms vllm:time_to_first_token_seconds, vllm:inter_token_latency_seconds and vllm:e2e_request_latency_seconds (vllm/v1/metrics/loggers.py at v0.30.0). Names change between versions: vllm:gpu_cache_usage_perc was renamed to vllm:kv_cache_usage_perc in 0.9.2 and removed in 0.12, and vllm:time_per_output_token_seconds gave way to vllm:inter_token_latency_seconds in 0.11. Dashboards and autoscalers that query the old names go silent after an upgrade, which is a real way to lose autoscaling: alert on missing metrics.
The KV cache is the engine's memory of each conversation (keys and values for every token so far), in GPU memory, growing with every token, so it caps how many conversations a replica holds. For this model it is 2 × 80 layers × 8 key-value heads × 128 dimensions × 1 byte = 160 KiB per token (FP8 cache), so one 1,400-token conversation holds about 219 MiB. How engines manage it is the subject of the PagedAttention paper page; for the system designer, "KV cache full" means "no room for more conversations on this replica".
The first feature calls a model API directly with a key in an environment variable; by the fifth there are five copies of retry logic, three provider keys in three services, no idea which team spent $40,000 last month, and no way to switch providers during an outage. The gateway speaks one API shape (almost always OpenAI's chat completions format) and authenticates, checks limits and budget, redacts personal data and applies input rails (Guardrails), looks up caches, routes, calls with a timeout, retries or falls back, streams the reply back unbuffered, and writes one usage event per call. Which model: tier routing (prices differ 2 to 40 times between tiers of one vendor), context routing (long prompts to long-context pools; getting it wrong was Anthropic's August 2025 bug, section 5), policy routing (tenant pinning, data residency). Fallbacks are planned like a backup generator: enough quota for all the traffic, the same prompt and tool format, the same safety behaviour, a cold prompt cache. Which replica: a second load balancer inside a self-hosted pool that sees each replica's queue and prefix cache rather than going round robin.
Two customers each limited to 60 requests a minute can differ 36 times in load (60 short chats against 60 summaries of a 50,000-token contract), so limits count tokens. Output tokens are unknown at admission: limiters reserve the worst case, count output as it streams, or charge after the response and accept overshoot (all three on Gateways and routing, sections 5 and 6). An internal tool with a handful of users and a monthly budget alert needs no per-tenant token buckets.
Multi-tenancy is serving many customer organisations from shared infrastructure, which is cheap, while keeping each from hurting or seeing the others, which is the work.
| Model | How | Good for | Cost |
|---|---|---|---|
| Shared pool, fair queue | everyone in one pool; per-tenant token limits and a fair scheduler | many small tenants | tail latency moves with others' load |
| Shared pool, priority classes | requests carry a priority; under pressure low priority waits or is shed first | mixing paid and free, chat and batch | low classes can starve |
| Reserved capacity | a tenant buys a guaranteed rate; overflow goes to the shared pool | large customers with latency contracts | reserved capacity held even when idle |
| Dedicated pool | a tenant's own replicas | the largest or most regulated customers | whole replicas, idle at night |
Priority classes are as old as Google's load shedding: requests are tagged CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS ("the default for batch jobs, which can retry requests minutes or even hours later") or SHEDDABLE, and criticality propagates to the calls a request makes (SRE book, ch. 21, Handling Overload). The Kubernetes inference stack does the same for model traffic with an integer priority per objective (LLM serving in production, section 2), and reserved capacity is sold by providers as well as built: Anthropic's Priority Tier, now closed to new buyers, is on Gateways and routing, section 6.
Each step down the table buys predictability with idle hardware, and scoping caches per tenant lowers hit rates. A product with one customer (your own app) has no tenants to isolate: start with a shared pool and per-tenant limits, and add reserved or dedicated capacity only for a customer who pays for it.
Caches cost memory and a lookup on every request, and invalidation when a model or prompt version changes (put both in the key). Answers that depend on the user, on time or on live data must not come from a response or semantic cache; prefix caching is almost always worth it.
Timeouts, retries with backoff and jitter, circuit breakers and load shedding are taught on Reliability engineering; here is how they apply when the dependency is a model.
| Failure | How you see it | Response |
|---|---|---|
| Provider outage or 5xx | errors, timeouts | retry once with jitter, then fall back to another provider or region; open a circuit breaker so you stop paying timeouts |
| Provider overloaded (Anthropic 529) or your quota hit (429) | status codes, retry-after | honour retry-after; for 429 on quota, route elsewhere or shed; never retry a spend-cap 429 |
| Your own pool overloaded | queue depth, TTFT rising | admission control: a bounded queue and 429 or 503 with Retry-After beyond it; shed lowest priority first |
| Stream cut mid-reply | client disconnect, partial output | decide resume or restart; record partial usage; make the request idempotent so a retry does not bill twice |
| Malformed structured output | JSON or schema validation fails | validate, one retry with the error message, then a safe default. LinkedIn found its model produced invalid YAML about 10% of the time and cut errors "to ~0.01%" with a defensive parser (LinkedIn Engineering, 25 Apr 2024) |
| Context too long | provider error before generation | truncate or summarise history by a stated policy, or fall back to a long-context model (LiteLLM's context_window_fallbacks) |
| Guardrail trips | classifier score | safe refusal text (Guardrails) |
| Silent quality loss | only quality monitoring | roll back to the pinned previous version (section 3) |
Google's SRE book recommends client-side throttling too: each client tracks its requests and the backend's accepts, and keeps sending until "requests is K times as large as accepts", with "We generally prefer the 2x multiplier" (SRE book, ch. 21). Retry in one layer only: client, gateway and SDK each retrying three times multiplies load during an outage (the parent topic's 243-times case).
Degrading means serving "responses that are not as accurate as or that contain less data than normal responses, but that are easier to compute" (SRE book, ch. 21). For the chat assistant, best to worst:
max_tokensEach rung needs a trigger, an owner who may pull it, and a test that it works; shed batch first, then free tier, then paid. Real policies differ, and some choose not to degrade quality at all. GitHub Copilot users who exhaust premium requests "can still use Copilot with one of the included models", which "may be subject to rate limiting" (GitHub docs, Copilot requests); ChatGPT's free tier pauses: "GPT access pauses until the limit resets" (OpenAI help, free tier FAQ, read 2026-10-04); and Anthropic states "We never reduce model quality due to demand, time of day, or server load", degrading by queueing and limits instead. Tell users which rung they are on.
The worst outages of model services are often in ordinary infrastructure: OpenAI's 11 December 2024 outage (4 hours 22 minutes) came from a telemetry service that overloaded the Kubernetes control plane, which broke DNS-based service discovery (parent's Case files, "A monitoring tool overloaded the cluster brains"). The gateway, the autoscaler, the metrics pipeline and DNS are part of the model service's reliability.
The gateway should measure TTFT too, because the user's TTFT includes everything before the engine. Capacity signals: waiting and running requests, KV cache use, prefix cache hit rate (vLLM exports vllm:prefix_cache_queries and vllm:prefix_cache_hits in tokens, so hit rate = hits ÷ queries), tokens per second per GPU, preemptions. One usage event per request (tenant, feature, model and prompt versions, input, cached and output tokens, cost, latency, outcome), streamed to an analytics store, gives bills, per-team showback, cost per request and margin per tenant. Price cached and output tokens separately: they differ by a factor of 50 (Sonnet 5.5: $0.20 against $10 per million).
The metric names to emit come from OpenTelemetry's generative-AI semantic conventions (status "Development", so pin the version you instrument against); which ones exist, including the server-side time to first token and the token counters that replaced the old usage histogram, is on LLM observability, section 2.
Storing prompts and outputs for debugging and evaluation is storing customer data: decide retention, redaction and access up front. Per-tenant, per-model labels multiply metric series; keep high-cardinality fields in the usage events, not in metric labels.
An ML or LLM design interview keeps the parent topic's method and its timing for 45 minutes (scope 3 to 10 minutes, high-level design 10 to 15, deep dive 10 to 25, wrap-up 3 to 5, after Alex Xu) and swaps the middle for this page's sections in order: frame (1), data and skew (2), evaluation (3), serving and budget (4), monitoring (5), and for an LLM product the design ladder and cost (6, 7). What interviewers reward is quantified trade-offs, not component names. Full worked designs from requirements to bottlenecks are on System design case studies; its Design 5, an LLM gateway for a company, is the one to practise with after this page. Frontier-lab interviews go deeper into the engine (KV cache sizing, prefill and decode on separate GPUs, speculative decoding): Topic: inference-and-serving.
max_tokens by default. Where limits reserve max_tokens (OpenAI), it burns rate limit that is never used; everywhere it allows runaway cost. Set it per feature.A design lab for the decision a system designer owns: how much quality to trade for cost. Put the chat assistant's traffic through a small and a large model, caches and a fallback provider, and see what each request costs, how long it takes, how many fail, and how many get a worse or wrong answer, against a naive, healthy baseline: the same traffic sent to the large model, no caching, no outage. Every number is an expectation per request (no randomness). How a real gateway retries, cools down and falls back, recorded call by call, is on Gateways and routing.
Try: start from Naive, then Router + prefix cache: cost halves and a few percent of answers get worse (hard questions misrouted to the small model). Then Provider outage, no fallback against with fallback: the fallback turns 40% errors into slower, pricier answers. Then push the semantic cache's hit rate up and watch wrong answers climb.
How it is computed. Requests first meet the exact cache, then (if on) the semantic cache, then the router; the router sends easy requests to the small model with the stated accuracy, and its mistakes send hard requests to the small model (counted as worse answers) and easy ones to the large model (wasted money). Calls to the failing provider either error or go to the fallback, which starts with no cached prefix. Cost per request = (uncached input × input price + cached input × cache-read price + output × output price) ÷ 1,000,000. Monthly cost uses the average rate, half the peak (the parent topic's peak factor 2), over 730 hours. Mean TTFT and full time are request-weighted means.
Sources and labels. Prices per million tokens (input, output, cache read), from the knowledge base's shared price snapshot of 2026-10-01: Claude Sonnet 5.5 $2, $10, $0.20 and Claude 4.5 Haiku $1, $5, $0.10 (Anthropic pricing); GPT-6.1 Sol $2, $10, $0.10 and GPT-6 Luna $0.10, $0.50, $0.01 (OpenAI pricing). Self-hosted Llama 3.3 70B: $1.00 per million output tokens with input included, derived from 2,209 tokens/s per H100 at half load and $3.99 per GPU-hour (the parent topic's shared figures); prefix caching saves it time, not money. Cache writes are ignored (they add 25% on the first use of each prefix). Illustrative: every latency (time to first token 0.8 s large API, 0.4 s small API, 0.2 s self-hosted; 60, 120 and 69 tokens/s per user; 10 ms gateway, 20 ms router, 20 ms semantic lookup; a cached prefix removes up to 60% of TTFT), the traffic mix and every hit rate. Defaults: the chat assistant's 231.5 peak requests a second (1 million daily users × 10 messages ÷ 86,400 × 2). Checked against src/models.py by src/recompute.py and check_js.mjs (60 random settings and every preset, no differences).
Times are estimates for a careful first read. Links checked 2026-10-04.
A design lab: model tiers, router accuracy, caches and a fallback provider in front of the chat assistant's traffic, traded as cost against latency, errors and wrong answers. About 10 min to explore. When: after section 6.
The from-zero overview this page builds on: one request to the chat assistant as it grows from 1 user to 10 million. Its Step 6 is the general design method this page applies to models; its tabs Scale simulator (the whole system's capacity and cost), Numbers to know (sourced latency and throughput figures) and Case files (Character.AI, Anthropic's postmortem, Slack's autoscaling outage, OpenAI's December 2024 outage and 29 more) are referred to here by name. About 21 min, plus the tabs.
The service in front of the gateway: request lifecycle, the data layer, async and workers, shutdown (section 7); the API contract itself is Service APIs. About 27 min.
Delivery semantics and the async job pattern behind section 4's long jobs and batch lane. About 40 min.
Timeouts, retries, circuit breakers, SLOs and incidents: the general tools section 7's failure block applies to models. About 40 min.
Logs, metrics, traces and alerting: the service layer of section 5's monitoring table. About 39 min.
Load balancing, caching, queueing theory and load testing: how to size the pools of section 7. About 39 min.
Unit, property-based, data and model tests, and CI: the offline gate of section 3. About 46 min.
Worked designs from requirements to bottlenecks, including Design 5, an LLM gateway: the place to practise section 8. About 41 min.
Replication, partitioning, consistency, consensus. About 46 min.
Readable code, abstractions, refactoring in small tested steps, code review, library design. About 42 min.
Sibling pages are being rebuilt; reading times are on each page.
The owner of section 7's gateway, routing and limits: a LiteLLM gateway read from source and recorded call by call: deployment choice, retries, cooldowns and fallbacks, token rate limits and budgets, OpenRouter, learned routers. About 34 min.
The owner of section 7's replica routing and autoscaling: prefix-aware routing on real replicas, autoscaling signals and thresholds, cold starts. About 34 min.
The engine layer: continuous batching, PagedAttention, speculative decoding, prefill and decode disaggregation, KV-aware scheduling in depth. 34 min. When: after section 4.
Gates, golden sets, shadow deployments, canaries and A/B tests with their statistics: the depth behind section 3's rollout stages. Time on its page. When: before your first model rollout.
Feature stores and the point-in-time join, pipelines, experiment tracking and registries: the offline lane of the hero figure, inside. When: after section 2.
Workflows against agents, measured on one task: the fourth rung of section 6's ladder.
How engines keep and reuse a prefix: the mechanism under section 6's prompt-layout animation.
Input, tool and output rails at runtime: the gateway's "transform and guard" step.
How engines manage the KV cache, with a simulation.
Kubernetes, GPU scheduling and the platforms under the autoscalers. 29 min.
Embeddings, vector search and retrieval caches. 21 min.
Adapters, including many per-tenant adapters on one base model.
How to score quality, offline and in production.
The best single book on building products on foundation models; chapter 10 (architecture: context, guardrails, router and gateway, caches, agents, monitoring, feedback) is this page's subject. About 13 h for the book, 1 h 30 for chapter 10.
The free blog post the chapter grew from. About 40 min.
Free; the classic ML interview framing (project setup, data pipeline, modelling, serving). About 1 h 30.
Worked ML interview cases in a standard structure; pair with Huyen. About 7 h 30.
Why queue size and batch size beat GPU and CPU signals, with thresholds to start from. About 20 min.
The retry discipline every gateway needs. About 25 min.
Criticality, load shedding, degraded responses, client-side throttling; ch. 4 on SLOs alongside. About 1 h for the two chapters.
What the open-source serving and routing layer looks like in 2026: routers, autoscaling recipes, Helm charts. About 1 h for the core pages.
A real gateway's configuration surface, readable in an afternoon. About 45 min.
How serving bugs degrade quality without errors, and what monitoring caught them. About 15 min.
Why ML systems are mostly glue, feedback loops, prediction bias and action limits (sections 1 and 5). About 40 min.
43 rules from Google: metrics before models, training-serving skew, the gaps of Rule #37 (sections 1 to 3). About 1 h.
src/ in the knowledge base repository (sh src/build.sh). Every number on this page is either linked to its source, derived with its formula shown, or labelled illustrative. The page's models (the Cost-quality lab and the prefix-cache animation) are checked against a Python copy, src/models.py, by src/recompute.py.