Sub topic 5
Continuous batching and the scheduler
This chapter assumes you know what the KV cache and PagedAttention are, and the difference between prefill and decode. It also assumes you can read a short Python script and run shell commands. Here you will learn how vLLM decides which requests run on the GPU at each step, and which settings control that decision.
Why batching is needed
Decoding one token for one request reads all the model weights from GPU memory to produce a single token. The arithmetic units sit mostly idle while they wait on memory. If the GPU decodes one token for 32 requests in the same step, it reads the weights once and produces 32 tokens. Throughput rises sharply while the latency of each step barely changes.
Batching is therefore the main way to raise throughput. The question is how to form the batch, because requests arrive at different times and finish at different lengths.
Static batching and its waste
In static batching, the server collects a group of requests, runs them together, and returns the results when the whole group is done. Two problems follow:
- A short request cannot leave early. It waits for the longest request in its group, and its slot produces padding.
- A new request cannot join. It waits in a queue until the current group finishes.
| Property | Static batching | Continuous batching |
|---|---|---|
| When a request joins | At the start of the next batch | At any step, if there is room |
| When a request leaves | When the whole batch ends | The step it finishes |
| GPU slots when lengths vary | Many idle | Refilled each step |
| Time to first token under load | Includes waiting for a full batch | Includes waiting only for free capacity |
Continuous batching
Continuous batching, also called iteration-level scheduling, makes the scheduling decision once per model step instead of once per batch. After every step, the scheduler:
- Removes requests that finished (hit EOS, a stop string, or
max_tokens). - Keeps the still-running requests in the batch.
- Admits waiting requests, as long as capacity remains.
The batch is a rolling set. A request that needs 16 tokens leaves after 16 steps, and a waiting request takes its place on the next step. This only works because PagedAttention allocates KV cache in blocks on demand. Without it, the server would have to reserve contiguous memory for each request's maximum length, and a freed slot could not easily be reused.
What the scheduler limits
Each step is bounded by three resources. You control them with engine arguments.
max_num_seqs: the maximum number of requests (sequences) in one step. This caps concurrency.max_num_batched_tokens: the maximum number of tokens processed in one step. Each decoding request uses one token. A prompt being prefilled uses as many tokens as the scheduler gives it.- Free KV cache blocks: the memory left after weights and activations, set indirectly by
gpu_memory_utilizationandmax_model_len.
Whichever limit is reached first stops admission. A server with max_num_seqs=256 but little KV cache memory will be limited by blocks, not by the sequence count.
Prefill and decode share a budget
Prefill processes a whole prompt, so it can use thousands of tokens in one step. Decode uses one token per request. If a 3,000-token prompt were prefilled in one step, every running request would wait for that long step before getting its next token, and users would see a stall.
Chunked prefill avoids this. The scheduler splits a long prompt across several steps and fills the remaining token budget with decode tokens first. The vLLM V1 engine uses it by default, and its scheduler treats a request as "tokens still to compute", with no separate prefill and decode phases. In older versions you enable it with --enable-chunked-prefill. Check your version's documentation for the default.
The trade-off is a smaller max_num_batched_tokens. A smaller value keeps decode latency steady, because each step stays short. A larger value finishes prefill in fewer steps, which improves time to first token and throughput on prompt-heavy work.
Running a mixed workload offline
The script below submits 200 requests with very different output lengths. Under static batching, the long requests would hold back the short ones. The scheduler instead refills slots as the short ones finish.
import time
from vllm import LLM, SamplingParams
llm = LLM(
model="Qwen/Qwen2.5-1.5B-Instruct",
max_model_len=4096,
max_num_seqs=64,
max_num_batched_tokens=4096,
)
prompts = [f"Write one fact about the number {i}." for i in range(200)]
params = [
SamplingParams(temperature=0.0, max_tokens=16 if i % 2 == 0 else 256)
for i in range(200)
]
start = time.perf_counter()
outputs = llm.generate(prompts, params)
elapsed = time.perf_counter() - start
generated = sum(len(o.outputs[0].token_ids) for o in outputs)
print(f"{generated} tokens in {elapsed:.1f}s, {generated / elapsed:.0f} tokens/s")llm.generate accepts one SamplingParams per prompt. It queues all 200 requests, and the scheduler keeps up to 64 running at a time. Try changing max_num_seqs to 8 and then 128, and compare tokens per second. Gains flatten once memory bandwidth or KV blocks become the limit.
Preemption
Admission is optimistic. Each request's output length is unknown, so the scheduler cannot know how many KV blocks it will need. If running requests grow until no free blocks remain, the scheduler preempts one, normally the most recently admitted request under first-come-first-served order. It frees that request's blocks and puts it back at the front of the waiting queue. When memory is available again, the request is rescheduled and its KV cache is recomputed from the prompt and the tokens generated so far. Older versions could also swap blocks to CPU memory.
Preemption keeps the server running, but it wastes work. Frequent preemptions show up as higher latency and lower throughput. The fixes are the memory settings from the earlier chapters: lower max_model_len or max_num_seqs, raise gpu_memory_utilization, or use a quantized model or more GPUs.
Scheduling policy
The default policy is first-come-first-served (--scheduling-policy fcfs). vLLM also supports priority. In that mode, each request carries a priority value, lower values run first, and ties are broken by arrival time. Priority scheduling helps when interactive traffic shares a server with batch jobs. It does not remove the capacity limits above.
Observing the scheduler
Two metrics show how the scheduler is doing:
curl -s http://localhost:8000/metrics | grep -E '^vllm:(num_requests_running|num_requests_waiting)'vllm:num_requests_runningis the current batch size. If it sits atmax_num_seqs, concurrency is capped.vllm:num_requests_waitingis the queue length. A queue that keeps growing means the arrival rate exceeds capacity.
If the waiting count is high while the running count is well below max_num_seqs, KV cache blocks or the token budget are the constraint.
Common errors
- Setting
max_num_seqsvery high and expecting more speed. Capacity is bounded by KV blocks, so extra slots only increase preemptions. - Setting
max_num_batched_tokensbelow the longest prompt without chunked prefill. The engine refuses to start or rejects such requests, depending on the version. - Judging throughput from a handful of requests. With a small batch, the GPU is underused regardless of the settings.
- Comparing latency and throughput as if they moved together. A larger batch raises total tokens per second but also lengthens each request's step time.
Exercise
A server has maxnumseqs=128, but the metric vllm:numrequestsrunning stays near 40 while vllm:numrequestswaiting keeps rising. Which limit is the scheduler most likely hitting, and name two changes that could help.
Show answer
It is most likely running out of free KV cache blocks (or the per-step token budget), not the sequence limit, because the batch is far below 128 while requests wait. Two changes: lower maxmodellen or raise gpumemoryutilization to give the KV cache more blocks, and use a quantized model or add GPUs with tensor parallelism to free memory. Raising maxnumbatched_tokens can also help if prefill is the bottleneck.
Exercise
Why does continuous batching give lower waiting time for a short request than static batching when it shares the server with a long request?
Show answer
Under static batching, the short request stays in its batch until the long request finishes, and new requests wait for the next batch. Under continuous batching, the scheduler removes the short request the step it finishes and fills the free slot with a waiting request, so neither the short request nor the queue waits for the longest one.