Requests do not arrive together or finish together. If a server fixes one batch and waits for every member to finish, shorter requests leave empty slots while longer requests continue. The GPU may have room for new work, but the static batch cannot admit it.
Continuous batching changes the membership of the active batch between model iterations. A scheduler can admit a new prompt, advance existing decodes, and remove finished requests at each step. The choice of which work to schedule affects time to first token, time between output tokens, throughput, and KV cache pressure.
In this post, you will learn about:
- How continuous batching changes the active request set between iterations
- How token budgets and cache capacity constrain a scheduler
- How prefill policy and fairness affect queue and streaming latency
Let’s get started.

Continuous Batching and Scheduling: An Introduction.
Photo by Ambitious Studio* | Rick Barrett. Some rights reserved.
Overview
This post is divided into three parts; they are:
- From Static to Continuous Batching
- An Iteration-Level Scheduler
- Token Budgets and Prefill Policy
From Static to Continuous Batching
Static batching groups requests before execution and keeps the group together until all finish. It is simple for offline jobs with similar lengths. Dynamic batching waits briefly to form a batch from arriving requests, but a conventional dynamic batch may still stay fixed once it starts. Continuous batching, also called in-flight batching, changes active membership at iteration boundaries.
For example, three requests may arrive at different times:
| Iterations | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Request A | Prefill | Decode | Decode | Done | – |
| Request B | – | Prefill | Decode | Decode | Decode |
| Request C | – | – | – | Prefill | Decode |
After A finishes, C can use the freed slot even while B continues. The scheduler cannot usually change a running GPU kernel halfway through an iteration. The useful scheduling boundary is the next model step.
An iteration can contain one new token for each decoding sequence and a chunk of prompt tokens for one or more prefilling sequences. These jobs have different shapes: prefill processes many positions in parallel, while decode normally processes one position per active sequence. Mixing them can improve occupancy, but a long prefill may delay the next token for an existing stream.
An Iteration-Level Scheduler
The following standard-library simulation schedules token work. It does not execute a model. Run the block to see which requests make progress each iteration.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
from dataclasses import dataclass @dataclass class Request: name: str arrival: int prompt_tokens: int output_tokens: int prefill_left: int = 0 decode_left: int = 0 first_token_at: int | None = None def __post_init__(self): self.prefill_left = self.prompt_tokens self.decode_left = self.output_tokens @property def reserved_tokens(self): return self.prompt_tokens + self.output_tokens requests = [ Request("A", arrival=0, prompt_tokens=8, output_tokens=3), Request("B", arrival=1, prompt_tokens=3, output_tokens=5), Request("C", arrival=2, prompt_tokens=6, output_tokens=2), ] max_num_seqs = 2 max_num_batched_tokens = 6 kv_token_capacity = 20 waiting = [] active = [] completed = [] next_arrival = 0 iteration = 0 while len(completed) < len(requests): while next_arrival < len(requests) and requests[next_arrival].arrival <= iteration: waiting.append(requests[next_arrival]) next_arrival += 1 # Reserve full prompt plus maximum output length before admission. while waiting and len(active) < max_num_seqs: candidate = waiting[0] reserved = sum(req.reserved_tokens for req in active) if reserved + candidate.reserved_tokens > kv_token_capacity: break active.append(waiting.pop(0)) budget = max_num_batched_tokens actions = [] # Give each ready decode one token before scheduling new prefill work. for req in active: if budget and req.prefill_left == 0 and req.decode_left: req.decode_left -= 1 budget -= 1 if req.first_token_at is None: req.first_token_at = iteration actions.append(f"{req.name}:decode 1") # Use the remaining token budget for prefill chunks. for req in active: if budget and req.prefill_left: chunk = min(req.prefill_left, budget) req.prefill_left -= chunk budget -= chunk if req.prefill_left == 0: # The last prompt position supplies the first output logits. req.decode_left -= 1 req.first_token_at = iteration actions.append(f"{req.name}:prefill {chunk} + first token") else: actions.append(f"{req.name}:prefill {chunk}") finished = [ req for req in active if req.prefill_left == 0 and req.decode_left == 0 ] for req in finished: active.remove(req) completed.append(req) print(f"step {iteration:02d}: {', '.join(actions) or 'idle'}") if not actions and next_arrival == len(requests) and not active: raise RuntimeError("requests cannot fit the cache budget") iteration += 1 for req in completed: print(req.name, "first output step:", req.first_token_at) |
The scheduler reserves the full maximum sequence length at admission. That is conservative: real engines may allocate cache blocks as needed, then preempt or reject requests if memory runs short. The simulation uses a fixed token budget and a sequence-count limit. Neither limit alone is sufficient: two very long prefills can exceed a token budget even when only two sequences are active.
The final prefill position produces logits for the first output token. Later output tokens use decode steps. The first_token_at value is a model-iteration number, not a wall-clock TTFT. An iteration containing six prefill tokens can take a different amount of time from one containing two decode tokens. You should measure execution time for the actual shapes and add queueing, transfer, and streaming overhead to predict latency.
This scheduler is intentionally simple. It uses FIFO admission, reserves each request’s full prompt and maximum output length, gives decode work priority over prefill, and never preempts an active request. A production scheduler can replace each of these choices, but every alternative introduces a different trade-off.
FIFO admission is predictable, but a large request at the front of the queue can block smaller requests behind it. Priority scheduling can reduce latency for urgent work, but it needs aging or deadlines so lower-priority requests do not starve. Full cache reservation prevents overcommit, but it leaves memory idle when requests stop early. Allocating cache space on demand improves average utilization, but it may require preemption, recomputation, rejection, or failure when many requests grow at once. The policy must also define how cancellation and capacity exhaustion release or reassign resources.
A scheduler may also account for the actual token work of packed or paged batches instead of assuming that every active request has the padded length of the largest request. Sequence length, attention pattern, adapter choice, and sampling work can all affect the cost of an iteration. The best policy therefore depends on whether the service prioritizes queue time, streaming latency, throughput, fairness, or memory utilization.
Token Budgets and Prefill Policy
Each model iteration must satisfy a token budget, an active-sequence limit, and the available KV cache capacity. Useful limits depend on the model, available GPU memory, expected prompt lengths, and latency targets.
The example schedules ready decodes first. This protects the inter-token latency of existing streams, but continuous arrivals of decode work could leave little room for long prefills. Prefill-first scheduling may reduce queue time for new requests but create visible gaps in existing streams. Chunked prefill lets the scheduler split a long prompt and mix it with decode work, as Long-Context Inference showed. Fair scheduling needs a rule for how long any request may wait.
The corresponding controls are arguments to LLM():
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from vllm import LLM, SamplingParams llm = LLM( model="facebook/opt-125m", max_model_len=512, max_num_seqs=4, max_num_batched_tokens=128, enable_chunked_prefill=True, ) outputs = llm.generate( ["A KV cache stores", "Continuous batching schedules"], SamplingParams(temperature=0.0, min_tokens=8, max_tokens=16), use_tqdm=False, ) for output in outputs: print(repr(output.outputs[0].text)) |
The setting max_model_len=512 limits the combined prompt and generated sequence length for each request. It is a per-sequence context limit, not an iteration budget.
The setting max_num_seqs=4 limits how many sequences vLLM can schedule in one model iteration. Raising it allows more concurrent requests, but those requests compete for KV cache capacity and the token budget.
The setting max_num_batched_tokens=128 limits the total number of token positions processed in one iteration. A decode sequence usually contributes one new position, while a prefill may contribute many prompt positions. The scheduler must fit their combined work within this budget.
The setting enable_chunked_prefill=True allows a prompt larger than the remaining iteration budget to be split across multiple iterations. This lets vLLM mix part of a long prefill with decode work instead of making the long prompt occupy one oversized iteration. The setting changes scheduling granularity; it does not change the model’s context limit or reduce the total prefill computation.
These limits work together. An iteration must satisfy both the sequence-count limit and the token budget, while every admitted request must fit the model-length and KV cache constraints. Larger values may improve throughput by exposing more work to the GPU, but they can also increase cache pressure or delay existing decode streams. Compare configurations using the same request mix and measure queue time, TTFT, time per later output token, throughput, and KV cache use.
Further Reading
- vLLM documentation. Scheduler Configuration. Defines token, sequence, queue, and chunked-prefill controls.
- vLLM documentation. Metrics. Lists queue, prefill, decode, and cache measurements.
- Gyeong-In Yu et al. (2022). Orca: A Distributed Serving System for Transformer-Based Generative Models. This paper introduced iteration-level scheduling for generative models.
Summary
Continuous batching admits and removes requests between model iterations. Token budgets, active-sequence limits, cache capacity, and prefill policy determine which work can run next. A scheduler that improves total throughput can still harm queue time or streaming latency, so compare policies under the same traffic and report both service-level and resource metrics.






No comments yet.