Notes
All notes

Serving LLMs at Scale (AI Engg #7)

Your prototype answered in two seconds. You demo it to fifty people and it is magic. Then you launch to five thousand, and within an hour p95 latency is eleven seconds, the GPU is pinned at 100%, and the bill has tripled. Nothing about your prompt or retrieval changed. What changed is inference serving — the part of AI engineering that decides whether a model call costs fractions of a cent or dollars, and whether it returns in 300ms or 30 seconds.

The previous six chapters treated the model as an API you call. This chapter opens the serving layer: how a forward pass actually spends time and memory, why the KV cache dominates everything, how quantization and batching change the cost curve, how prefix caching makes repeated work free, and how to measure and scale a real endpoint. If you ever self-host, choose a provider, or debug latency, this is the material.

Two phases: prefill and decode

A single LLM request is not one operation; it is two with opposite bottlenecks.

Prefill processes the entire input prompt at once. Every token attends to every earlier token, and the whole prompt is one big matrix multiply. This phase is compute-bound: the GPUs are busy doing math, and the time is roughly proportional to prompt tokens. It is highly parallel, which is why a long prompt still returns its first token in a few hundred milliseconds.

Decode generates the output one token at a time. Each new token attends to all previous ones, but the arithmetic per token is tiny — a handful of matrix-vector products against a large set of weights. This phase is memory-bandwidth-bound: the GPU spends its time moving weights and cache from HBM to the compute units, not multiplying. That is why output length, not input length, usually dominates latency and why batching is the great lever of decode.

\[ \text{latency} \approx \underbrace{\text{TTFT}}_{\text{prefill} + \text{queue}} + \underbrace{(\text{output\_tokens} - 1) \times \text{TPOT}}_{\text{decode}} \]

This split is the single most useful mental model for serving. Optimizing prefill (FP8, chunked prefill, prefix cache) attacks TTFT. Optimizing decode (quantization, batching, speculative decoding) attacks TPOT and throughput.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum height=0.7cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \draw[->, thick, black!45] (0,0) -- (7.6,0);
  \fill[orange!45] (0.1,0.1) rectangle (2.2,0.7);
  \node[font=\small] at (1.15,0.4) {prefill (prompt)};
  \foreach \x in {2.5,3.0,3.5,4.0,4.5,5.0,5.5,6.0,6.5} {
    \fill[blue!30] (\x,0.1) rectangle (\x+0.28,0.7);
  }
  \node[font=\small] at (4.5,0.95) {decode: one token at a time};
  \node[font=\scriptsize\ttfamily] at (1.15,-0.25) {TTFT};
  \node[font=\scriptsize\ttfamily] at (3.6,-0.25) {TPOT};
  \draw[a, <->] (2.5,-0.5) -- (3.05,-0.5);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.6,-1.0) {compute-bound, parallel \hspace{1.6cm} memory-bound, sequential};
\end{tikzpicture}

There is a deeper reason for the asymmetry. A GPU can do far more arithmetic per second than it can move bytes from memory. Prefill has high arithmetic intensity (many FLOPs per byte loaded), so it is FLOP-limited. Decode has arithmetic intensity near 1 FLOP/byte, so it is bandwidth-limited. Every serving optimization is an attempt to move one of those two limits.

The KV cache: the real memory hog

During attention, each token produces a Key and a Value vector at every layer. To generate token \(t\), the model needs the K and V of all previous tokens. Recomputing them every step would be quadratic and absurd, so they are stored: the KV cache.

The cache is what makes long conversations expensive. Its size is deterministic:

\[ \text{KV bytes} = 2 \times n_{\text{layers}} \times n_{\text{kv heads}} \times d_{\text{head}} \times L_{\text{seq}} \times B \times b_{\text{bytes}} \]

where the leading \(2\) is for K and V, \(L_{\text{seq}}\) is the sequence length, \(B\) is the batch (concurrent sequences), and \(b_{\text{bytes}}\) is bytes per element (2 for FP16). Worked example, Llama-3-8B (32 layers, 8 KV heads with GQA, head_dim 128, FP16):

The lesson: weights are fixed; KV grows with context × concurrency. This is why batch size is limited by KV memory, not by weight memory, and why long-context models are so expensive to serve. It is also why GQA/MQA (Grouped/Multi-Query Attention) exist: they reduce \(n_{\text{kv heads}}\) (from 32 to 8 above), cutting KV memory 4× at minimal quality cost. When you pick a model for serving, check its KV-head count, not just its parameter count.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  w/.style={draw, thick, fill=green!25},
  k/.style={draw, thick, fill=orange!30},
  bar/.style={draw, thick, fill=blue!18},
  a/.style={->, thick}]
  \fill[w] (0,0) rectangle (2.0,0.7); \draw[thick] (0,0) rectangle (2.0,0.7);
  \node[font=\small] at (1.0,0.35) {weights ~16GB};
  \node[font=\rmfamily\small, anchor=north] at (1.0,-0.05) {fixed};
  \foreach \i in {1,2,3,4} {
    \fill[k] (2.5+\i*0.75,0) rectangle (3.1+\i*0.75,0.7); \draw[thick] (2.5+\i*0.75,0) rectangle (3.1+\i*0.75,0.7);
  }
  \node[font=\small] at (5.0,0.35) {KV: 1GB $\times$ 4 seqs};
  \node[font=\rmfamily\small, anchor=north] at (5.0,-0.05) {grows with concurrency $\times$ context};
  \node[font=\rmfamily\small, text=black!60, anchor=west] at (2.4,0.9) {you run out of KV long before you run out of weights};
\end{tikzpicture}

PagedAttention, popularized by vLLM, borrowed the operating-system idea of paging: store the KV cache in fixed-size blocks instead of one contiguous buffer per sequence. This removes fragmentation (no need to pre-reserve max-length for every request) and lets sequences share blocks — which is exactly what makes prefix caching possible. If you self-host, this is the feature that most changes your throughput.

Quantization: fewer bits, more speed

Quantization reduces the numerical precision of weights and/or the KV cache. Because decode is memory-bandwidth-bound, smaller numbers decode faster and fit more concurrency — the effect is not marginal.

Format Bits ~Size (8B model) Notes
FP16 / BF16 16 ~16 GB baseline quality
FP8 8 ~8 GB strong on Hopper/Blackwell; good default on new GPUs
INT8 (SmoothQuant) 8 ~8 GB near-lossless with calibration
INT4 (GPTQ, AWQ) 4 ~4–5 GB best quality/size for local serving
GGUF Q4_K_M ~4.5 ~4.5 GB llama.cpp/Ollama default
GGUF Q8_0 8 ~8 GB higher quality, more memory

Two axes matter and are often confused:

Quantization is not free. It can hurt reasoning and long-tail accuracy, and it interacts with fine-tunes. Always sweep the quant on your own goldens (Chapter 15) before concluding “the open model is worse.” A common production stack is FP8 weights for prefill-heavy traffic and INT4 only when memory is the binding constraint.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  bar/.style={draw, thick}]
  \fill[red!20] (0,0) rectangle (6.4,0.55); \draw[bar] (0,0) rectangle (6.4,0.55);
  \fill[orange!35] (0,-0.7) rectangle (3.2,0.0-0.15); \draw[bar] (0,-0.7) rectangle (3.2,-0.15);
  \fill[green!30] (0,-1.4) rectangle (1.6,-0.85); \draw[bar] (0,-1.4) rectangle (1.6,-0.85);
  \node[font=\small, anchor=west] at (6.5,-0.28) {FP16};
  \node[font=\small, anchor=west] at (3.3,-0.43) {INT8/FP8};
  \node[font=\small, anchor=west] at (1.7,-1.13) {INT4/Q4};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (3.0,-1.6) {same model, memory footprint by precision};
\end{tikzpicture}

Batching: the throughput engine

A single decode step uses a tiny fraction of the GPU’s compute; the GPU waits on memory. Batching amortizes the weight reads across several sequences: loading the weights once serves many requests, so throughput rises dramatically while per-token latency barely moves. This is the highest-leverage serving change there is.

The trade curve is fundamental: as batch size grows, throughput rises and per-token latency creeps up. You pick an operating point based on whether the product values time-to-first-token, time-per-token, or cost.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, fill=cyan!35, minimum height=0.5cm},
  a/.style={->, thick}]
  \draw[->, black!45] (0,0) -- (8.2,0);
  \draw[->, black!45] (0,0) -- (0,2.3);
  \node[font=\small, rotate=90, anchor=south] at (-0.35,1.2) {requests};
  \fill[cyan!35] (0.2,0.2) rectangle (3.6,0.6); \draw (0.2,0.2) rectangle (3.6,0.6); \node[font=\scriptsize] at (1.9,0.4) {R1};
  \fill[cyan!35] (0.6,0.7) rectangle (4.6,1.1); \draw (0.6,0.7) rectangle (4.6,1.1); \node[font=\scriptsize] at (2.6,0.9) {R2};
  \fill[cyan!35] (1.2,1.2) rectangle (5.6,1.6); \draw (1.2,1.2) rectangle (5.6,1.6); \node[font=\scriptsize] at (3.4,1.4) {R3};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (4.0,-0.15) {continuous batching: a new sequence slots in the moment one finishes};
\end{tikzpicture}

Prefix caching: pay once for the shared part

Most production traffic shares a very long prefix: the system prompt, tool schemas, few-shot examples, or the same retrieved document set. Recomputing the prefill for that shared prefix on every request is pure waste. Prefix caching stores the KV blocks for a prefix and reuses them when the next request starts with the same tokens.

Two flavors:

The engineering rule from Chapter 4 now has a second payoff: stable content first, variable content last. Put the system prompt, tool schemas, and long shared documents at the front; put the user’s message and the freshest retrieved chunk at the end. Then a cache hit skips the most expensive part of prefill, cutting both TTFT and cost. Track the cache hit rate as a first-class metric — if it is low, your prompt ordering is leaking variation into the prefix.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum height=0.7cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=green!25, minimum width=2.6cm] (p) at (0,0) {shared prefix\\(system + docs)};
  \node[b, fill=orange!25, minimum width=1.2cm] (v1) at (2.0,0.8) {user A};
  \node[b, fill=orange!25, minimum width=1.2cm] (v2) at (2.0,0) {user B};
  \node[b, fill=orange!25, minimum width=1.2cm] (v3) at (2.0,-0.8) {user C};
  \draw[a] (p.east) -- (v1.west); \draw[a] (p.east) -- (v2.west); \draw[a] (p.east) -- (v3.west);
  \node[font=\rmfamily\small, text=black!60, anchor=west] at (2.7,1.4) {prefix KV computed once, reused};
\end{tikzpicture}

Other decode accelerators

You rarely implement these. You choose an engine that has them and tune the knobs.

Serving engines: what to run

Engine Best for Notes
vLLM general production OSS PagedAttention, continuous batching, APC, huge model support
SGLang structured/agent workloads RadixAttention prefix cache, fast structured output
TGI Hugging Face ecosystem production server, good observability
TensorRT-LLM max performance on NVIDIA most tuning, FP8/FP4, steeper setup
llama.cpp / Ollama local, CPU/edge, personal GGUF quants, easy, not for high concurrency
LMDeploy throughput on NVIDIA strong paged KV + quantization

The 2026 default for self-hosting is vLLM or SGLang. For an OpenAI-compatible endpoint, vLLM exposes one directly, so your application code from Chapter 6 does not change at all.

# serve an open model with continuous batching + prefix caching (OpenAI-compatible)
vllm serve Qwen/Qwen2.5-7B-Instruct \
  --port 8000 \
  --max-model-len 8192 \
  --gpu-memory-utilization 0.90 \
  --enable-prefix-caching
# then point the Chapter 6 client at http://localhost:8000/v1
from openai import OpenAI
c = OpenAI(base_url="http://localhost:8000/v1", api_key="vllm")
r = c.chat.completions.create(model="Qwen/Qwen2.5-7B-Instruct",
    messages=[{"role": "user", "content": "Explain KV cache in two lines."}])
print(r.choices[0].message.content)

For managed serving, the same model runs on Fireworks, Together, Bedrock, Vertex, or a provider’s dedicated endpoints. Serverless is pay-per-token and great for spiky traffic; dedicated GPUs are cheaper at steady high volume and let you pin exact weights and quant. The decision is the same as Chapter 5’s router logic, one level down.

Measuring and scaling: the metrics that matter

Serving is an operations discipline. Track these, not just “it works”:

Metric Meaning Watch because
TTFT (p50/p95) time to first token user-perceived responsiveness
TPOT / ITL (p50/p95) per-token decode time streaming smoothness
Throughput tokens/s, requests/s per GPU cost efficiency
Goodput requests/s meeting an SLO throughput that actually counts
Queue depth / wait requests waiting first sign of overload
KV cache utilization fraction of KV memory used the true capacity limit
Cache hit rate prefix reuse direct cost/latency savings
GPU utilization SM + memory bandwidth find the bound

Two formulas keep capacity planning honest. Little’s Law: for a stable system, \(\text{concurrency} = \text{arrival rate} \times \text{latency}\). If you serve 20 requests/s at 5s latency, you need 100 in flight — and if each needs 1 GiB of KV, 100 GiB of KV memory. Goodput is the real target: the fraction of requests meeting your latency SLO. You can always raise raw throughput by admitting more batch; goodput tells you when you have gone too far and blown the tail.

Autoscale on queue depth or p95 latency, never on CPU. GPU-bound services show low CPU right up until they fall over.

# back-of-envelope: will this model fit, and how many concurrent sequences?
def capacity(n_layers, n_kv_heads, head_dim, seq_len, bytes_per=2):
    per_seq = 2 * n_layers * n_kv_heads * head_dim * seq_len * bytes_per
    return per_seq  # bytes per sequence
kv = capacity(32, 8, 128, 8192)                 # Llama-3-8B @ 8k
print(kv / 2**30, "GiB per sequence")           # ~1.0
gpu_kv = 80 * 2**30 - 16 * 2**30                # 80GB card, ~16GB weights
print(int(gpu_kv // kv), "concurrent sequences (rough)")

The decision playbook

Pitfalls

QQuestionSelf-check

Why is decode memory-bound while prefill is compute-bound? What does the KV cache size depend on, and which two optimizations directly reduce it?

ASolution

Prefill processes the whole prompt in parallel, so it does many FLOPs per byte loaded and is compute-bound. Decode does one tiny token at a time against the full weights, so it is dominated by moving bytes from HBM — memory-bound. KV size grows with layers × KV-heads × head_dim × sequence length × batch × precision. Grouped/Multi-Query Attention (fewer KV heads) and KV-cache quantization (fewer bytes per element) reduce it directly; batching raises throughput but increases total KV.

Next: Embeddings (AI Engg #8) — the representation that makes search by meaning possible.