Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Inference and servingAI guideIntermediate#inference#vllm#pagedattention#batching
Frame · ai-engineering / inference-serving / 03-pagedattention-and-continuous-batching.mdGuide 062 / 103

PagedAttention and continuous batching

Before 2023, most LLM servers wasted a large share of GPU memory and spent a lot of time waiting for the slowest request in a batch to finish. Two ideas fixed that: continuous batching (from the Orca paper) changed when requests join and leave a batch, and PagedAttention (from the vLLM paper) changed how their KV caches are stored. Every serious engine now uses both, so it is worth understanding them properly, especially when you are tuning memory flags or debugging preemptions.

Why it matters

Recall from how inference works that decode is memory-bandwidth bound and that batching many sequences together amortises the cost of streaming the weights. The more sequences you can fit in a batch, the more tokens per second you get from the same GPU. Two things limit that:

  1. Memory fragmentation. Early servers reserved a contiguous KV buffer for each request sized to its maximum possible length. A request that might generate 4,000 tokens but stops after 200 wastes most of its reservation. The vLLM paper measured large amounts of wasted KV memory in existing systems from exactly this kind of over-reservation and fragmentation.
  2. Static batching. If you batch eight requests and wait for all eight to finish, the batch runs as long as its longest member. Short requests sit idle in finished slots, and new arrivals wait outside.

Fix both and you can serve several times more concurrent users on the same hardware. That is not a micro-optimisation; it is the difference between a viable product and an unaffordable one.

How it works

Continuous batching

Continuous (or "in-flight", or iteration-level) batching makes the scheduling decision every decode step instead of every batch. At each step the scheduler:

  • removes sequences that just emitted a stop token or hit max_tokens,
  • admits waiting requests if there is KV memory for them, running their prefill (often in chunks),
  • runs one forward pass over everything active.

The batch is a revolving door. A short request leaves after a few steps and its slot is reused immediately.

Rendering diagram…

Chunked prefill is the companion technique: a long prompt is split into chunks processed across several steps, mixed in with other sequences' decode tokens, so a single giant prompt does not freeze every other user's stream. vLLM's V1 engine enables it by default.

PagedAttention

PagedAttention borrows the operating system idea of virtual memory. The KV cache is divided into fixed-size blocks, each holding the keys and values for a small number of tokens (vLLM's default block size is 16 tokens). Each sequence has a block table that maps its logical token positions to physical blocks anywhere in GPU memory. The attention kernel follows the block table instead of assuming contiguous memory.

Consequences:

  • Allocation is on demand. A sequence takes a new block only when it fills its current one, so waste is limited to the last partially full block.
  • Blocks can be shared. Two sequences with the same prefix (a shared system prompt, or parallel samples from one prompt) can point at the same physical blocks, with copy-on-write when they diverge. This is the foundation of automatic prefix caching.
  • Preemption is possible. Under memory pressure the scheduler can evict a sequence's blocks (recompute later, or swap to CPU) and resume it, rather than crashing with out-of-memory.
Rendering diagram…

Reference architecture

In vLLM, at startup the engine loads weights, runs a profiling pass to see how much memory activations need, and then hands a fraction of the remaining GPU memory to the block pool. That fraction is controlled by --gpu-memory-utilization. The number of blocks, divided by blocks per sequence, sets your real concurrency ceiling. The engine logs how many tokens of KV cache it could allocate and the implied maximum concurrency at your --max-model-len, which is the single most useful line to read on startup.

Rendering diagram…

Code

The knobs you actually touch in vLLM are few. This is a reasonable starting point for a single 7B to 8B model on one GPU.

vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --gpu-memory-utilization 0.90 \
  --max-model-len 16384 \
  --max-num-seqs 128 \
  --max-num-batched-tokens 8192 \
  --enable-prefix-caching
  • --gpu-memory-utilization: share of GPU memory vLLM may use for weights, activations and KV blocks.
  • --max-model-len: longest context you accept. Lowering it does not shrink the pool, but it caps how much one sequence can take and makes the concurrency estimate honest.
  • --max-num-seqs: upper bound on sequences in a batch.
  • --max-num-batched-tokens: token budget per step, which controls how big prefill chunks are relative to decode work.

To watch the effect, scrape the Prometheus endpoint at /metrics and look at the KV cache usage gauge, the running and waiting request gauges, and the preemption counter. Names have changed between releases, so check the metrics page for your version.

Trade-offs and pitfalls

  • Bigger batches, slower streams. Pushing --max-num-seqs up raises total throughput but each user's inter-token latency rises. Set it from your latency target, not from the maximum the memory allows.
  • Preemption is a symptom. Occasional preemption is fine. Constant preemption means you are recomputing work; lower concurrency, shorten --max-model-len, or add GPUs.
  • Prefill chunk size is a latency dial. Larger per-step token budgets improve TTFT for long prompts but make the decode streams of other users stutter during big prefills. Smaller budgets do the opposite.
  • Memory utilisation too high crashes on spikes. Leaving no headroom can cause out-of-memory errors when activations spike or when other processes share the GPU.
  • Prefix caching needs identical prefixes. A timestamp or user id at the top of the system prompt defeats block sharing. Put dynamic content last.

Checklist

  • I read the startup log line for KV cache capacity and maximum concurrency.
  • I set --max-model-len to what my product needs, not the model's maximum.
  • I chose --max-num-seqs from a latency target, verified with a load test.
  • I alert on sustained preemptions and on waiting-queue growth.
  • Prefix caching is on and my prompts put static content first.
  • I re-check these settings when I change model, quantization or GPU.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.