LLM Serving: Continuous Batching & PagedAttention

How vLLM serves hundreds of LLM requests at once: build continuous batching and a paged KV cache from scratch and watch GPU utilisation and throughput jump.

Cover Image for LLM Serving: Continuous Batching & PagedAttention

Two people send requests to the same language model. One wants a short answer; the other asks for a long explanation. If the server makes their requests wait for each other, available compute can sit unused while users are still waiting. LLM serving has to manage these uneven arrivals and answer lengths, as well as the growing KV cache that stores each request's history.

Letting requests enter and leave independently triples throughput in our simulation. Mean latency falls from 2,810 steps to 791. We build scheduling and cache blocks alongside methods for shrinking the cache, tracing iteration-level scheduling from Orca in 2022 and PagedAttention from vLLM in 2023.

Let's Build It

Click the badge to open the full, runnable notebook in Google Colab:

Open In Colab

Decoding runs one token per step for every sequence in the batch. We simulate that clock and schedule a stream of 300 requests two ways: static batching (run a whole batch to completion, then start the next) and continuous batching (evict finished sequences and admit new ones every step). The animation shows each GPU batch slot over time; white is a wasted slot.

Two stacked timelines of 32 GPU batch slots over decode steps. Static batching drains after each batch and leaves large white idle regions while a few long requests finish; continuous batching stays densely packed.

import numpy as np

def make_workload(n, seed=0, short_frac=0.7, short=(8, 40), long=(200, 700)):
    """A bimodal request stream: mostly short generations, a few very long ones."""
    rng = np.random.default_rng(seed)
    is_short = rng.random(n) < short_frac
    out_len = np.where(is_short, rng.integers(*short, n), rng.integers(*long, n))
    return out_len.astype(int), np.zeros(n, int)      # (output lengths, arrival = burst)

def simulate_static(out_len, arrival, slots):
    """Run a full batch of `slots` requests until its LONGEST finishes, then the next."""
    order = np.argsort(arrival, kind="stable")
    completion, active, t, i = np.zeros(len(out_len), int), [], 0, 0
    while i < len(out_len):
        if arrival[order[i]] > t: t = arrival[order[i]]
        batch = []
        while len(batch) < slots and i < len(out_len) and arrival[order[i]] <= t:
            batch.append(order[i]); i += 1
        rem = out_len[batch]
        for step in range(rem.max()):
            active.append(int((rem > step).sum()))     # slots still generating
        for r in batch: completion[r] = t + out_len[r]
        t += rem.max()                                 # slot reused only after full drain
    return completion, np.array(active)

def simulate_continuous(out_len, arrival, slots):
    """Every step: evict finished sequences, admit waiting ones into freed slots."""
    order = list(np.argsort(arrival, kind="stable"))
    completion, active, trace, nxt, t = np.zeros(len(out_len), int), [], [], 0, 0
    while nxt < len(out_len) or active:
        while len(active) < slots and nxt < len(out_len) and arrival[order[nxt]] <= t:
            active.append([order[nxt], out_len[order[nxt]]]); nxt += 1
        if not active: t = arrival[order[nxt]]; continue
        trace.append(len(active))
        for a in active: a[1] -= 1
        for a in active:
            if a[1] == 0: completion[a[0]] = t + 1
        active = [a for a in active if a[1] > 0]; t += 1
    return completion, np.array(trace)

out_len, arrival = make_workload(300)
for name, sim in [("static", simulate_static), ("continuous", simulate_continuous)]:
    completion, active = sim(out_len, arrival, slots=32)
    util = active.mean() / 32
    print(f"{name:>11}: utilisation {util*100:4.0f}%   makespan {len(active)} steps")
# static: utilisation 27%, makespan 6372 | continuous: utilisation 80%, makespan 2154

The occupancy timeline as a static figure: static batching sits at 27 percent utilisation with long idle stretches, continuous batching at 80 percent with slots refilling continuously.

Same hardware, same requests, same model. Continuous batching lifts GPU utilisation from 27% to 80% and clears the whole queue in a third of the time, purely by scheduling smarter. No idle slot goes to waste while another request is waiting.

What Just Happened?

To see why the scheduler matters so much, you have to split inference into its two phases, because they stress the GPU in opposite ways.

Prefill and decode

Prefill processes the whole prompt in one parallel pass: a big matrix multiply over every prompt token at once. It is compute-bound, the GPU's arithmetic units are the bottleneck. Decode then generates the answer one token at a time, and each step must read the entire model's weights from memory to produce a single token. Decode is memory-bandwidth-bound: the GPU spends its time moving weights, not computing.

A schematic contrasting prefill, where all prompt tokens feed one parallel pass labelled compute-bound, with decode, where each step reads the full weights W again to emit one token, labelled memory-bandwidth-bound.

Decode being bandwidth-bound is the reason batching works at all. A decode step reads the weights once, so if 32 sequences share that step, they all ride on the same weight read. Thirty-two sequences per step is close to thirty-two times the throughput at nearly the same per-step latency. Every occupied slot is almost free; every empty slot is pure waste. That connects to the same memory-bandwidth story behind the KV cache and the tricks that shrink it.

Why static batching wastes the GPU

Static batching commits to a batch and runs it to completion. In our workload one batch might hold thirty-one short requests and one long one. The thirty-one finish in a few dozen steps, then sit as dead slots for hundreds more while the straggler generates, because their slots cannot be reused until the whole batch drains. Worse, any request that arrives mid-batch waits in line for the entire batch to finish first, a queueing delay called head-of-line blocking.

Continuous batching fixes both with one change: schedule at the level of a single decode step, not a whole batch. After every step it evicts sequences that just emitted their last token and admits waiting requests into the freed slots. The batch is now a living set that changes composition every step, so the GPU stays full as long as there is work to do.

Going Deeper

Throughput, latency, and the metrics that matter

The scheduler is a throughput-versus-latency lever. Plotting utilisation over the whole run shows the mechanism: static batching sawtooths, ramping down as each batch drains, while continuous batching holds near full until the backlog clears.

Left: GPU utilisation over the run, a sawtooth for static batching versus a sustained high line for continuous. Right: mean latency falls from 2810 to 791 steps and p95 latency from 5693 to 1689 steps.

On this workload continuous batching delivers about 3x the throughput and cuts mean latency from 2810 steps to 791, with the tail (p95) dropping from 5693 to 1689. Production serving is judged on a handful of numbers worth knowing: TTFT (time to first token, dominated by prefill and queueing), TPOT (time per output token, the decode step time), and goodput (requests per second that meet a latency target, not raw throughput). Continuous batching improves all of them at once because it stops wasting decode steps.

The KV cache fragments, and paging fixes it

Higher utilisation only helps if you can fit those sequences in memory, and the KV cache is the constraint. Each sequence needs KV memory proportional to its length, and that length grows token by token as it generates. Early serving systems allocated one contiguous block per request, sized for the maximum length the request might reach, because a sequence cannot safely grow into a neighbour's memory. That reserves far more than most requests use.

def contiguous_capacity(seq_lens, max_len, capacity):
    """Reserve a max-length contiguous slab per request."""
    n_fit = min(capacity // max_len, len(seq_lens))
    used = int(seq_lens[:n_fit].sum())
    return n_fit, used / capacity                      # requests that fit, utilisation

def paged_capacity(seq_lens, capacity, block=16):
    """PagedAttention: grab fixed-size blocks from a shared pool on demand."""
    total_blocks, used_blocks, used, n_fit = capacity // block, 0, 0, 0
    for L in seq_lens:
        need = int(np.ceil(L / block))
        if used_blocks + need > total_blocks: break
        used_blocks += need; used += int(L); n_fit += 1
    return n_fit, used / capacity

lens = np.random.default_rng(1).integers(20, 256, size=400)   # actual lengths << max
print(contiguous_capacity(lens, max_len=512, capacity=16384))  # (32, 0.27)
print(paged_capacity(lens, capacity=16384))                    # (111, 0.95)

Left: a memory map of the same KV budget, contiguous allocation showing 32 mostly-empty reserved slabs at 27 percent used, paged allocation tightly packed at 95 percent. Right: bars showing 32 versus 111 concurrent requests and 27 versus 95 percent utilisation.

PagedAttention treats the KV cache the way an operating system treats RAM. The cache is a pool of fixed-size blocks (16 tokens here), and a sequence grabs blocks on demand as it grows. A request now wastes at most one partially filled block, and because any free block fits any sequence, the external fragmentation that stranded contiguous memory disappears. In the same budget, paging fits 3.5x more concurrent requests and lifts memory utilisation from 27% to 95%. Paging also enables copy-on-write: two requests that share a prompt prefix (a common system prompt, a few-shot example) can share the same physical blocks until one of them diverges, the same idea as prefix reuse in decoding.

What the simulator leaves out

This is a scheduler and an allocator, not a GPU. The model assumes every decode step costs the same wall-time regardless of batch size, which holds while decode is bandwidth-bound but breaks once a batch grows large enough to become compute-bound. It also ignores the contention between prefill and decode: a long prompt's prefill can stall every ongoing decode, which is the problem chunked prefill (Sarathi-Serve) addresses by slicing prefill into decode-sized pieces. Reach for vLLM or SGLang for the real thing; the point here is to make the two core ideas concrete, not to replace them. The same "throughput from systems, not new weights" theme runs through serving mixtures of experts and on-policy distillation.

Where This Comes From

Serving throughput improved by an order of magnitude in two years, and the papers behind it are about scheduling and memory, not architecture.

A timeline from static batching (run a batch to completion) to Orca 2022 (continuous, iteration-level batching) to vLLM 2023 (PagedAttention, paged KV cache) to Sarathi-Serve 2024 (chunked prefill, stall-free decode).

Yu et al. (2022), "Orca: A Distributed Serving System for Transformer-Based Generative Models", introduced iteration-level scheduling. Their framing names the waste we reproduced:

"Existing systems process the batch of requests until completion. This can cause requests to wait for the completion of the entire batch, resulting in increased latency and low resource utilization."

Orca schedules one iteration at a time and returns finished sequences immediately, which is continuous batching.

Kwon et al. (2023), "Efficient Memory Management for LLM Serving with PagedAttention", the vLLM paper, brought virtual-memory paging to the KV cache. They measured that existing systems wasted 60% to 80% of KV memory to fragmentation and over-reservation, and showed paging recovers nearly all of it:

"PagedAttention divides the KV cache into blocks... allowing near-zero waste in KV cache memory."

The result was 2 to 4 times the throughput of the systems before it. Pope et al. (2022) laid the analytical groundwork in "Efficiently Scaling Transformer Inference" (the prefill-versus-decode, compute-versus-bandwidth analysis), and Agrawal et al. (2024), Sarathi-Serve, added chunked prefill to stop long prompts from stalling ongoing decodes. The through-line: the biggest serving wins came from treating an LLM server as a scheduling and memory-management problem, the kind of problem operating systems solved decades ago.

Interactive Tools

  • LLM Cost Calculator: Serving efficiency is cost: higher utilisation and more concurrent requests per GPU are exactly what move the per-token price.
  • Markov Chain Simulator: A request scheduler is a state machine over a queue; simulate how arrivals and service times drive occupancy.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions