CONTENTS
CHAPTER 3

Inference, the machine under every decision

7 MIN READ

You don't need to build an inference server to design AI systems, any more than you need to write a database engine to design a web app. But you do need to understand why the database is slow when you scan a table, and you need the same intuition for models. Every latency and cost number in your design comes from what happens on the GPU. This chapter gives you that intuition.

Two phases: reading and writing

When you send a request to an LLM, the server does two very different kinds of work.

Prefill processes your whole prompt. All the input tokens are known up front, so the GPU handles them in parallel, in large matrix multiplications. This is the GPU's favourite kind of work, and it's limited by raw compute. Prefill determines most of your time to first token (TTFT), along with queueing and network time.

Decode generates the output, one token at a time. Each new token depends on the one before, so this phase is sequential. For each token, the server has to read the model's weights from memory and do a comparatively tiny amount of math with them. Decode is limited by memory bandwidth, how fast bytes move from GPU memory to the compute units, and it determines your time per output token (TPOT, also called inter-token latency or ITL).

As Databricks puts it in its inference performance guide: generating the first token is typically compute-bound, while subsequent decoding is memory-bound.

Concept deep dive: why decode is memory-bound

This idea explains most of inference engineering, so it's worth building carefully.

Think of a kitchen. The chef (the GPU's compute units) is extremely fast. The ingredients (the model weights) are in a pantry down the hall (GPU high-bandwidth memory). To make one dish (one output token), the chef has to fetch every ingredient in the pantry, use a pinch of each, and put it back.

For a model with 70 billion parameters stored at 2 bytes each, that's 140 GB of "ingredients" per token. A high-end GPU's memory bandwidth is on the order of a few terabytes per second. So for a single request, just moving the weights caps you at a few tens of tokens per second, no matter how fast the chef is. The chef spends most of the time waiting for the walk to the pantry.

Now the trick: what if the chef cooks many dishes at once? Fetch each ingredient once, use a pinch for each of 64 dishes, put it back. The walk costs the same; you get 64 dishes. That's batching: run many users' decode steps together so each read of the weights does more useful work. It's why inference providers can sell tokens cheaply: their GPUs serve hundreds of requests in one batch.

Where the analogy breaks: each request also has its own private memory (the KV cache, next section) that must be read every step, and that doesn't get shared across the batch. As batches and contexts grow, reading those caches becomes the new bottleneck.

The formal version of this idea is arithmetic intensity: the number of math operations per byte moved. Prefill has high intensity (many tokens reuse each weight), so it's compute-bound. Single-request decode has very low intensity, so it's memory-bound. Batching raises it.

The KV cache

Inside a transformer, each token at each layer produces two vectors called a key and a value, which later tokens attend to. When generating token 1,001, the model needs the keys and values of tokens 1 to 1,000. Recomputing them every step would be wasteful, so the server stores them: the KV cache.

Its size per sequence is:

KV bytes=2⋅L⋅H⋅d⋅b⋅n\text{KV bytes} = 2 \cdot L \cdot H \cdot d \cdot b \cdot n

Here LL is the number of layers, HH the number of key-value heads, dd the dimension of each head, bb the bytes per stored value and nn the number of tokens. The 2 is for keys and values. Plug in a plausible large model: 80 layers, 8 KV heads, head dimension 128, 2 bytes per value. That's 2×80×8×128×2=327,6802 \times 80 \times 8 \times 128 \times 2 = 327{,}680 bytes, about 0.33 MB per token. A 100,000-token context therefore needs about 33 GB of KV cache, for one request.

This has direct design consequences:

  • Long contexts are expensive to serve, not just to bill. They consume GPU memory that could hold other users' requests, which lowers batch size and throughput.
  • Reusing a cached prefix saves real work. If ten thousand requests start with the same 5,000-token system prompt, the server can compute that prefix's KV cache once and reuse it. That's the physical reason providers can discount cached input tokens so steeply (Chapter 12).

How servers squeeze more out of the GPU

You'll meet these terms in provider docs and engineering blogs. You don't need to implement them, but you should know what each buys you.

Continuous batching. Old servers batched requests together and waited for the whole batch to finish, so a short reply waited for the longest one. The Orca paper (Yu et al., OSDI 2022) introduced iteration-level scheduling: the batch is re-formed at every decode step, so finished requests leave and new ones join immediately. It reported up to 36.9× the throughput of FasterTransformer on GPT-3 175B at the same latency. Every modern server does this.

PagedAttention. The vLLM team (Kwon et al., SOSP 2023) noticed that KV caches were stored in big contiguous chunks reserved up front, wasting most of the memory. Their blog estimated that existing systems wasted 60–80% of KV cache memory to fragmentation and over-reservation. PagedAttention borrows virtual memory paging from operating systems: the cache lives in small fixed-size blocks that can sit anywhere, with a table mapping them. Waste dropped to under 4%, and the paper reports 2–4× throughput at the same latency.

Prefix caching. SGLang's RadixAttention (Zheng et al., NeurIPS 2024) keeps KV caches of past prompts in a tree keyed by token prefix, so any new request sharing a prefix reuses it. This is the server-side machinery behind prompt caching.

Speculative decoding. Since decode is memory-bound, the GPU has spare compute. Speculative decoding (Leviathan et al., 2022; Chen et al., 2023) uses a small, fast draft model to guess several tokens ahead, then has the big model check all the guesses in one parallel pass, which costs about the same as generating one token. Accepted guesses are free speedup. Done correctly, the output distribution is identical to the big model's. Reported speedups were 2–3×.

Quantization. Store weights in fewer bits (8 or 4 instead of 16). Fewer bytes to move per token means faster decode and more room for KV cache. Methods like GPTQ and AWQ do this after training with modest quality loss. The trade-off is quality, so evaluate it on your task.

FlashAttention. An attention algorithm (Dao et al., 2022) that computes exactly the same result while moving far less data between GPU memory tiers. It's now standard; you benefit from it without doing anything.

Disaggregated prefill and decode. Since the two phases want different hardware behaviour, some systems run them on separate GPU pools and hand the KV cache across. DistServe (OSDI 2024) and Splitwise (ISCA 2024) showed large gains. DistServe also popularized the metric goodput: the maximum request rate at which requests still meet both TTFT and TPOT targets. Throughput that breaks your latency targets isn't worth anything.

The metrics you'll design against

Metric Meaning What drives it
TTFT Time to first token Queueing, prompt length (prefill), network, cache hits
TPOT / ITL Time between output tokens Model size, quantization, batch size, hardware
End-to-end latency TTFT + TPOT × (output tokens − 1) Both of the above plus output length
Throughput Tokens or requests per second across all users Batching efficiency
Goodput Requests per second that meet latency targets The trade-off between the above

Latency targets should be stated as percentiles (p50, p95, p99), not averages. A system with a fine average and a terrible p99 feels broken to one user in a hundred.

What this means for your designs

You'll mostly use hosted APIs, so here's the practical translation:

  1. Output length is your biggest latency lever. Asking for a 100-token answer instead of 800 cuts most of the wait. Ask for concise formats, and stream.
  2. Long prompts raise TTFT and cost. Keep the stable part of the prompt at the start so it can be cached, and don't stuff the context "just in case."
  3. Smaller models decode faster. For latency-sensitive steps (classification, routing, autocomplete), a small model is often the right call even if a big one is a bit smarter.
  4. Batch what isn't interactive. If no one is waiting, use batch APIs (both Anthropic and OpenAI discount batch jobs by 50%).
  5. Self-hosting is a throughput game. If you run your own models, the economics depend on keeping batches full. A GPU serving one user at a time is very expensive per token.

Common confusion: "Reasoning models are slow because they think hard." They're slow mostly because they generate many tokens (the reasoning) before the answer, and each token pays the decode cost. A reasoning budget is an output-length budget.

Key takeaways

  • Prefill reads your prompt in parallel and is compute-bound; it sets TTFT. Decode writes one token at a time and is memory-bound; it sets TPOT.
  • Batching amortizes the cost of reading the weights. It's why tokens are cheap at scale.
  • The KV cache grows with context length and eats GPU memory; reusing cached prefixes is real saved work.
  • Continuous batching, PagedAttention, prefix caching, speculative decoding and quantization are the main server-side wins.
  • Design against TTFT, TPOT, percentiles and goodput, and remember that output length is your biggest latency lever.

Exercises

  1. Compute the KV cache per token for a model with 32 layers, 8 KV heads, head dimension 128, at 2 bytes per value. How much for a 32,000-token context?
  2. A model streams at 40 ms per token with a 600 ms TTFT. Your product needs a full answer in under 5 seconds at p50. What's your maximum answer length?
  3. Explain to a colleague, without the word "bandwidth", why serving one user at a time is expensive per token.