Pidoku

Priorities, Preemption and Queues

Module 17 Lesson 17.c 50 min Difficulty 3/5

Prerequisites 17.a, 17.b


Before you start: words you need#

WordPlain meaning
PreemptionTaking all of a running request’s KV blocks away and sending it back to the waiting queue.
VictimThe request chosen to be preempted.
RecomputeRunning a preempted request’s prompt and earlier output through the model again to rebuild its KV.
FCFSFirst come, first served: the order of arrival decides.
PriorityA number a client attaches to a request. In vLLM, a lower value runs first.
HeapA data structure that always gives you the smallest item quickly; used for the priority queue.
WatermarkA share of KV blocks kept free when admitting new requests, as headroom.

1. What is it?#

A request’s memory need is unknown when it is admitted: nobody knows how long the answer will be. vLLM therefore admits requests optimistically and deals with the consequences. If running requests grow until the KV cache is full, one of them is preempted: all its blocks are taken away, it goes back to the waiting queue, and when re-admitted it must compute everything again from its first token. To the client, a preemption is a stream that freezes and later resumes.

This lesson covers who waits (the queues and the scheduling policy), who is evicted, what eviction costs, and the settings that make it rare. Queueing and priority as server-design ideas are in 20.c and 20.k; here we read vLLM’s implementation.

Facts checked on 12 November 2026 against vLLM v0.32.0.


2. Why does it exist?#

The alternative is to reserve, at admission, memory for the longest answer a request could give: max_model_len tokens each. 16.a showed how much capacity that costs: most of the cache would sit reserved and empty. vLLM instead reserves only what each request has used so far plus its whole prompt (17.a), and accepts that occasionally the cache runs out. Preemption is the safety valve that makes optimistic admission safe.


3. Simple analogy#

A car park that lets cars in as long as there is space at the entrance, even though some cars will later want a second bay for a trailer. When the park is full and a car needs its trailer bay, the attendant tows the car that arrived last back to the entrance queue, at the front. That car loses its spot and has to park again from scratch, but everybody else keeps moving.


4. Tiny example#

KV cache: 48 blocks. A, B, C running, each holding 16 blocks. 0 free.
A needs a 17th block.
  FCFS policy → victim = C (admitted last)
  C's 16 blocks freed, C.num_computed_tokens = 0, C goes to the front of the waiting queue
  A gets its block
  this step admits nobody new
Later, when blocks free up, C is re-admitted and recomputes its prompt AND everything it had
generated, as one prefill.

5. Technical explanation#

Two queues, one interface#

--scheduling-policy chooses the waiting queue’s data structure (vllm/v1/core/sched/request_queue.py):

PolicyStructureOrder
fcfs (default)dequeArrival order
priorityBinary heap(priority, arrival_time, request_id); lower priority value runs first

The heap order is the request’s own comparison operator (vllm/v1/request.py):

Python
def __lt__(self, other: "Request") -> bool:
    if self.priority != other.priority:
        return self.priority < other.priority
    if self.arrival_time != other.arrival_time:
        return self.arrival_time < other.arrival_time
    if self.request_id != other.request_id:
        return self.request_id < other.request_id
    return id(self) < id(other)

A client sets "priority": <int> in the request body. The default is 0, and the API docstring says “Any priority other than 0 will raise an error if the served model does not use priority scheduling.” vLLM does not check who may claim which priority; a gateway in front must decide that.

The running list is the same under both policies: a plain list in admission order.

There are really two waiting queues#

Python
# Waiting requests that hold KV blocks are always drained before
# self.waiting: a block-holder must never sit behind a request whose
# failed allocation would stop the scheduling scan.
self.kv_holding_waiting = create_request_queue(self.policy)

A request can be “waiting” while already holding blocks: for example one whose KV has been loaded from another machine by a KV connector (19.b) and is about to resume, or a streaming-input session between chunks. Those sit in kv_holding_waiting and are always considered first. The comment explains why: the ordinary queue stops at the first request that does not fit (17.a), and a request that is occupying memory must never be stuck behind it.

Requests that are not ready (grammar still compiling, KV still arriving) are skipped, not waited on: they are set aside during the pass and put back at the front afterwards, in their original order.

What priority does and does not do#

Priority affects exactly two decisions:

  1. Which waiting request is considered next (the heap’s order).
  2. Which running request is evicted when memory runs out.

It does not let a waiting high-priority request evict a running low-priority one. Pass 2 of the scheduler never preempts; if the head of the queue does not fit, admission simply stops for this step. A burst of high-priority requests waits for memory to free up naturally.

It also does not reorder the token budget inside a step: running requests are served in admission order, whatever their priority.

When preemption happens#

Only in pass 1, only when a running request needs another block and the pool cannot give one:

Python
new_blocks = self.kv_cache_manager.allocate_slots(request, num_new_tokens, ...)
if new_blocks is not None:
    break                                   # fine
if self.connector is not None and self.connector.has_pending_block_frees():
    break                                   # blocks are about to come back; just wait
# The request cannot be scheduled.
# Preempt the lowest-priority request.
if self.policy == SchedulingPolicy.PRIORITY:
    preempted_req = max(self.running, key=lambda r: (r.priority, r.arrival_time))
else:
    preempted_req = self.running[-1]
# A deferred free will not help with immediate allocation.
if not self._request_blocks_can_be_freed(preempted_req):
    break
...
self._preempt_request(preempted_req, scheduled_timestamp, ...)
preempted_reqs.append(preempted_req)
if preempted_req == request:
    # No more request to preempt. Cannot schedule this request.
    break

The victim is:

  • under FCFS, the last element of running: the most recently admitted request, which has usually done the least work;
  • under priority, the request with the numerically largest priority value, ties broken by latest arrival.

The loop repeats until the allocation succeeds or the victim is the very request that needed memory, in which case that request evicts itself.

Under the priority policy the victim may already have been scheduled earlier in this same step. The code then unwinds that decision, removing it from the scheduled list and returning its tokens (and any multimodal encoder budget) before evicting it.

The two checks with a KV connector are new in recent releases. If a connector is still moving blocks out and will free them shortly, or if the victim’s blocks cannot be freed yet because an in-flight transfer may still write to them (17.d), preempting would not help, so the request just waits a step.

What preemption does to the victim#

Python
def _preempt_request(self, request, timestamp, drop_stale_output=False):
    self._free_request_blocks(request)
    self.encoder_cache_manager.free(request)
    request.status = RequestStatus.PREEMPTED
    request.num_computed_tokens = 0
    ...
    request.num_preemptions += 1
    # Put the request back to the waiting queue.
    self.waiting.prepend_request(request)

Three facts follow.

Everything is recomputed. num_computed_tokens = 0. There is no partial preemption and no built-in swap to CPU memory (vLLM V1 dropped swapping; the docs say recomputation “has lower overhead in the V1 architecture”). When re-admitted, the gap is the whole of num_tokens: the prompt and every output token generated so far go through the model again as one prefill.

It goes to the front. Under FCFS a preempted request goes ahead of everything already waiting, so it is the first to return. Under the priority policy “front” has no meaning; it re-enters the heap at its priority.

The output is kept. Tokens already streamed to the client stay in the request. Nothing is sampled twice; the model re-reads them. The client sees a pause, then the stream continues.

And one fact about the step: if anything was preempted, pass 2 is skipped (if not preempted_reqs and ...). The scheduler does not evict one request and admit another in the same breath.

The prefix cache softens the blow#

Freeing a block does not erase it. A freed full block keeps its hash and joins the back of the free queue (17.e). When the victim is re-admitted, the ordinary prefix-cache lookup runs, and every one of its blocks that was not reused in the meantime is a hit:

preempted with 3,000 tokens computed  →  187 full blocks freed, hashes intact
re-admitted 40 ms later               →  cache lookup finds, say, 150 of them
recompute                              →  600 tokens instead of 3,000

How much is recovered depends on how much of the pool was reused between eviction and return. Under sustained memory pressure, the situation that caused the preemption, it is often “not much”.

If a KV offloading connector is configured (--kv-offloading-size, 14.k), blocks it has copied to CPU memory can also be found by the connector lookup on re-admission and loaded back instead of recomputed. How much that saves depends on the connector and what it had stored.


6. Under the hood#

The picture#

flowchart LR
  subgraph Q["Waiting"]
    direction TB
    KH[("kv_holding_waiting<br/><small>drained first</small>")]
    WQ[("waiting<br/><small>deque (fcfs) or heap (priority)</small>")]
  end
  WQ -->|"admitted: slots, budget, whole prompt fits"| RUN[":i-zap: <b>running</b><br/><small>a list, in admission order</small>"]
  KH --> RUN
  RUN -->|"needs a block, pool empty"| V{"choose a victim"}
  V -->|"fcfs: last admitted"| PRE[":i-triangle-alert: <b>preempt</b><br/><small>free all blocks<br/>num_computed_tokens = 0</small>"]
  V -->|"priority: worst priority,<br/>then latest arrival"| PRE
  PRE -->|"front of the queue"| WQ
  RUN -->|"finished"| DONE[":i-check: <b>free blocks</b>"]
  class KH,WQ memory
  class RUN compute
  class V queue
  class PRE warn
  class DONE neutral

The watermark, in allocate_slots#

Python
watermark_blocks = 0
# The watermark is applied to waiting/preempted requests only, and only
# when there's at least one request already scheduled.
if has_scheduled_reqs and request.status in (
    RequestStatus.WAITING,
    RequestStatus.PREEMPTED,
):
    watermark_blocks = self.watermark_blocks

It never blocks a running request from growing, and never blocks the only request in the system. It is purely an admission margin: --watermark 0.05 keeps 5% of blocks free for running requests to grow into.

Simulating the cost of concurrency#

Six identical requests, a cache that cannot hold them all at full length, and a varying max_num_seqs. The program counts preemptions, the tokens computed more than once, and the longest freeze any client saw.

Go
package main

import "fmt"

const (
	blockSize   = 16
	totalBlocks = 48 // 768 tokens of KV cache
)

type req struct {
	id                       string
	prompt, maxNew           int
	output, computed, blocks int
	lastToken                int // step at which it last produced a token
}

func (r *req) total() int { return r.prompt + r.output }

func blocksFor(tokens int) int { return (tokens + blockSize - 1) / blockSize }

// run serves six identical requests and reports how much work was repeated.
func run(maxSeqs int) (steps, computedTokens, preemptions, worstStall int) {
	var waiting, running []*req
	for i := 0; i < 6; i++ {
		waiting = append(waiting, &req{id: string(rune('A' + i)), prompt: 64, maxNew: 200})
	}
	free := totalBlocks

	for len(waiting)+len(running) > 0 {
		steps++
		scheduled := map[*req]int{}
		preempted := false

		// Pass 1: running requests. On allocation failure, preempt the most
		// recently admitted request (FCFS policy) and try again.
		for i := 0; i < len(running); i++ {
			r := running[i]
			n := r.total() - r.computed
			need := blocksFor(r.computed+n) - r.blocks
			evictedSelf := false
			for need > free {
				victim := running[len(running)-1]
				running = running[:len(running)-1]
				free += victim.blocks
				victim.blocks, victim.computed = 0, 0 // all of its KV is gone
				waiting = append([]*req{victim}, waiting...)
				preempted = true
				preemptions++
				if victim == r {
					evictedSelf = true
					break
				}
			}
			if evictedSelf {
				break
			}
			free -= need
			r.blocks += need
			scheduled[r] = n
		}

		// Pass 2: admit, unless this step had to preempt.
		for !preempted && len(waiting) > 0 && len(running) < maxSeqs {
			r := waiting[0]
			need := blocksFor(r.total()) // a resumed request re-reads prompt AND output
			if need > free {
				break
			}
			waiting = waiting[1:]
			running = append(running, r)
			free -= need
			r.blocks = need
			scheduled[r] = r.total()
		}

		keep := running[:0]
		for _, r := range running {
			if n, ok := scheduled[r]; ok {
				r.computed += n
				computedTokens += n
				if r.computed == r.total() {
					if r.output > 0 {
						worstStall = max(worstStall, steps-r.lastToken)
					}
					r.output++
					r.lastToken = steps
				}
			}
			if r.output == r.maxNew {
				free += r.blocks
				continue
			}
			keep = append(keep, r)
		}
		running = keep
	}
	return
}

func main() {
	const useful = 6 * (64 + 200 - 1) // every token computed exactly once
	fmt.Printf("KV cache: %d blocks. One request grows to %d blocks.\n\n", totalBlocks, blocksFor(264))
	fmt.Printf("%-12s %6s %12s %16s %8s %22s\n",
		"max_num_seqs", "steps", "preemptions", "tokens computed", "wasted", "longest gap in a stream")
	for _, seqs := range []int{2, 3, 4, 6} {
		steps, computed, pre, stall := run(seqs)
		fmt.Printf("%-12d %6d %12d %16d %7.0f%% %16d steps\n",
			seqs, steps, pre, computed, 100*float64(computed-useful)/float64(useful), stall)
	}
}

Output:

KV cache: 48 blocks. One request grows to 17 blocks.

max_num_seqs  steps  preemptions  tokens computed   wasted longest gap in a stream
2               600            0             1578       0%                1 steps
3               414            2             2083      32%                8 steps
4               400            2             2026      28%               72 steps
6               342            4             2298      46%              143 steps

How to read it: with max_num_seqs = 2 nothing is ever evicted and every stream is smooth, but the work takes the most steps. Admitting more finishes sooner overall (the extra concurrency outweighs the repeated work in this run), while up to 46% of all computation is wasted and one client watches its stream freeze for 143 steps. Which row is “best” depends on whether you sell throughput or a smooth stream. (The program has no prefix cache, so recomputation is the worst case.)


7. Performance implications#

  • A preemption costs a prefill of the whole sequence so far, minus any prefix-cache hits. Late in a long answer that can be thousands of tokens.
  • The victim’s client sees a freeze, and the step that preempts admits nobody, so queue time rises for everyone.
  • FCFS picks the cheapest victim on average (least work done). Priority may pick an expensive one if it has the worst priority.
  • A steady preemption rate wastes a large share of the GPU, as the table shows. A handful per hour is harmless.

8. Production implications#

How to see it#

  • Each preemption records a PREEMPTED event on the request and increments the vllm:num_preemptions counter (19.c).
  • For a client it appears as an inter-token gap far above normal, in the middle of a stream.
  • vllm:kv_cache_usage_perc sitting at or near 1.0 is the leading indicator.

Ways to make it rare#

SettingEffectCost
Lower --max-num-seqs (or --max-num-active-seqs)Fewer requests growing at onceLower peak throughput when requests are short
--watermark 0.05Keep 5% of blocks free when admitting, so running requests have room to growSlightly fewer concurrent requests
Lower --max-model-lenCaps how far any request can growLong requests rejected up front
More KV memoryRaise --gpu-memory-utilization, quantise weights or KV cache (13.h), use a larger GPU or more tensor parallelism (17.h)Hardware or some quality

The default admission rule already helps: scheduler_reserve_full_isl refuses a request whose whole prompt does not fit. What it cannot know is the length of the answer.

Priority in practice#

Turn on --scheduling-policy priority only behind a gateway that sets the field; otherwise any client can claim priority 0 over others (23.i). Remember that priority does not shorten the wait of a high-priority request when the cache is full of low-priority ones; it only makes those low-priority ones the first victims.


9. Common mistakes#

  1. Thinking a high-priority arrival interrupts running work. It waits for memory like anyone else.
  2. Assuming “higher priority number = more important”. In vLLM a lower number runs first.
  3. Treating preemptions as harmless. Each one recomputes a whole sequence and freezes a stream.
  4. Looking for a swap setting. V1 always recomputes; CPU offloading is a separate connector feature.
  5. Raising max_num_seqs to raise throughput on a server that is already preempting.

10. Hands-on exercise#

  1. Change totalBlocks to 102 (six requests at full length). Confirm preemptions vanish at every concurrency. That is the “more KV memory” row of the table.
  2. Change the victim rule to evict the first element of running (the oldest request). What happens to wasted tokens, and why is the real rule the opposite?
  3. On a test server, start with --num-gpu-blocks-override 200 --max-num-seqs 16 and send 16 long generations. Watch vllm:num_preemptions in /metrics. The config describes this flag as “Used for testing preemption.”

11. Interview questions#

  1. Under FCFS, which running request is evicted, and why that one?
  2. After a preemption, are the tokens the client already received generated again?
  3. A high-priority request arrives while the cache is full of low-priority requests. What happens to it?
  4. Why does a step that preempts admit no new requests?
  5. Why does vLLM keep a separate queue for waiting requests that already hold blocks?

12. Further reading#

Checked on 12 November 2026, against the v0.32.0 tag.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in