Level 3 In-Depth AI · ML Engineering and Production
Serving LLMs at Scale
How companies serve a large language model to thousands of users at once without going bankrupt. Why decoding is memory-bound, continuous batching, PagedAttention and the KV-cache budget, prefix caching, chunked prefill, quantization, engines such as vLLM and SGLang, and the arithmetic of latency, throughput and cost per token.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 35 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 35 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- The Perceptron
- The ML Project Lifecycle
- Logistic Regression
- Deploying Models
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- The KV Cache and Fast Inference
- Serving LLMs at Scale
Read them roughly in this order. See it on the concept map →
Why it matters
A trained language model is a file of weights. Turning it into a service that answers millions of requests a day, each streaming tokens back within a fraction of a second, is a hard engineering problem, and it decides the economics of every AI product. The difference between a naive server and a good one is often five to twenty times in throughput on the same GPUs. That is the difference between a product that loses money on every request and one that doesn't.
LLM serving differs from ordinary Deploying Models in three ways. Each request runs the model hundreds or thousands of times, once per generated token. Requests vary wildly in length, from "hi" to a 100-page document. And GPU memory, not arithmetic, is the scarce resource, mostly because of the The KV Cache and Fast Inference. This chapter explains the techniques that every modern inference engine uses to cope.
The intuition
Picture a bus that can carry 16 passengers, all heading to different stops. The naive approach, static batching, fills the bus, drives until the last passenger reaches their stop, returns empty, and only then lets the next 16 board. Seats sit empty for most of the trip, and people at the depot wait the whole time.
Continuous batching lets a new passenger board at every stop where someone gets off. The bus is always nearly full, and nobody waits for a stranger's long journey to finish.
Why is a full bus nearly free? Because generating a token is memory-bound (AI Hardware: GPUs, TPUs and Accelerators). Each decode step must read every weight of the model from GPU memory, whether it's producing one token or 64. Adding more sequences to the batch reuses those same weight reads, so throughput grows almost in proportion to the batch, until memory for the KV cache runs out.
Key idea LLM serving is a memory-management problem. Decoding reads all the weights for every step, so batching many sequences together is almost free, and the batch is limited by how much KV cache fits in GPU memory. Continuous batching keeps the batch full, and PagedAttention packs the cache tightly.
How it works
The metrics
Users and operators care about different numbers:
- Time to first token (TTFT): how long until the first word appears. Dominated by queueing and prefill, the parallel pass over the prompt (The KV Cache and Fast Inference).
- Inter-token latency (ITL), also called time per output token: the gap between streamed tokens. Dominated by the decode step. Around 20–50 ms per token (20–50 tokens per second) feels fluent for reading.
- Throughput: total tokens per second the server produces across all users. This is what decides cost.
- Goodput: throughput counting only requests that met their service level objectives (SLOs), the latency targets promised to users, such as "TTFT under 1 second and ITL under 50 ms for 99% of requests". It stops you gaming throughput with batches so large that everyone waits.
Latency and throughput pull against each other. Bigger batches raise throughput, but each step takes a little longer, and prefills for new arrivals interrupt everyone's decoding.
Why the batch size matters so much
Worked example. Llama 3 8B in BF16 is about 16 GB of weights. An H100 reads memory at about 3.35 TB/s, so one decode step needs at least ms just to read the weights. At batch 1, that caps one user at about 200 tokens per second, and the server's throughput at the same. At batch 64, the step costs only a little more (the per-sequence work is small next to the weight reads), but produces 64 tokens: throughput approaches tokens per second in this idealised picture. Real engines fall well short of the ideal, but batching still multiplies throughput many times over.
The KV-cache budget
What limits the batch is memory. Each sequence needs its KV cache, bytes per token (The KV Cache and Fast Inference). Engines such as vLLM by default use 90% of GPU memory: weights first, a little working space, and the rest for the cache.
| Model (BF16 KV cache) | KV per token | Weights | Memory left for cache (90% use) | Tokens that fit | 4,096-token sequences |
|---|---|---|---|---|---|
| Llama 2 7B on 1 × H100 (MHA, 32 KV heads) | 512 KiB | 13.5 GB | about 58 GB | about 112,000 | about 27 |
| Llama 3 8B on 1 × H100 (GQA, 8 KV heads) | 128 KiB | 16 GB | about 56 GB | about 426,000 | about 104 |
| Llama 3 70B on 2 × H100, BF16 weights | 320 KiB | 141 GB | about 3 GB | about 9,000 | about 2 |
| Llama 3 70B on 2 × H100, FP8 weights | 320 KiB | 71 GB | about 73 GB | about 224,000 | about 54 |
The table keeps the arithmetic simple by treating an H100 as exactly 80 GB. The card really reports about 80 GiB (roughly 85 GB), which adds about 5 GB of cache per GPU. That matters most in the tightest row: the 70B model with BF16 weights fits about 9 sequences rather than 2, still far short of the FP8 version's 60 or so.
Two lessons jump out. Grouped-query attention (Llama 3) fits four times as many sequences as full multi-head attention (Llama 2). And quantizing the weights of the 70B model from BF16 to FP8 frees enough memory to raise the batch from 2 sequences to more than 50. Quantization's biggest serving win is often batch size, not raw speed.
PagedAttention
A sequence's KV cache grows by one token at a time, to a length nobody knows in advance. Early servers reserved a contiguous block for the maximum possible length, wasting most of it. PagedAttention (Kwon et al., 2023, the core of vLLM) borrows the idea of virtual memory from operating systems. It splits the cache into small fixed-size blocks (for example 16 tokens each) allocated on demand, with a per-sequence table mapping logical positions to physical blocks. Waste drops to the unfilled part of each sequence's last block. The vLLM paper reported 2–4 times the throughput of earlier systems such as FasterTransformer and Orca at the same latency. Blocks can also be shared: sequences that start with the same prompt point to the same physical blocks.
Continuous batching
Continuous batching (also called iteration-level scheduling or in-flight batching), introduced by the Orca system (Yu et al., OSDI 2022), makes scheduling decisions at every decode step rather than once per batch. After each step, finished sequences leave and waiting requests join. In the simulation below, with requests needing between 10 and 400 tokens and 16 slots, continuous batching gives about 1.5 times the throughput of static batching and cuts the average time to finish by a third. With more varied lengths the gain is larger.
Prefill, chunked prefill and disaggregation
New requests need a prefill, which is compute-bound and can take hundreds of milliseconds for a long prompt. If the engine runs a big prefill on its own, every user in the batch sees a stall in their stream. Chunked prefill (as in Sarathi-Serve, 2024) splits long prompts into chunks and mixes them into ordinary decode steps, smoothing latency. At large scale, disaggregated serving runs prefill and decode on different GPUs (DistServe, 2024, among others), so that each pool can be sized and configured for its own bottleneck, and ships the KV cache between them.
More tricks
- Prefix caching: keep the KV cache of common prefixes (system prompts, shared documents, earlier conversation turns) and reuse it. SGLang's RadixAttention organises cached prefixes in a tree. API providers pass the saving on as cheaper "cached input" tokens.
- Quantization: FP8 or INT4 weights and an FP8 KV cache (Quantization).
- Speculative decoding: a small draft model proposes several tokens and the big model verifies them in one pass (The KV Cache and Fast Inference).
- Tensor parallelism: split a model that doesn't fit, or needs lower latency, across several GPUs in one server (Distributed Training).
Engines
You rarely build any of this yourself. An inference engine packages it all behind an HTTP API, usually compatible with OpenAI's chat-completions format so existing clients work unchanged. As of late 2026 the main open-source engines are vLLM (from UC Berkeley, now a large community project), SGLang (from LMSYS and collaborators) and NVIDIA's TensorRT-LLM. Hugging Face's Text Generation Inference (TGI), once a common choice, has been in maintenance mode since December 2025, and Hugging Face now points new deployments to vLLM or SGLang. For a single user on a laptop, llama.cpp and Ollama are the usual choices (Running Models Locally).
Cost per token
The cost per token (usually quoted per million tokens) comes down to one division:
Worked example. Suppose an H100 rents for 3 US dollars per hour (a plausible 2025 cloud price; real prices vary widely). Serving one user at a time at 60 tokens per second produces 216,000 tokens per hour: about $13.90 per million tokens. Batching to an aggregate 3,000 tokens per second produces 10.8 million tokens per hour: about $0.28 per million tokens, fifty times cheaper on identical hardware. This is why per-token API prices are so much lower than what one person would pay to rent a GPU, and why providers charge more for output tokens (slow, sequential decode) than for input tokens (fast, parallel prefill).
In code
A simulation of static versus continuous batching. 200 requests want between 10 and 400 output tokens, the GPU can decode 16 sequences at once, and each decode step costs 20 ms (reading the weights) plus 0.5 ms per sequence in the batch. Prefill is ignored to keep it short.
import numpy as np
rng = np.random.default_rng(0)
lengths = rng.integers(10, 400, size=200) # output tokens wanted by 200 requests
SLOTS = 16 # sequences the GPU can decode together
STEP_MS = lambda batch: 20 + 0.5 * batch # one decode step: read weights + per-sequence work
def static_batching(lengths):
t, finish = 0.0, []
for i in range(0, len(lengths), SLOTS): # take 16 requests, run until ALL are done
group = lengths[i:i + SLOTS]
for step in range(1, group.max() + 1):
t += STEP_MS(int((group >= step).sum()))
finish += [t] * int((group == step).sum())
return t, finish
def continuous_batching(lengths):
queue, running, t, finish = list(lengths), [], 0.0, []
while queue or running:
while queue and len(running) < SLOTS: # refill free slots before every step
running.append(queue.pop(0))
t += STEP_MS(len(running))
running = [r - 1 for r in running]
finish += [t] * sum(r == 0 for r in running)
running = [r for r in running if r > 0]
return t, finish
total = lengths.sum()
for name, fn in [("static", static_batching), ("continuous", continuous_batching)]:
t, finish = fn(lengths)
print(f"{name:<11} total {t / 1000:5.1f} s throughput {total / t * 1000:5.0f} tokens/s"
f" mean time to finish {np.mean(finish) / 1000:5.1f} s")
# static total 120.0 s throughput 362 tokens/s mean time to finish 58.4 s
# continuous total 79.8 s throughput 544 tokens/s mean time to finish 39.1 s
Static batching wastes the slots of requests that finish early while the longest in each group keeps going. Continuous batching fills them at once.
With a real engine, serving a model takes one command. vLLM needs a supported GPU, and this downloads the model:
pip install vllm
vllm serve Qwen/Qwen2.5-1.5B-Instruct --gpu-memory-utilization 0.9
It then exposes an OpenAI-compatible API on port 8000, so the official openai Python client works against it:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="not-needed")
reply = client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct",
messages=[{"role": "user", "content": "Explain continuous batching in one sentence."}],
max_tokens=60,
)
print(reply.choices[0].message.content)
Common pitfalls
- Benchmarking with one request at a time. A single-user test measures latency, not capacity. Load-test with realistic concurrency and a realistic mix of prompt and output lengths.
- Setting the maximum context far larger than needed. It doesn't reserve memory with PagedAttention, but a few huge requests can still crowd out many small ones. Set limits that match your use.
- Ignoring prefill. A workload of long documents with short answers is dominated by prefill and behaves very differently from a chatbot. Measure TTFT separately from ITL.
- Optimising only throughput. Pushing batch size to the limit can blow your latency SLOs. Track goodput, and percentiles rather than averages (Deploying Models).
- Mismatched chat templates. Sending raw text to an instruct model without its chat template gives oddly poor answers. Use the engine's chat endpoint, which applies the template.
Watch out When GPU memory for the KV cache runs out, engines must pause (preempt) some sequences, either swapping their cache to CPU memory or throwing it away and recomputing it later. Latency then spikes for those users. Watch the engine's preemption and cache-usage metrics, and add capacity or shrink the cache (quantization, shorter limits) before it happens in production.
Where it leads
- The KV Cache and Fast Inference: the data structure behind everything in this chapter, plus MQA, GQA and speculative decoding.
- Quantization and AI Hardware: GPUs, TPUs and Accelerators: the memory and bandwidth levers.
- Running Models Locally: the single-user version, on your own machine.
- Using LLM APIs and Building AI Products: the consumer side of the serving stack, including prompt caching and batch APIs.
- Reasoning Models and Test-Time Compute: models that generate thousands of thinking tokens make decode efficiency even more important.
A bit of history
Early transformer serving reused ideas from other neural networks: fixed batches and contiguous buffers, as in NVIDIA's FasterTransformer. ChatGPT's launch in late 2022 turned LLM inference into one of the largest computing workloads in the world almost overnight. Orca (OSDI 2022) had just introduced iteration-level scheduling, the basis of continuous batching. In 2023 the vLLM team at UC Berkeley published PagedAttention and released vLLM as open source, and Hugging Face's TGI and NVIDIA's TensorRT-LLM adopted similar techniques. SGLang followed with prefix-sharing RadixAttention and fast structured output. In 2024 work turned to chunked prefill, separating prefill from decode, and FP8 inference on H100s. Combined with cheaper hardware and smaller, better models, these engineering advances helped the price of a given level of model capability fall dramatically within a few years.
Try it
- In the simulation, change the output lengths to
rng.integers(190, 210, size=200)(all nearly equal). How much does continuous batching help now? Why?- Change
SLOTSto 4, 16 and 64. Plot throughput against slots for both schedulers. What would stop you increasing the slots on a real GPU?- Using the KV-cache formula, how many 32,768-token conversations can Llama 3 8B hold in 56 GB of cache memory? What if the cache is stored in FP8?
Hint for 3: 128 KiB per token in BF16, half that in FP8.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM)
Stores the KV cache in fixed-size pages like an operating system's virtual memory, so many requests can share GPU memory with little waste.
vLLM documentation
A widely used open-source LLM inference engine with paged KV cache, continuous batching and prefix caching.
How continuous batching enables 23x throughput in LLM inference while reducing p50 latency
A clear explanation of why LLM inference is memory-bound and how continuous batching and PagedAttention raise throughput, with benchmarks.
Orca: A Distributed Serving System for Transformer-Based Generative Models
Introduces iteration-level scheduling, the idea behind continuous batching: decide which requests run at every decoding step.
SGLang
A fast open-source serving engine for LLMs and vision-language models, known for RadixAttention prefix caching and structured output.
Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve
Chunked prefill and stall-free scheduling: mixing pieces of long prompts into decode batches to keep both throughput and latency good.
How To Scale Your Model
A free online book on the systems view of LLMs: rooflines, TPUs and GPUs, sharding, parallelism strategies and inference, with worked problems.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/llm-serving.md