Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Serving an LLM
fast, and cheap.
Training an LLM makes headlines; serving it pays the bills. Once a model is deployed to real users, a handful of systems tricks — the KV cache, continuous batching, quantization, speculative decoding — decide whether it feels instant or sluggish, and whether it costs a fortune or a rounding error. This is how they work.
Why serving is a memory problem
An LLM writes one token at a time, and to produce each token it must read every one of its billions of weights out of GPU memory. The arithmetic per token is trivial next to that data movement — so generation is memory-bandwidth-bound, not compute-bound. The GPU's math units sit mostly idle, waiting on memory.
This one fact explains almost every serving optimization. If the bottleneck is moving data, then the wins come from moving less of it (quantization), reusing what you've moved (the KV cache), and amortizing the move across many requests (batching). Keep "it's memory, not math" in mind and the whole field makes sense.
Reading the weights for one token is like driving to the warehouse to pick up a single item. The drive dominates — so you batch many orders into one trip, carry lighter boxes, and never re-fetch what's already in the truck.
Prefill vs decode — two very different phases
Every request has two phases with opposite characteristics, and serving systems treat them differently.
Prefill — read the prompt
Process the entire input prompt at once, in parallel. Compute-heavy, fast per token, done once. Produces the first token and fills the KV cache.
Decode — write the answer
Generate output tokens one at a time, each depending on the last. Memory-bound, slow, repeated once per output token. This is where most of the time goes.
The split matters for two metrics you'll live by: time to first token (TTFT) is dominated by prefill, while tokens per second after that is a decode property. A long prompt slows your first token; a long answer slows everything after it.
The KV cache — the thing that eats your memory
Attention lets each new token look back at every previous token — specifically at their Key and Value vectors. Recomputing those for the whole history at every step would be madness, so they're computed once and kept around: the KV cache. It's what makes decode fast.
The catch is size. The cache grows with every token, every layer, and every request in the batch — and it lives in the same precious GPU memory as the model weights. On long contexts and big batches, the KV cache, not the model, becomes the thing that runs you out of memory. Managing it well is the central problem of modern LLM serving.
The KV cache is why context length is expensive to serve, not just to train: double the context and you roughly double the cache each request holds. It's also why FlashAttention's memory savings matter so much — see the FlashAttention breakdown.
The arithmetic, worked with real models
Everything above becomes concrete with one formula. The KV cache stores a key and a value vector per token, per layer, per KV head:
Run it on real models at fp16 (2 bytes):
| Model | Shape | KV per token | One 4K-token sequence |
|---|---|---|---|
| Llama-2-7B (no GQA) | 32L × 32 KV heads × 128 | 2·32·32·128·2 = 512 KB | 2.0 GB |
| Llama-3-8B (GQA, 8 KV heads) | 32L × 8 KV heads × 128 | 2·32·8·128·2 = 128 KB | 0.5 GB — 4× less |
| 70B-class (GQA, 8 KV heads) | 80L × 8 KV heads × 128 | 2·80·8·128·2 = 320 KB | 1.25 GB |
Now the punchline that explains half of modern serving. Take an A100-40GB running Llama-2-7B: weights eat 14 GB, leaving ~26 GB. At 512 KB/token, a batch of 16 sequences at 4K context wants 32 GB of KV cache — more than the GPU has left. That is why grouped-query attention exists (4× fewer KV heads = 4× more batch), why PagedAttention stopped wasting reserved-but-unused KV space, and why long context is priced the way it is.
Decode speed is the same kind of one-liner. Generating one token requires reading essentially all the weights once, and decode is memory-bandwidth-bound. Take a round 2 TB/s (the 80 GB A100's figure; the 40 GB card above is closer to 1.6 TB/s, which gives ~114):
No kernel wizardry beats that ceiling for one stream — but the same weight read can serve a whole batch. At batch 32, those identical reads produce 32 tokens instead of 1, lifting the weight-read ceiling to ~4,500 tok/s aggregate — but only if 32 sequences' KV caches fit. At 4K context that is 64 GB, more than the whole 40 GB card, so that figure needs short contexts, and every sequence's own KV read still slows each step. Batching is free throughput until you run out of KV memory — which the table above just showed you is the real constraint. The whole modern serving stack is these two formulas fighting each other. Want to run the numbers on your own model and GPU? The interactive KV-cache calculator does exactly this arithmetic.
Continuous batching — keep the GPU full
Because moving the weights is the cost, you want as many requests as possible sharing each trip — that's batching. But naive static batching waits for the whole batch to finish before starting the next, so one long request holds up a dozen short ones and the GPU idles.
Continuous batching (popularized by vLLM) fixes this: it adds and removes requests from the running batch at every token step. The instant one request finishes, a waiting one takes its slot — the GPU never stalls.
This is the single biggest throughput win in modern serving, and it's why open-source servers like vLLM became the default. It costs nothing in quality — the outputs are identical; you're just scheduling the GPU better.
PagedAttention — no wasted memory
Continuous batching creates a new problem: requests come and go, each with a KV cache that grows unpredictably. Allocating one big contiguous block per request wastes huge amounts of memory to fragmentation and over-provisioning.
PagedAttention borrows the operating-system idea of virtual memory. It chops the KV cache into small fixed-size blocks (pages) that don't have to be contiguous, and keeps a lookup table mapping each request's logical sequence to its scattered physical blocks. Memory is handed out a page at a time, exactly as needed — so almost none is wasted, and you can fit far more concurrent requests on the same GPU.
PagedAttention is the trick that makes continuous batching practical at scale. Together they're why one GPU can serve many more simultaneous users than a naive implementation — the difference between renting one GPU and ten.
Quantization — carry lighter weights
Since serving is memory-bound, storing the model in lower precision is a direct speedup: smaller weights mean less data to move per token, plus more room for the KV cache. Quantization converts 16-bit float weights down to 8-bit or even 4-bit integers.
| Precision | Relative memory | Speed | Quality |
|---|---|---|---|
| FP16 / BF16 | 100% | baseline | full |
| INT8 | ~50% | faster | near-full |
| INT4 | ~25% | fastest | small, usually acceptable loss |
Going to 4-bit can shrink a model to a quarter of its size, often letting it run on a single consumer GPU with only a modest quality dip. The art is choosing what to quantize and how — weights are easy, activations are trickier — to keep the loss below what your product can notice.
Speculative decoding — guess ahead, verify in parallel
Decode is slow because it's sequential — one token, then the next. Speculative decoding breaks the sequence with a bet. A small, fast draft model guesses several tokens ahead; then the big model checks all of them in a single forward pass. Verifying in parallel is cheap, so:
Draft model guesses
- Small & fast, proposes 4–5 tokens
- Cheap to run
- Often right on easy tokens ("the", "of")
Big model verifies
- Checks all guesses in one pass
- Accepts the correct prefix for free
- Rejects the rest, continues normally
The crucial property: the output is exactly what the big model would have produced alone — verification guarantees it. You get lower latency with zero quality change, as long as the draft model is right often enough to pay for itself.
Latency vs throughput — the knob you're really turning
Every serving decision trades one against the other. Knowing which you're optimizing is half the job.
| You want… | Turn this up | Cost |
|---|---|---|
| Higher throughput (cheaper per token) | Bigger batches | Higher latency per request |
| Lower latency (snappier) | Smaller batches, speculative decoding | Lower GPU utilization / higher cost |
| Bigger model on the GPU | Quantization | Small quality loss |
| More concurrent users | PagedAttention + continuous batching | Engineering complexity |
A chat UI optimizes for TTFT and streams tokens so the wait feels short; a bulk document-processing job optimizes for raw throughput and happily runs huge batches. The last lever is routing: send easy requests to a small cheap model and only escalate hard ones to the big model — the job of an LLM gateway.
When asked to "make the LLM faster," don't jump to a trick. First ask: is this latency-sensitive or throughput-sensitive? TTFT or tokens/sec? Prefill-bound or decode-bound? The right optimization falls out of the answer.
Cost and trade-offs: batch size against memory, in numbers
The page’s two formulas, run together. A decode step reads every weight once and the whole KV cache of every sequence in the batch. Take the page’s 40 GB GPU, its 2 TB/s bandwidth and 4K-token sequences. (As the page notes, 2 TB/s is the 80 GB A100’s figure; the 40 GB card is closer to 1.6 TB/s, which makes every time below about 25% longer.) Here Time is one decode step and the tokens per second it gives, and Space is the memory it holds. Activations and framework overhead are ignored.
| Case | Time | Space | Why |
|---|---|---|---|
| Llama-2-7B fp16, batch 1 | 16 GB read → 8 ms; 125 tok/s | 14 GB weights + 2 GB KV | Below the page’s 143 tok/s ceiling: at 4K context the KV read adds 2 GB to every step. |
| Same, batch 8 | 30 GB → 15 ms; 533 tok/s in total, 67 per user | 14 + 16 = 30 GB | The weights are read once for all 8 users. The KV cache is not shared, so it is read 8 times. |
| Same, batch 13 | 40 GB → 20 ms; 650 tok/s, 50 per user | 14 + 26 = 40 GB: full | The most that fits. Total speed is 5.2× batch 1, but each user gets 2.5× slower tokens. |
| Same, batch 16 | — | 14 + 32 = 46 GB | Does not fit. This is the page’s “more than the GPU has left”. |
| Llama-3-8B (GQA) fp16, batch 48 | 40 GB → 20 ms; 2,400 tok/s, 50 per user | ~16 GB weights + 48 × 0.5 GB | 4× smaller KV per token buys 48 sequences instead of 13, and 3.7× the total throughput at the same per-user speed. |
| Llama-2-7B INT4 weights, batch 18 | 39.5 GB → 19.75 ms; 911 tok/s | 3.5 GB weights + 36 GB KV | Quantizing weights frees 10.5 GB, which is 5 more sequences. The KV cache is still fp16, so the gain is 1.4×, not 4×. |
Read the per-user column. Bigger batches raise total throughput and lower cost per token, while each user’s stream gets slower. That is the latency-against-throughput knob from section 09, with numbers on it. At long context the KV cache, not the weights, sets both the batch ceiling and the step time. That is why GQA moves throughput more than INT4 weights do here. Real servers also become compute-bound at larger batches, so treat these numbers as upper limits.
Common mistakes
- Benchmarking with toy lengths
A load test with 128-token prompts and 128-token answers barely touches the KV cache, so it reports batch sizes and throughput that real 4K-token traffic can never reach (compare batch 13 above with the batch 32 the page says needs short contexts). Replay your real distribution of prompt and output lengths.
- Expecting weight quantization to shrink the KV cache
INT4 weights cut the weights, not the cache. In the table above, 4× smaller weights gave 1.4× the throughput, because 36 of the 39.5 GB read per step was still fp16 KV. Shrinking the cache needs GQA in the model, or a separate KV-cache quantization setting in the server, checked with its own evals.
- Watching throughput and ignoring TTFT under load
Time to first token includes time spent waiting in the queue. With continuous batching, a newly admitted request’s long prefill runs in the same steps as everyone else’s decode, so one 30K-token prompt can stall every stream on that GPU. Track p95 TTFT separately from tokens per second. Chunked prefill, which splits a long prompt across several steps, exists for this problem.
- Turning on speculative decoding everywhere
It pays when the GPU is idle waiting on memory: small batches and predictable text such as code. At large batches the GPU is already busy, so verifying the draft’s guesses is no longer free. At high temperature the draft is wrong more often. Either way it can end up slower than plain decoding. Measure the acceptance rate on your own traffic.
- Running the KV pool at 100%
PagedAttention hands out pages as sequences grow. When the pool runs out mid-generation, the scheduler has to preempt a running request, then swap its cache out or recompute it later. That is wasted GPU time and a latency spike for that user. Leave headroom and cap concurrent sequences or the maximum context length.
Where this shows up in production and interviews
- Open serving engines
vLLM, Hugging Face TGI, NVIDIA TensorRT-LLM and SGLang all build on the same ideas: continuous batching, a paged KV cache, quantized weights and speculative decoding. SGLang’s RadixAttention also shares the KV cache between requests that start with the same prefix.
- Prefix caching and API prices
When thousands of requests start with the same system prompt, the server can keep that prefix’s KV cache and skip its prefill. That cuts TTFT and compute. It is why the major API providers bill cached input tokens at a fraction of the normal input rate.
- Splitting prefill from decode
Prefill is compute-bound and decode is memory-bound, so mixing them on one GPU makes each slow the other down. Research systems such as DistServe and Splitwise run them on separate GPU pools and move the KV cache between them. That way each pool can be sized and tuned for one kind of work.
- The interview version
“Design an inference server for a 7B model.” Do the two formulas out loud: KV bytes per token, then how many sequences fit, then the bandwidth ceiling. State TTFT and per-token targets. Then choose levers based on what you are short of: continuous batching and paging for concurrency, GQA or KV quantization for memory, speculative decoding for latency at low load.
Check yourself
Llama-3-8B (128 KB of KV per token) serves 32K-token contexts with 24 GB free after weights. How many sequences fit?
128 KB × 32,768 tokens = 4 GB per sequence, so 6 fit in 24 GB. At 4K context the same GPU held 48. Context length divides your batch size directly, which is why long-context requests cost more to serve.
The draft model proposes 4 tokens and the big model accepts the first 2. How many tokens does this step produce?
3. The two accepted tokens, plus the big model’s own token at the first position it rejected, which it computed in the same verification pass. Even when nothing is accepted, the step still produces 1 token. So a bad draft never changes the output; it only wastes the draft’s time.
Users with 30K-token prompts wait 6 s for the first token, then text streams quickly. Which lever do you reach for: INT4 weights, speculative decoding, or prefix caching?
Prefix caching (and chunked prefill, or a shorter prompt through retrieval). The slow part is prefill, which is TTFT. Speculative decoding and smaller weights mainly speed up decode, and decode is already fine. If most of those 30K tokens are a shared document or system prompt, caching its KV removes most of the prefill.
INT4 cuts Llama-2-7B’s weights from 14 GB to 3.5 GB. How much faster is one stream, and how much faster is a full GPU?
One stream at short context: 2 TB/s ÷ 3.5 GB ≈ 571 tok/s against 143, so 4×. A full GPU at 4K context: 911 against 650 tok/s, only 1.4×, because most of each step now reads the fp16 KV cache. The answer to “how much faster?” depends on whether the weights or the KV cache are the bigger read.
Quick answers
Why is serving an LLM slow?
Generation is autoregressive and every token requires reading the whole model from GPU memory, so it's memory-bandwidth-bound, not compute-bound. The optimizations are all about moving less memory.
What is the KV cache?
Stored Key/Value vectors for every previous token so attention doesn't recompute them each step. It makes decode fast but grows with sequence length and batch size, dominating GPU memory.
What is continuous batching?
Adding and removing requests from the running batch every token step (vLLM), so a finished request is instantly replaced — keeping the GPU full and multiplying throughput.
What is quantization?
Storing weights in int8/int4 instead of 16-bit floats — less memory to move means faster generation, at a small, usually acceptable quality loss.
What is speculative decoding?
A small draft model guesses several tokens; the big model verifies them in one parallel pass. Correct guesses are free, cutting latency with no change to the output.
This idea in other formats
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Prompting HandbookA friendly, hands-on field guide for everyday humans — learn the CRISP framework, spot bad prompts, practice with real recipes, play a drag-and-drop game, and test yourself with a quiz. No code required.Read →
- The Senior AI Engineer Interview Handbook60 questions across architecture, production incidents, agentic systems, RAG, evals, cost, safety, and leadership — what staff-level AI interviewers actually probe for.Read →
- The Transformers HandbookThe architecture behind every LLM, built up from scratch — tokens and embeddings, positional encoding, self-attention (query/key/value), multi-head attention, the transformer block (FFN, residuals, layer norm), and how a decoder-only model generates text autoregressively.Read →
- The Fine-Tuning HandbookWhen to fine-tune vs RAG vs prompting, full fine-tuning vs parameter-efficient methods, how LoRA and QLoRA make it cheap enough for a single GPU, why the data matters more than the method, catastrophic forgetting, and how to evaluate and decide.Read →
- The On-Device AI HandbookSmall models, everywhere: why 1–14B models got frontier-adjacent (distillation + textbook data), the napkin law of local inference (tokens/sec ≈ bandwidth ÷ bytes), quantization and the llama.cpp / GGUF / Ollama / MLX stack, the honest local-vs-cloud decision table, four hybrid patterns that ship, and the evals craft of choosing a small model that actually fits the device.Read →
- The GPU Fundamentals HandbookThe bottleneck is never where you think. SIMT and warps, the memory hierarchy from registers to HBM, arithmetic intensity and the roofline (compute-bound vs bandwidth-bound), where LLM workloads actually land, why FlashAttention was inevitable, the kernel stack from CUDA to Triton to torch.compile, and the multi-GPU interconnect story.Read →