◆ AI All-in-One

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
↗ Plan a path here

Read first

The KV Cache and Fast InferenceDeploying Models

This leads to

—
The full path from zero — 35 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. Python for AI
  6. How Machines Learn
  7. Partial Derivatives and Gradients
  8. Matrices and Matrix Multiplication
  9. The Chain Rule
  10. Dot Product, Norms and Similarity
  11. Tokenization
  12. Supervised, Unsupervised and Reinforcement Learning
  13. Gradient Descent
  14. Language Modeling and Next-Token Prediction
  15. Supervised Learning
  16. Linear Regression
  17. The Perceptron
  18. The ML Project Lifecycle
  19. Logistic Regression
  20. Deploying Models
  21. Neural Networks
  22. Recurrent Neural Networks
  23. Backpropagation
  24. Activation Functions
  25. Vanishing and Exploding Gradients
  26. Normalization Layers: BatchNorm and LayerNorm
  27. LSTMs and GRUs
  28. Residual Connections
  29. Sequence-to-Sequence Models
  30. Attention
  31. Self-Attention and Multi-Head Attention
  32. Positional Encodings
  33. The Transformer
  34. GPT and Decoder-Only Models
  35. The KV Cache and Fast Inference
  36. 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.

Static batching group 2 waits for R2, the longest in group 1 slot 1 slot 2 slot 3 slot 4 R1 R2 R3 R4 R5 R6 R7 R8 all done after 17 steps Continuous batching a waiting request takes any slot that frees up slot 1 slot 2 slot 3 slot 4 R1 R2 R3 R4 R5 R6 R7 R8 all done after 14 steps 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 step idle slot (wasted)
Fig. 1 The same eight requests served by four batch slots. Top: static batching. Each group of four runs until its longest request finishes, so slots sit idle (hatched) and the second group waits. Bottom: continuous batching. A new request starts in a slot the moment the previous one finishes, so slots stay busy and everything finishes sooner.

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 16/3350≈4.816 / 3350 \approx 4.8 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 64×200≈12,80064 \times 200 \approx 12{,}800 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, 2×nlayers×nkv heads×dhead×2 \times n_{\text{layers}} \times n_{\text{kv heads}} \times d_{\text{head}} \times 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.

How GPU memory is split, and how many 4,096-token chats fit 0 40 80 120 160 GB of GPU memory Llama 2 7B1 × H100, MHA≈ 27 chats Llama 3 8B1 × H100, GQA≈ 104 chats Llama 3 70B BF162 × H100≈ 2 chats Llama 3 70B FP82 × H100≈ 54 chats weights KV cache reserved (10%)
Fig. 2 GPU memory split between weights (tan), KV cache (purple) and a 10% reserve, with the number of 4,096-token conversations whose cache fits. Llama 2 7B fits about 27, Llama 3 8B about 104 thanks to grouped-query attention. Llama 3 70B on two H100s fits only 2 with BF16 weights, but about 54 with FP8 weights.

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:

cost per million tokens=GPU cost per hourtokens per hour×106\text{cost per million tokens} = \frac{\text{GPU cost per hour}}{\text{tokens per hour}} \times 10^6

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

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

  1. 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?
  2. Change SLOTS to 4, 16 and 64. Plot throughput against slots for both schedulers. What would stop you increasing the slots on a real GPU?
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Requests need between 10 and 400 output tokens. Why does continuous batching beat static batching?

  2. Llama 3 70B on two H100s fits only about 2 long conversations in BF16 but about 54 with FP8 weights. Why?

  3. An H100 rents for $3 per hour and your server produces 3,000 tokens per second across users. Roughly what is the cost per million tokens?

  4. You push batch size up until throughput is maximal, but many users now wait over 2 seconds for the first token, breaking your SLO. Which metric captures this problem?

  5. Long prompts arriving cause stalls in everyone else's token stream. Which technique addresses this?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

vLLM documentation

vLLM project · Intermediate · Free

A widely used open-source LLM inference engine with paged KV cache, continuous batching and prefix caching.

Tool

SGLang

SGLang project (LMSYS and contributors) · Intermediate · Free

A fast open-source serving engine for LLMs and vision-language models, known for RadixAttention prefix caching and structured output.

Book

How To Scale Your Model

Google DeepMind · 2025 · Advanced · Free

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