Serving Models at Scale
local graph
Chapter 28 — Serving Models at Scale
Section titled “Chapter 28 — Serving Models at Scale”Serving a model to one user is the loop of Chapter 27; serving it to thousands at once, cheaply, is a systems discipline that has matured rapidly. The central tension is throughput versus latency, and the central obstacle is the KV cache — its memory limits how many requests fit on a GPU, and its unpredictable size makes that memory hard to manage. The innovations that solved this, continuous batching and paged attention, are why modern inference servers achieve many times the throughput of naive implementations. This chapter explains them.
28.1 The Economics of Serving
Section titled “28.1 The Economics of Serving”Because decode is memory-bound (Chapter 27), a single request leaves most of the GPU’s arithmetic idle — reading the weights to generate one token wastes the hardware. The fix is batching: process many requests together so one read of the weights serves them all, turning wasted compute into throughput. Serving is measured by three numbers: time to first token (TTFT, essentially prefill latency), time per output token (TPOT, decode speed), and aggregate throughput (tokens per second across all requests). The art is maximizing throughput without letting any individual request’s latency suffer.
28.2 Continuous Batching
Section titled “28.2 Continuous Batching”Naive (static) batching groups a fixed set of requests and runs them together until all finish — but requests have wildly different lengths, so the whole batch waits on the slowest, and the GPU empties as short requests complete. Continuous batching fixes this by managing the batch at the granularity of a single decode step: finished requests are evicted and new ones admitted between steps, so the batch stays full and the GPU never idles waiting for stragglers. This one change, the core of modern serving, can multiply throughput several-fold.
28.3 Paged Attention
Section titled “28.3 Paged Attention”Continuous batching needs many requests’ KV caches resident a once, and here a subtle problem bites: a request’s cache grows token by token to an unknown final length, so reserving a contiguous block for its maximum possible size wastes enormous memory, while reserving too little means reallocating mid-generation. Paged attention, introduced by vLLM, borrows the operating system’s solution to exactly this problem — virtual memory. The KV cache is split into fixed-size blocks (pages) that need not be contiguous in physical memory; a per-sequence block table maps the logical cache to scattered physical pages, allocated on demand as the sequence grows. Fragmentation nearly vanishes, far more requests fit, and throughput rises again. Figure 28.1 shows the mapping.
Figure 28.1. Paged attention. A sequence’s logically contiguous KV cache is mapped, block by block, to non-contiguous physical pages via a block table — exactly like virtual memory. Pages are allocated only as the sequence grows, so memory is not wasted reserving for the maximum length.
28.4 The Serving Stack
Section titled “28.4 The Serving Stack”Production inference engines combine these with several more optimizations. Prefix caching reuses the KV cache of a shared prefix — a common system prompt, or a document queried many times — so its prefill is computed once and shared across requests. Quantization (Chapter 26) shrinks the weights and cache, fitting more concurrent requests per GPU. And increasingly, systems disaggregate the compute-bound prefill and memory-bound decode phases onto separate hardware pools so each can be optimized independently. Table 28.1 collects the techniques; together they define the modern serving stack.
| Technique | What it does | Benefit |
|---|---|---|
| Continuous batching | admit/evict requests between decode steps | GPU stays full; higher throughput |
| Paged attention | KV cache in non-contiguous pages | less waste; more concurrent requests |
| Prefix caching | reuse KV for shared prefixes | skip redundant prefill |
| Quantization | fewer bits for weights and cache | more requests per GPU |
| Prefill/decode disaggregation | separate pools per phase | optimize each phase independently |
Table 28.1 — Inference-serving optimizations
The reward for all this machinery is that it is invisible to use. Serving a model with everything in this chapter — paged attention, continuous batching, a quantized model — is a few lines with vLLM, the most widely used open server:
from vllm import LLM, SamplingParams
# loads the model; paged attention + batching are automaticllm = LLM(model="your-model", quantization="awq") # 4-bitparams = SamplingParams(temperature=0.7, max_tokens=256)
# many prompts are scheduled and continuously batched for yououtputs = llm.generate(["Explain MLA.", "Write a haiku."], params)for o in outputs: print(o.outputs[0].text)
# or an OpenAI-compatible HTTP server, one command:# vllm serve your-model --quantization awqPython — vllm-project/vllm: offline serving (reproduced, Apache 2.0)
Nothing in that snippet mentions blocks, bubbles, or page tables — yet every optimization of this chapter is running underneath. LLM(…) allocates the paged KV cache and starts the continuous-batching scheduler; passing a list to generate lets that scheduler pack the prompts together and admit and evict them per step; and quantization=“awq” loads the 4-bit weights of Chapter 26 so more requests fit per GPU. The vllm serve command exposes the same engine as an OpenAI-compatible endpoint, which is how most open models are actually deployed in production. SGLang offers similar performance with especially fast structured generation and prefix caching; TensorRT-LLM is NVIDIA’s most optimized engine; and FlashMLA supplies the MLA decode kernels that make DeepSeek models fast to serve. These systems are where the theory of this part becomes deployed reality — and, as the code shows, where it becomes genuinely easy to use.
The model can now be served efficiently to many users. The final question of Part VII is the hardest to answer honestly: how good is it, really? Benchmarks are easy to run and easy to misinterpret, and the gap between a high leaderboard score and a genuinely capable model is where the next chapter lives.
28.5 Worked Example: Continuous Batching
Section titled “28.5 Worked Example: Continuous Batching”Static batching wastes GPU time: a batch runs only as fast as its slowest member, and finished requests idle until the rest complete. Continuous batching (Chapter 28) admits and retires requests every step, keeping the GPU full:
while running or queue: while queue and len(running) < max_batch: running.append(queue.pop()) # admit new requests anytime logits = model.decode_step(running) # one step for the whole batch for req in list(running): req.append(sample(logits[req.id])) if req.done: running.remove(req) # ...freeing a slot at oncePython — continuous batching: admit and retire requests every step
28.6 Prefix Caching for Shared Prompts
Section titled “28.6 Prefix Caching for Shared Prompts”Real workloads are not independent. Thousands of requests to an agent share the same 2,000-token system prompt; every user of a few-shot template shares its examples. Prefilling that common prefix afresh for each request (Section 27.1) is pure waste. Prefix caching stores the KV of frequently seen prefixes and reuses it, so only each request’s unique suffix is actually prefilled:
key = hash_tokens(prompt[:prefix_len]) # identify the shared prefixif key in kv_store: past = kv_store[key] # skip prefill of the prefixelse: past = prefill(prompt[:prefix_len]) kv_store[key] = pastoutput = decode(prompt[prefix_len:], past) # prefill only the suffixPython — serving/prefix_cache.py: reuse KV for shared prefixes
The savings scale with how much structure the workload shares. An agent serving a 2,000-token system prompt to thousands of requests pays that prefill once instead of thousands of times; a chat application reuses the entire conversation history across a multi-turn exchange. Production engines — vLLM and SGLang — perform this automatically (it is called automatic prefix caching), built directly on top of the paged KV blocks of Section 28.3, which is what makes the shared blocks safe to reference from many requests at once.
28.7 Worked Example: The Throughput–Latency Trade-off
Section titled “28.7 Worked Example: The Throughput–Latency Trade-off”Serving lives on a tension between two metrics that pull in opposite directions. Throughput — total tokens per second across all users — rises with batch size, because the GPU’s matrix units are far better utilized by a wide batch (Section 28.2). Latency — how fast a single user’s tokens arrive — worsens with batch size, because more sequences share the same fixed compute each step. The operator’s job is to find the largest batch that still meets a latency target:
| Batch size | Per-user tokens/s | Total tokens/s | Cost/token |
|---|---|---|---|
| 1 | ~90 | ~90 | highest |
| 16 | ~70 | ~1,120 | low |
| 64 | ~40 | ~2,560 | lowest |
Table 28.1 — Illustrative batch-size trade-off on one GPU
Read across the table: moving from batch 1 to batch 64 multiplies total throughput roughly thirty-fold — collapsing the cost per token — while each individual user’s speed falls by half. If the service-level objective is “at least 30 tokens per second per user,” batch 64 is acceptable and is far cheaper to operate; if users demand 80, the operator must run a smaller batch and pay more per token. Continuous batching (Section 28.2) softens the dilemma by keeping the batch full as requests come and go, but the fundamental trade between a single user’s latency and the fleet’s throughput never disappears — it is the central economic fact of serving.
There is no free batch size Bigger batches always trade per-user latency for fleet throughput. The “right” batch is whatever is largest while still meeting your latency SLO — a business decisi wearing an engineering costume.
28.8 Disaggregated Prefill and Decode
Section titled “28.8 Disaggregated Prefill and Decode”The two phases of inference have opposite hardware appetites. Prefill — processing the prompt in parallel — is compute-bound: it saturates the matrix units with one big batched operation. Decode — generating tokens one at a time (Section 10.6) — is memory-bandwidth- bound: each step does little arithmetic but must stream the entire KV cache and weights. Running both on the same GPU forces an awkward compromise, since a configuration tuned for one starves the other.
Disaggregated serving, an increasingly common frontier technique, splits them onto separate GPU pools. A prefill pool, optimized for throughput, ingests prompts and produces the initial KV cache; that cache is then transferred to a decode pool, optimized for low-latency token generation, which streams the response. Each pool runs at a batch size and configuration suited to its phase, and the two scale independently — a workload heavy on long prompts can add prefill capacity without touching decode, and vice versa. The cost is the KV-cache transfer between pools and the added system complexity, which is why disaggregation appears first in large, high-traffic deployments where the efficiency gain repays it. It is the serving-side echo of a theme running through this book: prefill and decode are different problems, and at scale it pays to stop pretending one machine should do both.
Two phases, two machines Prefill is compute-bound, decode is bandwidth-bound. Disaggregated serving runs each on hardware tuned for it and scales them separately — trading a KV-cache transfer for the ability to stop compromising between two opposite workloads.
28.9 Autoscaling and Load Balancing Across Replicas
Section titled “28.9 Autoscaling and Load Balancing Across Replicas”A single serving replica has a throughput ceiling (Section 28.7), so any real service runs many replicas behind a load balancer and adjusts their number to match demand. Doing this well for language models has wrinkles that ordinary web services do not face, and ignoring them wastes either money or latency.
The first wrinkle is cold start. Spinning up a new replica means loading a multi-gigabyte (or multi-hundred-gigabyte) model onto fresh GPUs, which takes minutes — far too slow to react to a traffic spike after it arrives. Production autoscalers therefore scale ahead of demand, using queue depth and latency trends as leading signals rather than waiting for saturation. The second wrinkle is routing. A naive round-robin balancer spreads load evenly but ignores the prefix cache (Section 28.6); routing requests that share a long system prompt to the same replica — sticky routing on the prefix — lets that replica reuse its cached KV and serve them far more cheaply. The art of serving at scale is thus not only choosing a batch size per replica but orchestrating the fleet: scaling on the right leading indicators, and routing to exploit the caching that makes each replica efficient. These fleet-level concerns are exactly what the Kubernetes machinery of Section 35.6 exists to automate.
Scale early, route with memory Model cold starts are too slow to react to spikes, so autoscale ahead of demand; and route shared-prefix requests to the same replica so the prefix cache pays off. Fleet efficiency is as much routing as batch size.
28.10 Chunked Prefill
Section titled “28.10 Chunked Prefill”The two-phase nature of inference (Section 28.8) creates a scheduling hazard in a mixed workload. A long prompt’s prefill is one large, compute-heavy operation, and if a serving engine runs it as a single indivisible step, it can monopolize the GPU — stalling the token-by-token decode of every other in-flight request and spiking their latency. One enormous prompt arriving can momentarily freeze everyone else’s generation. Chunked prefill is the remedy.
The idea is to split a long prompt’s prefill into smaller chunks and process them across several scheduling steps, interleaved with the ongoing decode work of other requests, rather than all at once. Each step does a manageable slice of the big prefill plus a round of everyone’s decode, so the long prompt makes steady progress without ever blocking the fleet. This smooths the latency that other users experience — no single request can seize the GPU for a long uninterrupted stretch — at the cost of a little scheduling complexity and a marginal overhead from splitting the prefill. It is the fine-grained, single-engine complement to the coarse-grained disaggregation of Section 28.8: where disaggregation separates prefill and decode onto different hardware, chunked prefill interleaves them on the same hardware by slicing the prefill small enough to share. Both exist for the same reason — that prefill and decode are different beasts, and letting a big prefill run unchecked is unfair to the many small decodes waiting behind it.
Slice the big prefill so decodes keep flowing A long prompt’s prefill can monopolize a GPU and stall everyone’s decode. Chunked prefill splits it across steps, interleaved with ongoing generation, smoothing latency — the single-engine counterpart to prefill/decode disaggregation.