How LLM Inference Actually Works
Why generating text is memory-bound, what the KV cache is, and the tricks (batching, paging, quantization, speculative decoding) that make serving a model affordable.
A first-principles walkthrough for backend engineers. Numbers are rounded, back-of-the-envelope figures meant to build intuition, not benchmarks.
Training gets the headlines. Inference gets the bill.
Training a large language model happens once. Inference happens every time someone sends a prompt, forever. For any model that ships to real users, the lifetime cost of serving it quickly dwarfs the cost of training it.
If you are a backend engineer, inference should feel familiar. It is a latency-sensitive, resource-constrained service with a scheduler, a cache, and a throughput-versus-latency tradeoff. The twist is that one resource, memory bandwidth, dominates everything. Once you see why, most of the optimizations in this field stop looking like magic.
This post builds that picture in four steps:
- How a model generates text one token at a time
- Why the two phases of a request behave completely differently
- What the KV cache is and why it dominates memory
- The techniques that turn all this into a viable service
Step 1: Generation is a loop
An LLM does not write a response. It predicts one next token, appends it to the input, and runs again.
prompt: "The capital of France is"
step 1: model(prompt) -> " Paris"
step 2: model(prompt + " Paris") -> "."
step 3: model(prompt + " Paris.") -> <end>
Each pass through the model is called a forward pass. A 500-token answer means 500 sequential forward passes. You cannot compute token 100 until token 99 exists, so this loop cannot be parallelized across the output of a single request. That one fact shapes everything that follows.
Step 2: Two phases with opposite personalities
Every request has two distinct phases.
Prefill: reading the prompt
The model processes your entire prompt at once. All input tokens are known up front, so the GPU handles them in parallel as large matrix multiplications. This keeps the GPU's compute units busy. Prefill is compute-bound.
Decode: writing the answer
Now the model generates one token per forward pass. Each pass only needs to process a single new token, but it still has to read every weight in the model from GPU memory to do it. That is a tiny amount of math against a huge amount of data movement. Decode is memory-bandwidth-bound.
A quick calculation makes this concrete. Take a 7-billion-parameter model stored in 16-bit precision:
weights: 7B parameters x 2 bytes = ~14 GB
GPU memory bandwidth: ~2 TB/s (A100-class)
time to read weights: 14 GB / 2000 GB/s = ~7 ms
best case for one stream: ~1 token / 7 ms = ~140 tokens/sec
No matter how many FLOPs the GPU has, a single request cannot decode faster than the time it takes to stream the weights through the chip. The GPU spends most of the decode phase waiting on memory.
Another way to say it is arithmetic intensity: floating-point operations performed per byte read. A modern GPU needs roughly 150 or more operations per byte to keep its compute units busy. Single-request decode delivers about 1. That gap is the whole story.
| Prefill | Decode | |
|---|---|---|
| Tokens processed per pass | Whole prompt | One |
| Bottleneck | Compute | Memory bandwidth |
| GPU utilization | High | Low (for one request) |
| User-visible metric | Time to first token | Time per output token |
The metrics that matter
Because the phases differ, we measure them separately:
- TTFT (time to first token): how long until the user sees anything. Dominated by queueing plus prefill.
- TPOT (time per output token): the gap between streamed tokens. Dominated by decode. This is what makes a response feel fast or sluggish while it streams.
- Throughput: total tokens per second across all users. This is what determines cost per token.
These pull against each other. Packing more requests onto a GPU raises throughput but can hurt TTFT and TPOT for each individual user. Most of inference engineering is negotiating that tradeoff.
Step 3: The KV cache
Inside each transformer layer, attention lets a token look back at every previous token. To do that, each token produces a key and a value vector.
Here is the key insight: the keys and values for tokens we already processed never change. Recomputing them on every step would waste enormous effort, since step 500 would redo the work for tokens 1 through 499.
So we store them. That store is the KV cache.
without cache: step N recomputes keys/values for all N tokens -> O(N^2) total work
with cache: step N computes keys/values for 1 new token,
reads the other N-1 from memory -> O(N) total work
The cache turns repeated computation into memory reads, which is a great trade, but it creates a new problem: the cache is big.
How big?
Per token, the cache holds a key and a value for every layer. For a 7B-class model with 32 layers and a hidden size of 4096, stored in 16-bit:
per token: 2 (K and V) x 32 layers x 4096 x 2 bytes = ~0.5 MB
one 4,096-token conversation: ~2 GB
Two gigabytes for a single conversation. Serve 32 concurrent users at that length and the cache alone is about 64 GB, more than the model weights, and it grows with every generated token. In practice, the KV cache, not the weights, decides how many requests fit on a GPU.
(Newer architectures shrink this with techniques like grouped-query attention, where many query heads share a smaller set of key/value heads. That is a model design choice rather than a serving trick, and it directly cuts cache size.)
Step 4: Making it affordable
Now that we know the bottlenecks, the major techniques each attack one of them.
Batching: share the weight reads
Decode is slow because reading the weights is expensive and each request does almost no math with them. The fix: serve many requests in the same forward pass. The weights are read from memory once and used for every request in the batch.
batch of 1: read 14 GB -> 1 token produced
batch of 32: read 14 GB -> 32 tokens produced (nearly the same time)
Batching raises arithmetic intensity almost for free, which is why serving many users on one GPU is dramatically cheaper per token than serving one.
Continuous batching: don't wait for the slowest request
Naive batching groups requests, runs them together, and waits until every request finishes. But responses have wildly different lengths. A 10-token answer sits idle while a 1,000-token answer in the same batch keeps running.
Continuous batching (also called iteration-level scheduling) fixes this by rebuilding the batch at every decode step. When a request finishes, its slot is immediately given to a waiting request. The GPU never sits on dead slots. It is the single biggest scheduling win in modern serving engines.
PagedAttention: manage the cache like virtual memory
Early systems reserved one contiguous block of memory per request, sized for the maximum possible length. Since most responses are shorter, large amounts of reserved memory sat unused, and the leftover gaps could not fit new requests. This is classic fragmentation.
PagedAttention, introduced with the vLLM project, borrows the operating system's answer: split the cache into small fixed-size blocks (pages) and allocate them on demand, with a table mapping each request's logical positions to physical blocks.
The payoffs:
- Almost no wasted memory, so more concurrent requests fit
- Requests that share a prefix (the same system prompt, for example) can share the same physical blocks instead of each storing a copy
Prefix caching: skip work you already did
Many production prompts start with the same long preamble: a system prompt, tool definitions, a document everyone is asking questions about. Since the KV cache for an identical prefix is identical, an engine can keep it around and skip prefill for the shared part. This lowers TTFT and cost for chat and retrieval workloads with repeated context.
Quantization: shrink the bytes
If decode is limited by how many bytes we read, read fewer bytes. Quantization stores weights in lower precision, such as 8-bit or 4-bit integers instead of 16-bit floats.
16-bit weights: 7B x 2.0 bytes = ~14 GB
8-bit weights: 7B x 1.0 bytes = ~7 GB
4-bit weights: 7B x 0.5 bytes = ~3.5 GB
Fewer bytes means a smaller model footprint and a faster decode, since the memory read is the bottleneck. The cost is some loss in accuracy, which good quantization methods keep small for many models. The KV cache can be quantized too, which stretches how many requests fit.
FlashAttention: stop shuttling data you don't need to
Standard attention writes a large intermediate score matrix out to GPU memory and reads it back, which is slow because of the exact bandwidth limit we have been discussing. FlashAttention reorganizes the computation into tiles that stay in the GPU's fast on-chip memory, producing the same result with far less memory traffic. It is an exact optimization, not an approximation.
Speculative decoding: guess ahead, verify in bulk
Decode generates one token per pass, which wastes a compute-starved GPU. Speculative decoding exploits that spare capacity:
- A small, fast draft model guesses the next several tokens (say, 4).
- The large model verifies all of them in a single forward pass, which is cheap because checking several tokens in parallel looks like prefill.
- It accepts the longest correct run of guesses and continues from there.
draft guesses: "The" "capital" "of" "France"
big model check: accept, accept, accept, reject -> keep 3 tokens, fix the 4th
result: 3-4 tokens for the price of ~1 big-model pass
The output distribution is preserved, so quality does not change. The speedup depends on how often the draft model guesses right.
Disaggregated serving: giving each phase its own hardware
Since prefill is compute-bound and decode is memory-bound, running both on the same GPUs means they interfere: a long prefill can stall the decode steps of everyone else in the batch, causing visible hiccups in streaming.
A growing pattern is disaggregated serving: dedicate one pool of machines to prefill and another to decode, passing the KV cache between them. Each pool can then be sized and tuned for its own bottleneck. The tradeoff is the cost and complexity of moving cache data over the network, so it pays off most at larger scale.
Putting it together
| Bottleneck | What causes it | Technique |
|---|---|---|
| Weights re-read every token | Decode is memory-bound | Batching, quantization |
| Idle GPU slots | Requests finish at different times | Continuous batching |
| Wasted cache memory | Fragmentation from worst-case reservation | PagedAttention |
| Repeated prompt work | Shared prefixes | Prefix caching |
| Attention memory traffic | Large intermediate matrices | FlashAttention |
| One token per pass | Sequential generation | Speculative decoding |
| Prefill and decode interfering | Different bottlenecks | Disaggregated serving |
The mental model to take away
Inference performance is almost never about raw compute. It is about moving bytes: weights from memory to the chip, cache entries back and forth, data between machines. Every technique above either reads fewer bytes (quantization, FlashAttention), shares the bytes it reads across more work (batching, prefix caching), or wastes fewer bytes (PagedAttention).
When you evaluate an inference system or debug a slow one, ask the same question each time: what is this GPU waiting on? More often than not, the answer is memory, and the fix is to make each byte do more useful work.