On this page
A shared code-assistant GPU receives three requests at once: a one-line completion (A, 10 decode steps), a failing-test explanation (B, 50 steps), and a migration plan (C, 200 steps). More work is queued behind them. Under static batching, A finishes at step 10 and B at step 50, yet both seats stay idle until C ends at step 200.
FlashAttention speeds up a single attention kernel; it never decides who shares the next forward pass. Continuous batching (iteration-level scheduling, introduced in Orca) rebuilds the active batch after every token step.[1][2] As soon as A retires at step 10, queued request D takes its seat at step 11. As soon as B retires at step 50, E takes its seat at step 51.

Why autoregressive batches break static scheduling
Unlike image classifiers with fixed inputs and one forward pass, autoregressive LLMs have two properties that defeat static batching:
- Two distinct phases: Prefill reads all prompt tokens in parallel (compute-heavy, governing Time To First Token, TTFT). Decode emits one token per step (memory-bandwidth-bound at small batches, governing inter-token latency ITL and average TPOT).
- Unknown output lengths: Generation stops on EOS or
max_tokens, so the scheduler cannot pack equal-length jobs in advance.
import numpy as np
remaining = np.array([10, 50, 200], dtype=np.int64)
static_capacity = int(remaining.max()) * remaining.size
useful = int(remaining.sum())
print(f"useful seat-steps: {useful} / {static_capacity} ({useful / static_capacity:.1%})")
print(f"idle seat-steps: {static_capacity - useful}")useful seat-steps: 260 / 600 (43.3%)
idle seat-steps: 340The throughput, latency, cost triangle
Why not pack as many concurrent streams into a continuous batch as VRAM allows? Because every extra active stream adds its own KV cache to the bytes read on every decode step. Bigger batches amortize model weight reads, raising aggregate throughput and cutting dollar cost per million tokens, while simultaneously lengthening each step.
Watch the math for Llama 3 8B FP16 (16 GB weights, 32 layers, 8 GQA KV heads, head dim 128) serving 4,096-token streams on an H100 SXM (3.35 TB/s peak bandwidth). Each token holds of KV state, so one 4K stream adds 0.50 GiB (0.537 decimal GB) per decode step:
import numpy as np
weight_bytes = 16_000_000_000.0
kv_per_req = float(2 * 4096 * 32 * 8 * 128 * 2) # 8B FP16, 4K context (0.50 GiB)
peak_bw = 3.35e12
linear_flops = 2 * 8_000_000_000.0
batches = np.array([1, 8, 32, 64], dtype=np.float64)
bytes_read = weight_bytes + batches * kv_per_req
step_sec = bytes_read / peak_bw
intensities = batches * linear_flops / bytes_read
for b, s, inten in zip(batches.astype(int), step_sec, intensities):
print(f"B={b:>2}: floor={s * 1000:5.2f} ms, agg={b / s:6.1f} tok/s, intensity={inten:4.1f} FLOPs/byte")
for tps in (2_500, 250):
cost_per_m = 3.00 / (tps * 3600) * 1_000_000
print(f"At {tps:>4} sustained tok/s ($3.00/hr GPU) -> ${cost_per_m:.2f} / 1M tokens")B= 1: floor= 4.94 ms, agg= 202.6 tok/s, intensity= 1.0 FLOPs/byte
B= 8: floor= 6.06 ms, agg=1320.5 tok/s, intensity= 6.3 FLOPs/byte
B=32: floor= 9.90 ms, agg=3230.9 tok/s, intensity=15.4 FLOPs/byte
B=64: floor=15.03 ms, agg=4257.4 tok/s, intensity=20.3 FLOPs/byte
At 2500 sustained tok/s ($3.00/hr GPU) -> $0.33 / 1M tokens
At 250 sustained tok/s ($3.00/hr GPU) -> $3.33 / 1M tokensScaling from to multiplies aggregate throughput 21x, yet KV traffic triples the per-step bandwidth floor from 4.94 ms to 15.03 ms and caps linear arithmetic intensity at 20.3 FLOPs/byte. That 10x gap between $0.33 and $3.33 per million tokens at $3.00/hr GPU rent is the core serving trade-off: interactive chat caps batch size to protect p95 ITL, whereas offline batch pipelines saturate the KV pool to minimize unit cost.
Sizing an 8B replica end-to-end
Now partition one 80 GB card () into weights, runtime activations, and the KV pool:
Subtracting 14.90 GiB for 8B FP16 weights and an 8.00 GiB activation/runtime reserve leaves 51.60 GiB for KV. At 0.50 GiB per 4,096-token prompt, a naive snapshot fits streams. Live requests also generate tokens: reserving 512 output positions (4,608 total = 0.5625 GiB) drops the safe ceiling to 91 concurrent requests. With PagedAttention 16-token blocks, each sequence rounds up individually to whole blocks, eliminating contiguous-allocation external fragmentation while leaving up to 15 unused tail-block slots per request:[2]

import math
BYTES_PER_TOK = 2 * 32 * 8 * 128 * 2 # 128 KiB/token (Llama 3 8B FP16)
BLOCK = 16
device_gib = 80_000_000_000 / 1024**3
weight_gib = 16_000_000_000 / 1024**3
kv_pool_gib = device_gib - weight_gib - 8.0
raw_4k = math.floor(kv_pool_gib / (4096 * BYTES_PER_TOK / 1024**3))
with_512_out = math.floor(kv_pool_gib / ((4096 + 512) * BYTES_PER_TOK / 1024**3))
print(f"KV pool: {kv_pool_gib:.2f} GiB -> {raw_4k} raw 4K streams, {with_512_out} with 512-token headroom")
prompts = [4090, 4096, 4100]
reserved_slots = [((p + 512 + BLOCK - 1) // BLOCK) * BLOCK for p in prompts]
actual_slots = [p + 512 for p in prompts]
print("Reserved slots per request:", reserved_slots)
print("Unused tail-block slots: ", sum(reserved_slots) - sum(actual_slots))KV pool: 51.60 GiB -> 103 raw 4K streams, 91 with 512-token headroom
Reserved slots per request: [4608, 4608, 4624]
Unused tail-block slots: 18Note that hybrid architectures store KV only in their full-attention layers: Qwen3.6-27B has 64 layers, but 48 use Gated DeltaNet and only 16 use full attention (4 KV heads, head dim 256, FP16), giving 64 KiB/token (0.25 GiB at 4K) plus separate recurrent state.[3]
The iteration-level scheduling loop
Modern engines cap three independent limits on every step: active sequences (max_num_seqs), per-step token budget (max_num_batched_tokens), and KV-block capacity. One 4,000-token prefill consumes far more compute than 96 single-token decodes, so request count alone misstates GPU load.
Suppose 96 decode streams are active and a 1,800-token prompt arrives under max_num_batched_tokens = 1024. Decode-first scheduling reserves 96 positions for live streams and hands the remaining 928 positions to a prefill chunk, leaving 872 prompt tokens for the next iteration:
Scheduling policies and preemption
Every policy trades throughput against fairness:
- FCFS: Simple and arrival-ordered, but suffers head-of-line blocking when an oversized prompt stalls behind insufficient KV blocks. Scanning past the head fills idle blocks immediately, yet a steady stream of small requests can starve the large request unless you age waiting work or reserve freeing blocks.[4]
- SJF: Minimizes average completion time on an idealized serial worker when lengths are known, but LLM output lengths are unknown up front (
max_tokensis a poor proxy) and batch step times depend on co-scheduled neighbors. - Decode-first & priority: Protects interactive ITL by serving active streams before new prefills, backed by aging or reserved prefill slots so new prompts never starve. Note engine conventions: vLLM V1's
--scheduling-policy priorityserves smaller numeric priority values first.[5][6]
When growing streams exhaust the KV-block pool mid-generation, the scheduler must preempt a victim before launching the next forward pass:

Two recovery paths exist: Recompute drops the victim's KV and replays its token history when space opens (default in vLLM V1; simple, no PCIe copy, costs GPU compute), while Swap-out copies KV to CPU RAM and back (preserves progress for long histories, costs host-device bandwidth).[7][8]
from dataclasses import dataclass
@dataclass
class Request:
id: str
prompt_len: int
max_new_tokens: int
priority: int = 0 # Higher value = higher priority
generated_tokens: int = 0
allocated_blocks: int = 0
swapped_to_cpu: bool = False
canceled: bool = False
eos: bool = False
@property
def total_tokens(self) -> int:
return self.prompt_len + self.generated_tokens
def is_finished(self) -> bool:
return self.canceled or self.eos or self.generated_tokens >= self.max_new_tokens
class ContinuousBatchScheduler:
BLOCK_SIZE = 16
def __init__(self, max_batch_size: int, max_memory_blocks: int):
self.max_batch_size = max_batch_size
self.max_memory_blocks = max_memory_blocks
self.running: list[Request] = []
self.waiting: list[Request] = []
self.swapped: list[Request] = []
self.used_blocks = 0
self.preemptions = 0
def _blocks(self, tokens: int) -> int:
return (tokens + self.BLOCK_SIZE - 1) // self.BLOCK_SIZE
def submit(self, req: Request) -> None:
if self._blocks(req.prompt_len + req.max_new_tokens) > self.max_memory_blocks:
raise ValueError("request cannot finish within KV capacity")
self.waiting.append(req)
def _admit(self, queue: list[Request]) -> None:
queue.sort(key=lambda r: r.priority, reverse=True)
while queue and len(self.running) < self.max_batch_size:
needed = self._blocks(queue[0].total_tokens)
if self.used_blocks + needed > self.max_memory_blocks:
break
req = queue.pop(0)
req.allocated_blocks = needed
self.used_blocks += needed
req.swapped_to_cpu = False
self.running.append(req)
def schedule_step(self) -> list[Request]:
# 1. Retire finished/canceled streams and free exclusively owned KV.
active = []
for req in self.running:
if req.is_finished():
self.used_blocks -= req.allocated_blocks
req.allocated_blocks = 0
else:
active.append(req)
self.running = active
# 2. Resume paused work first, then admit waiting work.
self._admit(self.swapped)
self._admit(self.waiting)
# 3. Preempt lowest-priority victim if next decode token exceeds KV budget.
while self.running:
growth = sum(
max(0, self._blocks(r.total_tokens + 1) - r.allocated_blocks)
for r in self.running
)
if self.used_blocks + growth <= self.max_memory_blocks:
break
victim = min(self.running, key=lambda r: (r.priority, r.generated_tokens))
self.running.remove(victim)
self.used_blocks -= victim.allocated_blocks
victim.allocated_blocks = 0
victim.swapped_to_cpu = True
self.swapped.append(victim)
self.preemptions += 1
for r in self.running:
g = max(0, self._blocks(r.total_tokens + 1) - r.allocated_blocks)
r.allocated_blocks += g
self.used_blocks += g
return list(self.running)
def finish_decode_step(self) -> None:
for r in self.running:
r.generated_tokens += 1
# Trace 1: Refill seats immediately as requests finish.
sched = ContinuousBatchScheduler(max_batch_size=3, max_memory_blocks=16)
for r in [
Request("req_A", 8, 3), Request("req_B", 8, 1), Request("req_C", 8, 2),
Request("req_D", 8, 2), Request("req_E", 8, 1),
]:
sched.submit(r)
timeline = []
for _ in range(3):
timeline.append([r.id for r in sched.schedule_step()])
sched.finish_decode_step()
print("refill timeline:", timeline)
assert timeline == [["req_A", "req_B", "req_C"], ["req_A", "req_C", "req_D"], ["req_A", "req_D", "req_E"]]
# Trace 2: Tight 2-block budget triggers priority preemption before decode.
pressure = ContinuousBatchScheduler(max_batch_size=2, max_memory_blocks=2)
pressure.submit(Request("urgent", 16, 2, priority=1))
pressure.submit(Request("background", 16, 2, priority=0))
active = pressure.schedule_step()
print("under KV pressure:", [r.id for r in active], f"preemptions={pressure.preemptions}")
assert [r.id for r in active] == ["urgent"] and pressure.preemptions == 1refill timeline: [['req_A', 'req_B', 'req_C'], ['req_A', 'req_C', 'req_D'], ['req_A', 'req_D', 'req_E']]
under KV pressure: ['urgent'] preemptions=1When recomputing a preempted request, separate accepted client outputs from computed KV positions. Suppose prompt [101, 102, 103] has already emitted [201, 202]; the KV cache held [101, 102, 103, 201] because 202 was just sampled. On resume, silently replay [101, 102, 103, 201] to rebuild KV state without sampling or streaming, then feed 202 as the next decode input.

Chunked prefill and disaggregated serving
Running a monolithic 4,000-token prefill alongside 96 live decode streams stalls every stream's ITL until the full prompt finishes. Chunked prefill (SARATHI / Sarathi-Serve, enabled by default in vLLM V1) slices long prompts into bounded chunks (for example 512 tokens) and co-batches each slice with ongoing decodes under .[9][10][7]

Smaller chunks smooth ITL at the cost of extra kernel launches and slightly longer TTFT; larger chunks favor prompt throughput.
When one shared GPU still cannot satisfy both tight TTFT and tight ITL under heavy prompts, disaggregated serving (Splitwise, DistServe) splits prefill and decode onto separate worker pools.[11][12] That eliminates cross-phase interference but introduces a KV state handoff on the critical path:

Serialization alone makes interconnect bandwidth decisive: moving 0.25 GiB of attention KV takes 5.0 ms at 50 GiB/s, 85.9 ms at 25 Gbit/s, and 214.7 ms at 10 Gbit/s before overhead. Always tune chunked prefill on a shared pool first; vLLM's own documentation notes that disaggregated prefill targets separate TTFT/ITL control rather than higher aggregate throughput.[13]
Goodput, engines, and failure signatures
Raw tokens/sec hides missed deadlines. DistServe defines goodput as the highest offered request rate per GPU whose joint SLO attainment (TTFT, TPOT, and optionally p99 ITL) stays at or above a threshold (such as 90%):[12]
Sweep with an open-loop Poisson or replayed production trace (a closed-loop client hides overload by slowing its own arrivals), count rejected and timed-out requests as failures in the denominator, and report p50/p99 ITL alongside TTFT.[14][15]
import numpy as np
window_seconds = 10.0
ttft_ms = np.array([120, 450, 180, 190], dtype=np.float64)
tpot_ms = np.array([25, 22, 42, 27], dtype=np.float64)
within_slo = (ttft_ms <= 300.0) & (tpot_ms <= 30.0)
print(f"raw throughput: {ttft_ms.size / window_seconds:.2f} req/s")
print(f"SLO-compliant rate: {int(within_slo.sum()) / window_seconds:.2f} req/s ({int(within_slo.sum())}/{ttft_ms.size})")raw throughput: 0.40 req/s
SLO-compliant rate: 0.20 req/s (2/4)Across production engines, the same primitives recur: vLLM V1 pairs paged KV with default chunked prefill and recompute preemption;[7] SGLang combines continuous batching with RadixAttention prefix reuse;[4] TensorRT-LLM implements in-flight batching;[16] and Mooncake separates KV storage across DRAM/SSD/RDMA with early rejection.[17]
| Failure signature | Check first | Lever to test |
|---|---|---|
| High raw TPS, violent p99 ITL spikes | Whether long gaps align with large prefill steps | Shrink chunk size or max_num_batched_tokens; recheck TTFT and ITL |
| Stable p50 ITL, climbing p99 TTFT | Prefill queue wait by class under decode-first | Age waiting prompts, reserve prefill budget, or shed infeasible load |
| Mid-generation OOM or preemption storms | Resident blocks + projected decode growth | Reserve output headroom and lower concurrency; check swap vs. recompute cost |
| Disaggregated TTFT worse than colocated | Queue + exposed handoff + first-token buffering | Improve KV locality/link bandwidth, rebalance P/D pools, or return to chunked colocation |
Always separate health from load: a worker at its KV or queue limit should reject or defer new requests cleanly rather than failing its liveness probe, because restarting a full worker destroys live streams and warm caches right when capacity is tightest.