Before you start: words you need#
| Word | Plain meaning |
|---|---|
| Engine step | One turn of the engine core loop (16.g): plan a batch, run one forward pass on the GPU, read the results. |
| Token budget | The most tokens one forward pass may process, set by --max-num-batched-tokens. |
| KV cache block | A fixed-size slice of GPU memory that holds keys and values for 16 tokens (12.l). |
| Running / waiting | Running requests already hold KV blocks and are in the batch. Waiting requests have not been admitted yet. |
| Admission | Moving a request from waiting to running, which needs both budget and memory. |
| Preemption | Taking all of a running request’s blocks away so others can continue; it recomputes later (17.c). |
| Head-of-line blocking | The first request in a queue cannot go, so nobody behind it goes either. |
SchedulerOutput | The plan for one step, sent from the scheduler to the GPU worker. |
1. What is it?#
Scheduler.schedule() is the function vLLM calls once per engine step. It answers one question:
which tokens does the GPU process next?
It has two limited resources: a budget of tokens and a pool of KV cache blocks. It first walks the
requests that are already running and gives each what it needs. Then, if budget and memory
remain, it admits requests from the waiting queue. For each request it decides a single
number, how many tokens to compute this step, and reserves the blocks those tokens will occupy.
The result is a SchedulerOutput. After the GPU has run, update_from_output() records what was
produced. Those two functions are the scheduler, and this lesson reads both in the vLLM v0.32.0
source (vllm/v1/core/sched/scheduler.py).
The general idea, continuous batching, is taught in 12.j. Here we look at how vLLM implements it.
Facts checked on 12 November 2026 against vLLM v0.32.0 (18 October 2026).
2. Why does it exist?#
A GPU is only cheap per token when it works on many requests at once. But requests arrive at random times, have prompts from 10 to 100,000 tokens, and stop at unpredictable lengths. Something must decide, every few milliseconds:
- which requests share the next forward pass,
- how many prompt tokens a newcomer may read in this pass,
- whether there is memory for one more request, and
- what to do when memory runs out.
Get this wrong and either the GPU idles (too little work), streams stall (one huge prompt hogs the step), or memory thrashes (requests evict each other). vLLM’s throughput comes mostly from this one function and the KV cache manager it calls (17.e to 17.i).
3. Simple analogy#
A restaurant kitchen with one big oven that bakes every few seconds and holds 64 trays.
Before each bake the head chef first serves the tables that are already eating: each needs one more small tray (one token). Then, if trays are left, the chef seats new guests from the door queue, giving a big party only as many trays as remain. A party that will not fit in the dining room is not seated, and the chef does not skip past them to seat a smaller party behind, or the big party would wait forever.
4. Tiny example: one step with three requests#
Budget 64 tokens, 12 free blocks of 16 tokens.
running: A generating, needs 1 token → gets 1
B in the middle of a 100-token prompt → gets min(76 left, 63 budget) = 63
waiting: C 90-token prompt → budget is 0: wait for next step
step uses 64/64 tokens. A samples a token; B has read 87 of 100 prompt tokens.Next step B needs only 13 more tokens, so C may be admitted, if its whole prompt fits in the free blocks.
5. Technical explanation#
What the scheduler holds#
self.requests: dict[str, Request] # every unfinished request, by ID
self.waiting: RequestQueue # not yet running (a deque, or a heap for priority)
self.kv_holding_waiting: RequestQueue # waiting, but already holding KV blocks
self.running: list[Request] # admitted; holds KV blocks
self.kv_cache_manager # the block pool and prefix cacheEach Request carries the counters the algorithm is built on:
| Field | Meaning |
|---|---|
num_prompt_tokens | Length of the prompt |
num_tokens | Prompt plus output tokens so far |
num_tokens_with_spec | num_tokens plus any speculative draft tokens (18.f) |
num_computed_tokens | How many tokens have had their KV computed, or are scheduled to be |
max_tokens | The output limit |
status | WAITING, three “waiting for something” states, RUNNING, PREEMPTED, or a FINISHED_* state |
A comment at the top of schedule() states the whole design:
# There's no "decoding phase" nor "prefill phase" in the scheduler.
# Each request just has the num_computed_tokens and
# num_tokens_with_spec. ... At each step, the scheduler tries to assign
# tokens to the requests so that each request's num_computed_tokens can
# catch up its num_tokens_with_spec.The budgets#
token_budget = self.max_num_scheduled_tokens
input_budget = self.scheduler_config.max_num_batched_tokensmax_num_batched_tokens is the flag you set. max_num_scheduled_tokens defaults to the same
value; it is smaller only when the model itself may add tokens to the batch, as speculative
decoding does. For this lesson treat them as one number: the most tokens the GPU processes in
one forward pass.
The second limit is max_num_seqs: the most requests that may be in running at once. It also
sizes per-request buffers and CUDA graphs in the model runner. Since v0.32.0 there is also
--max-num-active-seqs, an admission limit that may be set below max_num_seqs to keep decode
batches smaller without shrinking those buffers. A step is therefore bounded both ways: a number
of sequences and a number of tokens.
Pass 1: running requests#
req_index = 0
while req_index < len(self.running) and token_budget > 0:
request = self.running[req_index]
...
num_new_tokens = (
request.num_tokens_with_spec
+ request.num_output_placeholders
- request.num_computed_tokens
)
if 0 < long_prefill_token_threshold < num_new_tokens:
num_new_tokens = long_prefill_token_threshold
num_new_tokens = min(num_new_tokens, token_budget, input_budget - draft_slots)
# Make sure the input position does not exceed the max model len.
num_new_tokens = min(
num_new_tokens,
self.max_model_len - request.num_computed_tokens - self.num_sampled_tokens_per_step,
)Read it as: the gap, then caps.
- A request in the middle of its prompt has a large gap. It gets as much as the budget allows. That is one chunk of a chunked prefill (12.k, 17.b).
- A request that is generating has a gap of 1: the token it sampled last step has not been through the model yet.
num_output_placeholders is zero unless async scheduling is on (17.d). long_prefill_token_threshold
is a per-request cap, 0 by default (17.b).
Running requests go first, in the order they were admitted. That protects requests already in progress: a newly arrived 50,000-token prompt cannot stall anyone’s generation, because every running request takes its share before the newcomer is considered.
If nothing can be scheduled for a request this step, the code skips it rather than stopping:
if num_new_tokens == 0:
# NOTE(woosuk): Here, by doing `continue` instead of `break`,
# we do not strictly follow the FCFS scheduling policy and
# allow the lower-priority requests to be scheduled.
req_index += 1
continueThe source lists the reasons a request may get zero: all its prompt tokens are already in flight (pipeline parallelism), the multimodal encoder budget or cache is full, or a hybrid model needs a block-aligned chunk that does not fit. One request that cannot move must not hold up the batch.
Then memory:
while True:
new_blocks = self.kv_cache_manager.allocate_slots(
request, num_new_tokens, num_lookahead_tokens=self.num_lookahead_tokens
)
if new_blocks is not None:
break # the request can be scheduled
... # otherwise: preempt someone and try againallocate_slots returns the blocks needed to hold num_new_tokens more tokens, or None if the
pool cannot supply them (17.g traces it). A generating request needs a new block only once every
16 tokens, so most calls return an empty list at almost no cost. On None, a running request is
preempted to free memory (17.c).
Finally the bookkeeping for a scheduled request:
scheduled_running_reqs.append(request)
req_to_new_blocks[request_id] = new_blocks
num_scheduled_tokens[request_id] = num_new_tokens
token_budget -= num_new_tokens
input_budget -= num_new_tokens + draft_slotsPass 2: waiting requests#
Pass 2 runs only if pass 1 preempted nobody. If memory was so short that a running request had to be evicted, admitting more work would be self-defeating:
if not preempted_reqs and self._pause_state != PauseState.PAUSED_ALL:
while token_budget > 0:
# Requests holding KV blocks are always drained first, ...
request_queue = self.kv_holding_waiting
if not request_queue and self._pause_state == PauseState.UNPAUSED:
request_queue = self.waiting
if not request_queue or input_budget <= draft_slots:
break
num_running = len(self.running) + self.num_waiting_for_streaming_input
if num_running >= self.max_num_active_reqs:
break
request = request_queue.peek_request()
...kv_holding_waiting holds waiting requests that already own blocks (for example one whose KV has
arrived from another machine); they always go first (17.c). The pause states let the engine stop
admitting new requests (PAUSED_NEW) or schedule nothing at all (PAUSED_ALL), for example
while weights are being updated.
For the request at the head of the queue, in order:
| Gate | Passes when | Otherwise |
|---|---|---|
| Budget | token_budget > 0 | Stop admitting this step |
| Slots | running (plus paused streaming sessions) < max_num_active_seqs | Stop admitting this step |
| Ready | Not waiting for a grammar to compile, KV to arrive from elsewhere, or the next chunk of a streaming input | Skip it and look at the next |
| LoRA | Its adapter is already in this batch, or the batch has fewer than max_loras adapters (18.g) | Skip it |
| Cache lookup | (always) | Find how much of the prompt is already in the prefix cache, locally or through a KV connector |
| Memory | allocate_slots(...) returns blocks | Stop admitting this step |
Two different reactions appear in that table, and the difference matters. A request that is not ready is skipped: set aside and put back at the front of the queue afterwards, so the requests behind it are not delayed. A request that does not fit in memory stops admission: the scheduler does not search further down the queue for a smaller one. That is head-of-line blocking, chosen on purpose: letting small requests overtake a large one would starve the large one for as long as small requests keep arriving.
The cache lookup happens once per request, when it has computed nothing yet:
if request.num_computed_tokens == 0:
(new_computed_blocks, num_new_local_computed_tokens, ...) = \
self._get_local_prefix_cache_hit(request)
if self.connector is not None:
ext_tokens, load_kv_async = self.connector.get_num_new_matched_tokens(...)If the first 2,048 tokens of a 2,100-token prompt are already cached, the request starts with
num_computed_tokens = 2048 and only 52 tokens are charged to this step’s budget (17.f). If a
KV connector (an add-on that fetches KV from another server or from CPU/disk, 19.b) reports
more matching tokens, those are counted too; an asynchronous load parks the request in
WAITING_FOR_REMOTE_KVS until the data has arrived.
The amount to schedule follows the same rule as pass 1:
num_new_tokens = request.num_tokens - num_computed_tokens
if 0 < long_prefill_token_threshold < num_new_tokens:
num_new_tokens = long_prefill_token_threshold
...
num_new_tokens = min(num_new_tokens, request_token_budget)If the prompt does not fit in what is left of the budget, it gets what is left and continues in later steps. That is chunked prefill, and it needs no code of its own: the request simply comes back through pass 1 next step with a smaller gap.
The memory check for a new request is stricter than for a running one:
new_blocks = self.kv_cache_manager.allocate_slots(
request, num_tokens_past_hit,
num_new_computed_tokens=num_new_local_computed_tokens,
new_computed_blocks=new_computed_blocks,
full_sequence_must_fit=self.scheduler_reserve_full_isl,
...
)scheduler_reserve_full_isl (“input sequence length”) defaults to True: the request is admitted
only if blocks for its whole prompt are free now, not just for the first chunk. Without it,
several long prompts could each be admitted on the strength of a first chunk and then fight for
memory halfway through, preempting one another. The config docstring calls this “over-admission
and KV cache thrashing”.
On success the request changes state:
request = request_queue.pop_request()
self.running.append(request)
...
request.status = RequestStatus.RUNNING
request.num_computed_tokens = num_computed_tokensWhat the scheduler sends to the worker#
scheduler_output = SchedulerOutput(
scheduled_new_reqs=new_reqs_data, # full data, sent once per request
scheduled_cached_reqs=cached_reqs_data, # only the changes since last step
num_scheduled_tokens=num_scheduled_tokens, # req_id -> tokens this step
total_num_scheduled_tokens=...,
preempted_req_ids=...,
finished_req_ids=self.finished_req_ids, # so the worker can forget them
new_block_ids_to_zero=...,
kv_cache_block_copies=...,
...
)The split between new and cached saves bandwidth. The first time a request is scheduled, the
worker receives its prompt token IDs, sampling parameters and block IDs (NewRequestData). Every
later step it receives only the difference: newly allocated block IDs and the updated token count
(CachedRequestData). A 100,000-token prompt crosses to the worker once, not once per generated
token. (With Model Runner V2, the default for dense models since v0.25.0, a resumed request is
also sent as a new request, because the runner rebuilds its state.)
finished_req_ids rides along so the worker can drop its copy of a request’s state. The worker
never decides on its own that a request is over. If a KV connector is configured, the scheduler
also attaches its plan for loads and saves (kv_connector_metadata).
After scheduling: advance the counter at once#
def _update_after_schedule(self, scheduler_output):
# Advance the number of computed tokens for the request AFTER
# the request is scheduled.
for req_id, num_scheduled_token in num_scheduled_tokens.items():
request = self.requests[req_id]
request.num_computed_tokens += num_scheduled_token
request.num_in_flight_tokens += num_scheduled_token
request.is_prefill_chunk = request.num_computed_tokens < (
request.num_tokens + request.num_output_placeholders
)num_computed_tokens moves forward when the work is scheduled, not when it is done. That is
what lets the next schedule() run before the GPU has finished (17.d): the scheduler’s view
already shows this step’s tokens as computed, so it can plan the next chunk.
num_in_flight_tokens records how much of that is still a promise.
update_from_output(): closing the step#
When the worker returns sampled token IDs, the scheduler loops over every request in the batch:
for req_id, num_tokens_scheduled in num_scheduled_tokens.items():
request = self.requests.get(req_id)
if request is not None:
request.num_in_flight_tokens -= num_tokens_scheduled
...
if request is None or request.is_finished():
continue # aborted while the GPU was working on it
generated_token_ids = sampled_token_ids[req_index] if sampled_token_ids else []
... # rejected draft tokens roll num_computed_tokens back
if new_token_ids:
new_token_ids, stopped = self._update_request_with_output(request, new_token_ids)
...
if stopped:
finished = self._handle_stopped_request(request)
if finished:
self._free_request(request)
outputs[request.client_index].append(EngineCoreOutput(request_id=req_id, ...))For each request:
- Skip it if it has gone. An abort may have arrived while the forward pass ran.
- Take its sampled tokens. A request still in the middle of its prompt has none.
- Append and check for stop (
check_stopinvllm/v1/core/sched/utils.py), in this order: end-of-sequence token; a stop token ID; length (num_tokens >= max_model_lenornum_output_tokens >= max_tokens); then, oncemin_tokensis met, repetition detection. - If finished, free its blocks back to the pool and add its ID to
finished_req_idsfor the nextSchedulerOutput. - Emit an
EngineCoreOutput, filed under the API server that owns the request.
The comment above this loop warns contributors: “As len(num_scheduled_tokens) can be up to 1K
or more, the below loop can be a performance bottleneck.” Everything in it is paid once per
request per token.
6. Under the hood#
The life of a request#
flowchart LR W["WAITING"] -->|"admitted in pass 2"| R["RUNNING"] W -->|"grammar compiling,<br/>KV arriving, stream paused"| B["WAITING_FOR_…"] B -->|"ready"| W R -->|"blocks taken away"| P["PREEMPTED"] P -->|"re-admitted, recomputes"| R R -->|"EOS or stop token"| F1["FINISHED_STOPPED"] R -->|"max_tokens or context full"| F2["FINISHED_LENGTH_CAPPED"] R -->|"repetition detected"| F4["FINISHED_REPETITION"] R -->|"client disconnected"| F3["FINISHED_ABORTED"] W --> F3 class W,B,P queue class R compute class F1,F2,F3,F4 neutral
The statuses are an IntEnum (vllm/v1/request.py), and one comparison defines “finished”:
@staticmethod
def is_finished(status: "RequestStatus") -> bool:
return status > RequestStatus.PREEMPTEDThe full list in v0.32.0 also has FINISHED_IGNORED (prompt longer than the model allows) and
FINISHED_ERROR.
One step as a flowchart#
flowchart TB
S[":i-list-checks: <b>schedule()</b><br/><small>token_budget = max_num_batched_tokens</small>"] --> P1["<b>Pass 1: each RUNNING request</b><br/><small>tokens = min(gap, budget)</small>"]
P1 --> A1{"allocate_slots()"}
A1 -- "pool empty" --> PRE[":i-triangle-alert: preempt a running request<br/><small>then try again</small>"]
PRE --> A1
A1 -- "blocks granted" --> P2["<b>Pass 2: head of the WAITING queue</b><br/><small>gates: budget, active slots,<br/>ready, LoRA</small>"]
P2 --> C["prefix-cache lookup<br/><small>local, then KV connector</small>"]
C --> A2{"allocate_slots()<br/><small>whole prompt must fit</small>"}
A2 -- "granted" --> OK2["move to RUNNING<br/><small>then the next in the queue</small>"]
A2 -- "refused" --> STOP["stop admitting this step"]
OK2 --> OUT[":i-package: <b>SchedulerOutput</b>"]
STOP --> OUT
class S,P1,P2 queue
class C,OK2 neutral
class A1,A2 memory
class PRE,STOP warn
class OUT ioA scheduler in 100 lines of Go#
Both limits and a block pool: the two passes, the whole-prompt admission check and the “stop at the first request that does not fit” rule. Preemption is left out (17.c adds it).
package main
import (
"fmt"
"strings"
)
const (
blockSize = 16
tokenBudget = 64 // max_num_batched_tokens
maxSeqs = 3 // max_num_seqs
totalBlocks = 12 // the whole KV cache: 192 tokens
)
type request struct {
id string
prompt int
maxNew int
output int
computed int
blocks int
}
func (r *request) total() int { return r.prompt + r.output }
func blocksFor(tokens int) int { return (tokens + blockSize - 1) / blockSize }
func main() {
waiting := []*request{
{id: "A", prompt: 40, maxNew: 4},
{id: "B", prompt: 100, maxNew: 2},
{id: "C", prompt: 90, maxNew: 2},
{id: "D", prompt: 10, maxNew: 2},
}
var running []*request
free := totalBlocks
for step := 1; len(waiting)+len(running) > 0 && step < 20; step++ {
budget := tokenBudget
var log []string
scheduled := map[*request]int{}
note := ""
// Pass 1: running requests, in admission order.
for _, r := range running {
if budget == 0 {
break
}
n := min(r.total()-r.computed, budget)
need := blocksFor(r.computed+n) - r.blocks
if need > free {
note = r.id + " cannot grow (a real scheduler would preempt here)"
break
}
free -= need
r.blocks += need
scheduled[r] = n
budget -= n
log = append(log, fmt.Sprintf("%s:%d", r.id, n))
}
// Pass 2: admit from the head of the waiting queue.
for len(waiting) > 0 && budget > 0 && note == "" {
if len(running) >= maxSeqs {
note = "max_num_seqs reached"
break
}
r := waiting[0]
// The whole prompt must fit, not just the first chunk.
if blocksFor(r.prompt) > free {
note = fmt.Sprintf("%s needs %d blocks, %d free: stop admitting",
r.id, blocksFor(r.prompt), free)
break
}
waiting = waiting[1:]
running = append(running, r)
n := min(r.total()-r.computed, budget)
need := blocksFor(r.computed+n) - r.blocks
free -= need
r.blocks += need
scheduled[r] = n
budget -= n
log = append(log, fmt.Sprintf("%s:%d", r.id, n))
}
// "Forward pass" and update_from_output.
keep := running[:0]
for _, r := range running {
if n, ok := scheduled[r]; ok {
r.computed += n
if r.computed == r.total() {
r.output++ // sampled a token
}
}
if r.output == r.maxNew {
free += r.blocks // finished: blocks go back to the pool
log = append(log, r.id+" done")
continue
}
keep = append(keep, r)
}
running = keep
fmt.Printf("step %-2d [%-22s] used %2d/%d free blocks %2d %s\n",
step, strings.Join(log, " "), tokenBudget-budget, tokenBudget, free, note)
}
}Output:
step 1 [A:40 B:24 ] used 64/64 free blocks 7
step 2 [A:1 B:63 ] used 64/64 free blocks 3
step 3 [A:1 B:13 ] used 14/64 free blocks 2 C needs 6 blocks, 2 free: stop admitting
step 4 [A:1 B:1 A done B done ] used 2/64 free blocks 12 C needs 6 blocks, 2 free: stop admitting
step 5 [C:64 ] used 64/64 free blocks 8
step 6 [C:26 D:10 ] used 36/64 free blocks 5
step 7 [C:1 D:1 C done D done ] used 2/64 free blocks 12 How to read it:
- B’s 100-token prompt is read in three chunks (24, 63, 13) while A keeps generating one token per step.
- In steps 3 and 4, C is refused although the token budget has room, because its whole 90-token prompt does not fit in the free blocks.
- D, a tiny request, waits behind C even though it would fit. That is head-of-line blocking, exactly as the real scheduler behaves.
- (In the program, the stop message is decided before the step’s finished requests free their
blocks, so step 4 still shows it; the real scheduler also frees blocks only in
update_from_output, after the step.)
7. Performance implications#
- The two passes are pure Python, every step. At 1,000 running requests the per-request
loops in
schedule()andupdate_from_output()become a measurable part of each step, which is why async scheduling (17.d) hides them behind GPU work. - Decode tokens are cheap for the budget. 256 generating requests take 256 tokens of an 8,192-token budget, leaving most of the step for prefill chunks.
- Head-of-line blocking costs latency, not throughput. A large waiting request can idle some budget for a few steps, but it guarantees the large request makes progress.
- The whole-prompt check trades some admission for stability. It occasionally leaves blocks unused that a first chunk could have used, in exchange for far fewer preemptions.
8. Production implications#
max_num_seqsandmax_num_batched_tokensare the two dials of a step. Their defaults depend on the GPU (17.b); check the startup log for the values in force.- A stream that pauses mid-answer is usually a preemption, not a slow GPU. Watch
vllm:num_preemptions(17.c, 19.c). - A long queue with spare budget usually means memory is the limit. The head request does
not fit; look at
vllm:kv_cache_usage_percand at prompt lengths. - Custom schedulers are possible through
--scheduler-cls, but the interface is not public; subclassAsyncScheduler, notScheduler, or you lose async scheduling (17.d).
9. Common mistakes#
- Thinking vLLM has a “prefill phase” and a “decode phase”. The scheduler only knows each request’s gap between computed and known tokens.
- Assuming a small request can jump a large one that does not fit. Admission stops at the first request that fails the memory check.
- Expecting
max_num_seqsalone to bound memory. It bounds the number of requests, not how long each grows. - Reading
num_computed_tokensas “done on the GPU”. It advances when the work is scheduled. - Forgetting that a step which preempted admits nobody. Pass 2 is skipped entirely.
10. Hands-on exercise#
- Run the program. Set
totalBlocksto 20 and rerun. Does C get in earlier? Does D? - Change the admission rule to check only the first chunk (
blocksFor(min(r.prompt, budget))). Find a step where a running request “cannot grow”. That is the thrashingscheduler_reserve_full_islprevents. - Reorder the waiting queue so D arrives before C. How much sooner does D finish?
- In a clone of vLLM v0.32.0, open
vllm/v1/core/sched/scheduler.pyand find everybreakin pass 2. For each, write one sentence on why stopping is right there.
11. Interview questions#
- Why are running requests scheduled before waiting ones?
- What is the difference between skipping a waiting request and stopping admission, and when does each happen?
- Why does vLLM check that the whole prompt fits before admitting a request, when chunked prefill only needs the first chunk now?
- Why does the worker receive a request’s prompt token IDs only once?
- Why does
num_computed_tokensadvance at scheduling time rather than after the forward pass?
12. Further reading#
Checked on 12 November 2026, against the v0.32.0 tag.
vllm/v1/core/sched/scheduler.py:schedule,_update_after_schedule,update_from_outputvllm/v1/core/sched/output.py:SchedulerOutput,NewRequestData,CachedRequestDatavllm/v1/core/sched/utils.py:check_stopvllm/v1/request.py:Request,RequestStatusvllm/config/scheduler.py: every scheduler flag and its docstring- Continuous batching in general: 12.j. The engine loop that calls
schedule(): 16.g.