Skip to content
English

Switch theme

Inference & Deployment

LLM Serving Engines: PagedAttention, Continuous Batching, Prefix Caching and Speculative Decoding

Advanced 35 min For: Developers

🖥️Self-hosted computeSelf-hosted software stack: drivers, CUDA, vLLM, SGLang, llama.cpp→

Key takeaways

  • ▸A serving engine is judged on three things: time to first token (TTFT), time per output token (TPOT) and throughput. Bigger batches raise throughput but slow each request; tuning is about finding the balance.
  • ▸PagedAttention splits the KV cache into fixed-size blocks allocated on demand, like OS paging. The paper found earlier systems used only 20.4%–38.2% of KV-cache memory for actual token state; vLLM bounds waste to under one block and improves throughput 2–4×.
  • ▸Continuous batching (Orca's iteration-level scheduling) lets requests join or leave the batch after every step; chunked prefill splits long prompts into chunks batched together with decodes, so a long prompt does not stall requests that are generating.
  • ▸Prefix caching lets requests that share an opening (system prompt, long document, chat history) reuse the KV cache, cutting prefill time only. vLLM implements it with block hashes; SGLang uses a radix tree (RadixAttention) with LRU eviction.
  • ▸Speculative decoding has a cheap draft guess several tokens that the large model verifies in one pass; the standard acceptance rule leaves the output distribution unchanged. EAGLE and Medusa replace the separate draft model with small heads, and gains are largest at low concurrency, when decoding is memory-bandwidth bound.

The short answer

A serving engine turns a large model into an API that many people can use at the same time. Its core problem: GPU memory is limited, and each request's KV cache is large and keeps growing, so how do you fit as many requests as possible into one batch while keeping everyone's wait short? Engines such as vLLM and SGLang answer with PagedAttention + continuous batching + prefix caching + speculative decoding. This lesson belongs to the Inference engines and serving unit; the prerequisite is How LLMs generate text (prefill, decode and the KV cache).

Step 1: Define "fast" — serving metrics

A single user only cares about tokens per second; a server has to watch latency and throughput together. The vLLM benchmarking docs define them as follows (measured on the client):

Metric Definition Mainly driven by
TTFT (time to first token) From sending the request to receiving the first streamed output Queueing + prefill (longer prompts are slower)
TPOT (time per output token) (end-to-end latency − TTFT) ÷ (output tokens − 1), computed per request Decode speed, number of requests in the batch
ITL (inter-token latency) Gap between consecutive streamed chunks Close to TPOT in normal decoding; differs with speculative decoding, which can emit several tokens at once
Throughput Requests completed per second, output tokens per second Batch size, how much KV cache fits in memory

The vLLM docs warn that benchmarking tools do not define these names consistently, so check where and how they are measured before comparing numbers. The DistServe paper also introduces goodput: the maximum request rate per GPU while meeting both TTFT and TPOT targets (SLOs) — closer to real serving capacity than peak throughput.

The batching trade-off. Every decode step reads all of the weights; serving several requests per read raises throughput, but each step does more work, so individual requests slow down. Here are the results measured for this lesson on an 8-core CPU with llama.cpp's llama-server (Qwen3-0.6B, Q4_K_M quantization, 4 parallel slots); the benchmark script is in Step 7:

Concurrency Median TTFT Median TPOT Output throughput
1 63 ms 10.8 ms 87 tok/s
4 194 ms 19.7 ms 185 tok/s

Going from 1 to 4 concurrent requests roughly doubled total throughput, but per-request TPOT also roughly doubled and TTFT rose about 3× (the machine was running other jobs, so the numbers fluctuate — look at the trend). GPU numbers are completely different, but the trade-off is the same: set the latency target first, then maximize throughput within it.

Step 2: PagedAttention — managing the KV cache like an operating system

The PagedAttention paper observed that existing systems reserved one contiguous chunk of memory per request, sized for the maximum possible length (for example 2,048 tokens). That causes three problems: space reserved for future tokens sits idle; actual outputs are shorter than the limit, causing internal fragmentation; and different reservation sizes cause external fragmentation. They measured that only 20.4%–38.2% of KV-cache memory in those systems actually held token state.

PagedAttention borrows virtual memory and paging from operating systems:

  • Each request's KV cache is split into fixed-size blocks (each holding the K and V of a few tokens). Blocks need not be contiguous; a block table maps logical blocks to physical blocks.
  • A new block is allocated only when the current one is full, so each request wastes less than one block; when a request finishes, its blocks go straight back to the pool.
  • When several outputs are sampled from the same prompt, the prompt's blocks are shared and copied only on write (copy-on-write).

The paper reports 2–4× higher throughput than FasterTransformer and Orca at the same latency, with larger gains for longer sequences, larger models and more complex decoding algorithms. Block size is a trade-off: too small underuses GPU parallelism, too large increases fragmentation and reduces sharing, so the paper sets the default block size to 16 tokens.

Step 3: Scheduling — continuous batching and chunked prefill

Continuous batching. The traditional approach runs a batch until every request in it finishes: early finishers cannot return, and new requests wait for the whole batch. Orca (OSDI '22) introduced iteration-level scheduling: the scheduler runs the model one step (one token) at a time, and after each step finished requests can leave and new ones can join. On GPT-3 175B the paper reports 36.9× the throughput of NVIDIA FasterTransformer at the same latency. Today's mainstream engines schedule this way by default.

Chunked prefill. Prefill processes a whole prompt at once — compute-saturated but slow; decode computes one token per step and underuses compute. Mixing them means a very long prompt makes requests that are generating stall. Sarathi-Serve splits long prompts into near-equal chunks and batches them with decode requests without pausing ongoing decodes; the paper reports 2.6× the serving capacity of vLLM for Mistral-7B on a single A100. The vLLM docs explain that the V1 engine enables chunked prefill whenever possible and schedules decode requests first, then fills the remaining max_num_batched_tokens budget with prefill: a small value (such as 2048) gives better ITL, a larger value better TTFT.

Preemption when memory runs out. When the KV cache cannot hold every request, vLLM preempts some and recomputes them later (RECOMPUTE is the V1 default). If preemption warnings appear often, the docs suggest raising gpu_memory_utilization, lowering max_num_seqs or max_num_batched_tokens, or using tensor parallelism to spread the weights across GPUs and free memory for the KV cache.

Step 4: Prefix caching — compute a shared opening once

Many requests start the same way: the same system prompt, the same long document, the history of a multi-turn chat. Prefix caching keeps the computed KV cache so a new request with the same opening can reuse it and skip that part of prefill.

  • vLLM's Automatic Prefix Caching (APC): the design doc explains that each KV block gets a hash built from the parent block's hash, the block's tokens and extra information (LoRA ID, image hashes, a cache salt for multi-tenant isolation); only full blocks are cached. Since v0.11 the default hash is sha256, lowering the risk of collisions. It is on by default in current versions.
  • SGLang's RadixAttention: the SGLang paper stores the prompts and outputs of all requests in a radix tree, evicting leaves first with an LRU policy; the cache and running requests share one memory pool. The scheduler sorts requests by matched prefix length and runs longer matches first (cache-aware scheduling), and the paper proves that, offline, visiting the radix tree in depth-first order achieves the optimal hit rate. It reports up to 6.4× higher throughput on agent control, few-shot, JSON decoding, RAG and multi-turn chat workloads.

Where the gains stop. The vLLM docs are explicit: prefix caching reduces prefill time only, not decode time, and helps little when answers are long or requests share no prefix. So when building applications, put fixed content at the start of the prompt and variable content at the end, or the cache will not hit.

Measured for this lesson with llama.cpp's llama-server (its cache_prompt is on by default; see the official docs): with a "product manual" of roughly 1,150 tokens as the system prompt, the first question had a TTFT of 1,457 ms and a different follow-up question only 118 ms; the server log shows the second request prefilled only 9 new tokens and reused the cache for the rest.

import time
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8080/v1", api_key="not-needed")
doc = "Product manual. " + "The product works offline, has a multilingual UI and automatic backups. " * 80

def ttft(question):
    t0 = time.perf_counter()
    stream = client.chat.completions.create(
        model="local", stream=True, max_tokens=8, temperature=0,
        messages=[{"role": "system", "content": doc},          # fixed content first
                  {"role": "user", "content": question}])      # variable content last
    first = None
    for chunk in stream:                                        # drain the stream before the next request
        d = chunk.choices[0].delta if chunk.choices else None
        if first is None and d and (d.content or getattr(d, "reasoning_content", None)):
            first = time.perf_counter()                         # thinking models stream reasoning first
    return (first - t0) * 1000

print(f"first:  {ttft('Does it work offline?'):.0f} ms")       # measured 1457 ms
print(f"second: {ttft('Does it back up automatically?'):.0f} ms")  # measured 118 ms, prefix cache hit

Step 5: Speculative decoding — let the large model verify several tokens at once

Decoding is memory-bandwidth bound: computing 1 token or checking 5 tokens in parallel takes about the same time for a large model. Speculative decoding (Leviathan et al., 2022; concurrently DeepMind's speculative sampling) exploits this:

  1. A cheap draft model guesses γ tokens in a row.
  2. The large model runs one forward pass, computing probabilities at all γ positions.
  3. Each draft token x is accepted with probability min(1, p(x)/q(x)) (p is the large model's distribution, q the draft's). At the first rejection, one token is resampled from norm(max(0, p − q)) and the remaining drafts are discarded.

Each round yields at least 1 and at most γ+1 tokens, and the output distribution is exactly the large model's. The paper defines the acceptance rate α = E[Σ min(p, q)]; each round yields (1 − α^(γ+1)) / (1 − α) tokens on average. The original paper measured 2–3× speedups on T5-XXL with identical outputs; speculative sampling sped up the 70B Chinchilla by 2–2.5×.

This NumPy snippet checks that the accept/reject rule does not change the distribution (run for this lesson):

import numpy as np
rng = np.random.default_rng(0)
p = np.array([0.40, 0.25, 0.15, 0.12, 0.08])   # large model's next-token distribution
q = np.array([0.20, 0.40, 0.20, 0.10, 0.10])   # draft distribution, deliberately off

def step():
    x = rng.choice(5, p=q)                       # draft guesses
    if rng.random() < min(1, p[x] / q[x]):       # accept with min(1, p/q)
        return x, True
    r = np.maximum(p - q, 0)                     # reject: resample from norm(max(0, p-q))
    return rng.choice(5, p=r / r.sum()), False

N = 200_000
xs, acc = zip(*(step() for _ in range(N)))
print(np.round(np.bincount(xs, minlength=5) / N, 3))   # [0.402 0.25 0.149 0.12 0.079] ≈ p
alpha = np.minimum(p, q).sum()
print(f"{np.mean(acc):.3f} {alpha:.3f}")                # 0.780 0.780: acceptance rate = Σmin(p,q)
print(f"{(1 - alpha**5) / (1 - alpha):.2f}")            # γ=4: 3.23 tokens per round on average

Variants without a separate draft model:

  • Medusa adds extra decoding heads to the large model to predict several future tokens at once, verifying multiple candidates in one pass with tree attention. Medusa-1 freezes the backbone and trains only the new heads, reporting over 2.2× speedup without quality loss; Medusa-2 trains them together with the backbone for 2.3–3.6×.
  • EAGLE autoregresses on second-to-top-layer features, also feeding in the token sequence advanced by one step to resolve uncertainty; on LLaMA2-Chat 70B it reports 2.7–3.5× lower latency and doubled throughput without changing the output distribution. EAGLE-2 uses a context-dependent dynamic draft tree for 3.05–4.26×; EAGLE-3 drops feature prediction, predicts tokens directly and fuses multi-layer features, reaching up to 6.5× and a 1.38× throughput gain at batch size 64 in SGLang.

Turning it on. vLLM takes JSON via --speculative-config, for example {"method": "eagle3", "model": "<draft weights>", "num_speculative_tokens": 2}, and also supports draft models, MTP, n-gram and other methods (vLLM docs). SGLang uses --speculative-algorithm EAGLE3 --speculative-draft-model-path ... --speculative-num-steps 3 --speculative-eagle-topk 4 --speculative-num-draft-tokens 16 (SGLang docs). Note how the vLLM docs position it: speculative decoding reduces inter-token latency at medium-to-low QPS in memory-bound workloads, and the gain shrinks at high concurrency. Draft weights must match the target model.

Step 6: Prefill/decode disaggregation

Prefill is compute-bound and decode is memory-bandwidth-bound; on the same GPUs they interfere. DistServe puts the two phases on different GPUs and picks resources and parallelism for each against TTFT and TPOT targets, reporting 7.4× more requests served, or 12.6× tighter SLOs, while meeting latency constraints for over 90% of requests. Microsoft's Splitwise puts the phases on different machines and reports 1.4× higher throughput at 20% lower cost.

There is an engineering cost: the KV cache has to move between machines, which needs fast interconnects. The vLLM docs say the feature is still experimental, that its value is tuning TTFT and ITL separately and controlling tail ITL, and that it does not improve throughput; chunked prefill with a well-chosen chunk size can achieve similar goals, though the chunk size is hard to tune. SGLang supports PD disaggregation with KV transfer over Mooncake or NIXL (docs).

Step 7: Deploy and load-test

vLLM (NVIDIA GPU; quickstart):

uv venv --python 3.12 --seed && source .venv/bin/activate
uv pip install vllm --torch-backend=auto
vllm serve Qwen/Qwen2.5-1.5B-Instruct            # listens on http://localhost:8000, OpenAI-compatible
# keys are checked only with --api-key; always set it before going live

# in another terminal: random data, 1024 input / 128 output tokens, max concurrency 16
vllm bench serve --backend vllm --model Qwen/Qwen2.5-1.5B-Instruct \
  --endpoint /v1/completions --dataset-name random \
  --random-input-len 1024 --random-output-len 128 \
  --num-prompts 200 --max-concurrency 16

The output reports request throughput, output-token throughput, and mean, median and P99 of TTFT, TPOT and ITL. --request-rate defaults to inf (all requests sent at once, measuring maximum throughput); with a finite value, arrivals follow a Poisson process, closer to real traffic. The vLLM docs also recommend GuideLLM for production benchmarking.

SGLang (quickstart, benchmarking guide):

uv pip install --prerelease=allow sglang
sglang serve Qwen/Qwen2.5-1.5B-Instruct --host 0.0.0.0 --port 30000
python3 -m sglang.bench_serving --backend sglang --host 127.0.0.1 --port 30000 \
  --dataset-name random --num-prompts 200 --max-concurrency 16

If memory runs short, lower --mem-fraction-static (the fraction of GPU memory for weights plus the KV-cache pool); --chunked-prefill-size sets the prefill chunk size; --disable-radix-cache turns RadixAttention off, which is handy for measuring what prefix caching buys you (server arguments).

The vLLM and SGLang commands above were checked against the official docs on 2026-10-25 but not run here (no GPU). You can practice benchmarking without a GPU: the script below measures TTFT, TPOT and throughput against any OpenAI-compatible server. For this lesson it ran against llama.cpp's llama-server -m Qwen3-0.6B-Q4_K_M.gguf -c 8192 -np 4 --port 8080, producing the table in Step 1 (with the Chinese prompt from the Chinese version of this lesson):

import asyncio, time, statistics
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="http://localhost:8080/v1", api_key="not-needed")

async def one(prompt, max_tokens=128):
    t0 = time.perf_counter(); first = None; n = 0
    stream = await client.chat.completions.create(
        model="local", stream=True, max_tokens=max_tokens, temperature=0,
        stream_options={"include_usage": True},          # last chunk carries token usage
        messages=[{"role": "user", "content": prompt}])
    async for chunk in stream:
        d = chunk.choices[0].delta if chunk.choices else None
        if d and (d.content or getattr(d, "reasoning_content", None)) and first is None:
            first = time.perf_counter()                   # first output arrives → TTFT
        if chunk.usage:
            n = chunk.usage.completion_tokens
    end = time.perf_counter()
    return first - t0, (end - first) / max(n - 1, 1), n   # TTFT, TPOT, output tokens

async def run(concurrency, total=16):
    sem = asyncio.Semaphore(concurrency)
    async def guarded(i):
        async with sem:
            return await one(f"Question {i}: explain the KV cache in three sentences.")
    t0 = time.perf_counter()
    res = await asyncio.gather(*(guarded(i) for i in range(total)))
    wall = time.perf_counter() - t0
    print(f"concurrency {concurrency}: median TTFT {statistics.median(r[0] for r in res)*1000:.0f} ms, "
          f"median TPOT {statistics.median(r[1] for r in res)*1000:.1f} ms, "
          f"throughput {sum(r[2] for r in res)/wall:.1f} tok/s")

for c in (1, 4):
    asyncio.run(run(c))

Note: in our test, setting -np 4 explicitly on llama-server split the -c 8192 context evenly across 4 slots, so each request could use at most 2,048 tokens and longer ones were rejected with an error; when -np is left at auto, the server defaults to one unified KV buffer shared by all slots (--kv-unified).

Choosing an engine

Scenario Common choice Notes
Datacenter GPUs, multi-user API vLLM, SGLang Both have PagedAttention-style block KV management, continuous batching, prefix caching, speculative decoding and an OpenAI-compatible API; decide after load-testing your own workload
Multi-turn chat, agents, lots of shared prefixes Test both, look closely at SGLang RadixAttention and cache-aware scheduling target exactly this
Personal computers, CPU, Apple silicon, small internal services llama.cpp, Ollama, MLX LM Quantized models, cross-platform; llama-server has parallel slots and a prompt cache but is not built for large-scale high concurrency. See Running LLMs on your own computer
One entry point for many providers, fallbacks, rate limits, cost tracking Put a model gateway in front of the engine See Model gateways, routing and cost control

Common pitfalls

Symptom Cause Fix
Great benchmark, slow in production Benchmark keeps hitting the prefix cache, or input/output lengths differ from real traffic Change the seed or restart the server; use realistic length distributions and arrival rates
Frequent "preempted" warnings in logs KV cache cannot hold current concurrency Raise gpu_memory_utilization, lower max_num_seqs, or use tensor parallelism
Other users' output stutters when a long prompt arrives Prefill interrupts decoding Make sure chunked prefill is on; lower max_num_batched_tokens
Low prefix-cache hit rate Timestamps, user names or other changing content at the start of the prompt Fixed content first, variable content last
Speculative decoding makes things slower High concurrency with compute saturated, or a mismatched draft with low acceptance Enable it for low-concurrency workloads; use the official matching EAGLE/MTP weights and watch the acceptance metrics
Strangers are calling your server Keys are not checked by default Use --api-key and put the server behind a gateway or reverse proxy

Try it yourself

  1. Get vLLM running: follow the vLLM quickstart to start an OpenAI-compatible server, run vllm bench serve at concurrency 1, 8 and 32, and plot throughput against TTFT.
  2. Compare prefix caching: on SGLang, run the same workload twice (default and --disable-radix-cache) where 80% of requests share a 2,000-token system prompt, and compare TTFT.
  3. No GPU: run the benchmark script above against llama.cpp's llama-server and change -np to see how throughput and latency move.
  4. Unit project: deploy a 7B/8B open model, measure throughput and P99 TTFT at concurrency 1–64, then enable speculative decoding (EAGLE-3 or n-gram), compare low and high concurrency, and write down when it is worth turning on.

Related algorithm cards: PagedAttention, Continuous batching, RadixAttention prefix caching, Speculative decoding, Medusa, EAGLE, Prefill/decode disaggregation.

FAQ

Should I choose vLLM or SGLang?

Both support continuous batching, prefix caching, speculative decoding, an OpenAI-compatible API and prefill/decode disaggregation, so their features overlap heavily. The reliable way to decide is to load-test both on the same GPU with your own model, real prompt lengths and concurrency. SGLang's RadixAttention and cache-aware scheduling are the core of its paper, so compare closely for multi-turn chat, agents and workloads with long shared prefixes.

My benchmark showed low TTFT and high throughput, but production is much slower. Why?

A common cause is the benchmark repeatedly hitting the prefix cache. The vLLM docs warn that running vllm bench serve repeatedly against the same server can reuse cached prompts and inflate throughput; the random dataset is reproducible with a fixed --seed, so change the seed, restart the server, or use the sweep mode that resets the cache. Input and output lengths should also match your real traffic.

Does speculative decoding always speed things up?

No. It trades extra compute for fewer sequential steps, and the gain depends on how many draft tokens are accepted. The vLLM docs position it as a way to reduce inter-token latency at medium-to-low QPS in memory-bound workloads; at high concurrency, when GPU compute is saturated, the gain shrinks or can turn negative.

Do I need prefill/decode (PD) disaggregation?

Most single-node, small deployments do not. Its value is tuning TTFT and TPOT separately and controlling tail latency; the vLLM docs state plainly that it does not improve throughput and that the feature is still experimental. Get chunked prefill right first, and consider disaggregation at large scale with strict latency targets.

Software used in this lesson

Related AI news

Links go to the original publishers.

Sources & further reading

  1. Kwon et al. (2023), Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM)
  2. Yu et al. (2022), Orca: A Distributed Serving System for Transformer-Based Generative Models (OSDI '22)
  3. Zheng et al. (2023), SGLang: Efficient Execution of Structured Language Model Programs (RadixAttention)
  4. Agrawal et al. (2024), Taming Throughput-Latency Tradeoff in LLM Inference with Sarathi-Serve (chunked prefill)
  5. Leviathan et al. (2022), Fast Inference from Transformers via Speculative Decoding
  6. Chen et al. (2023), Accelerating Large Language Model Decoding with Speculative Sampling
  7. Cai et al. (2024), Medusa: Simple LLM Inference Acceleration Framework with Multiple Decoding Heads
  8. Li et al. (2024), EAGLE: Speculative Sampling Requires Rethinking Feature Uncertainty
  9. Li et al. (2024), EAGLE-2: Faster Inference of Language Models with Dynamic Draft Trees
  10. Li et al. (2025), EAGLE-3: Scaling up Inference Acceleration of Large Language Models via Training-Time Test
  11. Zhong et al. (2024), DistServe: Disaggregating Prefill and Decoding for Goodput-optimized LLM Serving
  12. Patel et al. (2023), Splitwise: Efficient generative LLM inference using phase splitting
  13. vLLM docs: Quickstart
  14. vLLM docs: Automatic Prefix Caching
  15. vLLM docs: Automatic Prefix Caching (design)
  16. vLLM docs: Optimization and Tuning (preemption, chunked prefill, parallelism)
  17. vLLM docs: Speculative Decoding
  18. vLLM docs: Disaggregated Prefilling
  19. vLLM docs: Benchmark CLI (vllm bench serve and latency metric definitions)
  20. SGLang docs: Quick Start
  21. SGLang docs: Server Arguments
  22. SGLang docs: Speculative Decoding
  23. SGLang docs: PD Disaggregation
  24. SGLang docs: Bench Serving Guide
  25. vllm-project/vllm (official code)
  26. sgl-project/sglang (official code)
  27. SafeAILab/EAGLE (official EAGLE implementation)
  28. llama.cpp docs: llama-server (parallel slots, prompt cache)
  29. Hugging Face blog: Assisted Generation

Part of these paths

Data updated: Learn AI curriculum · Lesson news(UTC+8)