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:
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.

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

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.

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.

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)

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.

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.
Related Posts
- KV Cache Memory: Sizing LLM Inference: The single-request KV-cache problem that serving has to manage at scale.
- Shrinking the KV Cache: MQA, GQA, and Multi-Head Latent Attention: Making each request's cache smaller, complementary to packing more of them in.
- Parallel LLM Decoding: Speculative and Diffusion: Another angle on decode throughput, at the algorithm level rather than the scheduler.
- Mixture of Experts in LLMs: From Switch to DeepSeek-V3: Serving conditional compute, where routing adds its own scheduling wrinkle.
- On-Policy Distillation: When Self-Generated Data Wins: Generating training data at scale leans on exactly this serving throughput.
- Structured Output from LLMs: Constrained JSON Decoding: Guided decoding is the workload that fights this scheduler, because requests in one batch sit at different automaton states.
- Four Multi-Agent Orchestration Patterns in Python: A fan-out of agent calls that becomes slower than a sequential chain once concurrency is capped at two.







