Pidoku

Request Scheduling and Priorities

Module 20 Lesson 20.k 1h Difficulty 4/5

Prerequisites 12.j, 20.c, 21.f


Before you start: words you need#

WordPlain meaning
Scheduling policyThe rule that decides which waiting request starts next.
Priority classA label such as “interactive” or “batch” that says how urgent a request is.
StarvationA request that never runs because more urgent ones keep arriving.
AgingRaising a request’s priority the longer it waits, so nothing waits forever.
Fair shareEach tenant (customer or team) getting its agreed fraction of capacity when everyone is busy (21.f).
Shortest job firstRunning the shortest request first. Best average latency, but needs to know lengths in advance.
Earliest deadline firstRunning the request whose deadline is nearest.
PreemptionThrowing a running request out to make room; in vLLM it is recomputed later (17.c).

1. What is it?#

At every step the engine decides:

1. which waiting requests to admit
2. how to split the step's token budget between prefill and decode
3. whether to preempt a running request
4. in what order to consider them all

Lessons 12.j and 17.a covered the mechanism, and 17.c shows exactly how vLLM implements priorities. This lesson is about policy: whether a multi-tenant service is fair, whether “premium” and “batch” tiers mean anything, and whether long requests starve. Queue bounds and admission are 20.c.

Facts checked on 12 November 2026.


2. Why does it matter?#

First come, first served is fine while there is spare capacity. The moment demand exceeds capacity, even for a few minutes, someone must wait, and the policy decides who:

  • the paying user typing in a chat window, or the overnight evaluation job;
  • the tenant who sends ten requests a second, or the one who sends one;
  • the 50-token question, or the 50,000-token document summary.

Without a deliberate policy, the answer is “whoever arrived first”, which under a burst means everyone waits equally and nobody’s SLO holds.


3. Simple analogy#

An emergency department’s triage desk.

Critical patients go first (priority). But a patient with a broken wrist cannot wait forever just because ambulances keep arriving, so the longer someone waits, the higher up the list they move (aging). Two clinics sharing the department each get their agreed share of doctors (fair share). And a patient who will only be seen after the clinic closes is told so at the door, not at midnight (deadline-aware admission).


4. Tiny example: starvation and aging#

32 slots, mean service 2 s, so capacity is 16 requests per second. Batch traffic arrives at 2 per second. Interactive traffic arrives at 11 per second, except for a 5-minute surge to 16 per second, which on its own is more than the whole capacity. When a slot frees, the waiting request with the highest score starts. With aging, waiting agingSec seconds is worth one priority class.

Go
// aging.go — strict priority starves the low class under sustained load; aging bounds the wait.
package main

import (
	"fmt"
	"math"
	"math/rand"
	"slices"
)

type req struct {
	arrive, service float64
	high            bool
}

// run serves requests on `slots` parallel slots. Whenever a slot frees, it starts the waiting
// request with the highest score. agingSec is the wait that cancels the class gap
// (0 = strict priority, -1 = first come first served).
func run(reqs []req, slots int, agingSec float64) (hi, lo []float64) {
	free := make([]float64, slots)
	var waiting []req
	next := 0
	score := func(r req, now float64) float64 {
		switch {
		case agingSec < 0:
			return -r.arrive // oldest first
		case agingSec == 0 && r.high:
			return 1e9 - r.arrive // high class always first, oldest within a class
		case agingSec == 0:
			return -r.arrive
		}
		s := (now - r.arrive) / agingSec // waiting agingSec seconds is worth one class
		if r.high {
			s++
		}
		return s
	}
	for next < len(reqs) || len(waiting) > 0 {
		k := slices.Index(free, slices.Min(free))
		now := free[k]
		for next < len(reqs) && (reqs[next].arrive <= now || len(waiting) == 0) {
			waiting = append(waiting, reqs[next])
			now = math.Max(now, reqs[next].arrive)
			next++
		}
		best := 0
		for i := range waiting {
			if score(waiting[i], now) > score(waiting[best], now) {
				best = i
			}
		}
		r := waiting[best]
		waiting = slices.Delete(waiting, best, best+1)
		free[k] = now + r.service
		if r.high {
			hi = append(hi, now-r.arrive)
		} else {
			lo = append(lo, now-r.arrive)
		}
	}
	return hi, lo
}

func pct(xs []float64, p int) float64 {
	slices.Sort(xs)
	return xs[len(xs)*p/100]
}

func main() {
	rng := rand.New(rand.NewSource(5))
	// 32 slots, mean service 2 s → capacity 16 requests/s. Batch (low) traffic: 2/s.
	// Interactive (high): 11/s, except a 5-minute surge to 16/s (over capacity on its own).
	var reqs []req
	for t := 0.0; t < 3600; {
		high := 11.0
		if t > 1200 && t < 1500 {
			high = 16
		}
		t += rng.ExpFloat64() / (high + 2)
		reqs = append(reqs, req{t, 2 * rng.ExpFloat64(), rng.Float64() < high/(high+2)})
	}
	fmt.Println("policy                 high p50  high p99   low p50   low p99   low max  (wait, s)")
	for _, p := range []struct {
		name  string
		aging float64
	}{{"first come first served", -1}, {"strict priority", 0}, {"priority + 10 s aging", 10}, {"priority + 30 s aging", 30}} {
		hi, lo := run(reqs, 32, p.aging)
		fmt.Printf("%-22s %9.1f %9.1f %9.1f %9.1f %9.0f\n", p.name,
			pct(hi, 50), pct(hi, 99), pct(lo, 50), pct(lo, 99), slices.Max(lo))
	}
}

Output (one simulated hour, waits in seconds):

policy                 high p50  high p99   low p50   low p99   low max  (wait, s)
first come first served       0.0      32.4       0.0      32.4        34
strict priority              0.0       4.5       0.0     242.0       269
priority + 10 s aging        0.0      30.9       0.0      40.7        42
priority + 30 s aging        0.0      28.2       0.0      58.0        60

How to read it:

  • First come first served treats both classes the same: during the surge everyone waits up to half a minute.
  • Strict priority protects interactive users (p99 4.5 s) by starving batch requests: some wait four and a half minutes, until the surge ends.
  • Aging puts a ceiling on the batch wait (42 s with 10 s aging, 60 s with 30 s) and pays for it with interactive tail latency during the surge.
  • No policy creates capacity. During the surge the system is short of about 2 requests per second; the policy only decides who absorbs that.

5. Technical explanation#

The policies#

FIRST COME FIRST SERVED (FCFS)
  ✓ simple, no starvation        ✗ no way to express urgency
  → vLLM's default (--scheduling-policy fcfs)

PRIORITY CLASSES
  ✓ expresses tiers              ✗ starvation without aging
  → vLLM --scheduling-policy priority; SGLang --enable-priority-scheduling

FAIR SHARE (weighted fair queueing, deficit round robin)
  ✓ tenants get their share whatever they send   ✗ per-tenant bookkeeping
  → 21.f implements it; llm-d's flow control does it in the router

SHORTEST JOB FIRST
  ✓ provably lowest average wait ✗ needs lengths in advance; starves long jobs
  → only as a light preference, from an estimate (below)

EARLIEST DEADLINE FIRST
  ✓ maximises deadlines met      ✗ needs deadlines and cost estimates
  → when clients send deadlines

Practical recommendation: two or three priority classes with aging, fair share between tenants inside a class, and chunked prefill (12.k) so one long prompt cannot block a step.

Priority with aging#

effective_priority = class_priority + wait_time / aging_rate

  class priority: interactive = 2, standard = 1, batch = 0
  aging rate:     10 s per class

  → a batch request that has waited 20 s ranks with a fresh interactive one

The aging rate turns starvation from an accident into a number you choose: roughly, the longest a lower class waits behind a stream of higher-class work. Section 4 shows the trade: the shorter the bound, the more the top class pays during a surge.

Go
func effectivePriority(r *Request, now time.Time) float64 {
	wait := now.Sub(r.ArrivalTime).Seconds()
	return r.ClassPriority + wait/agingRateSeconds // waiting raises priority: nobody starves forever
}

Where priority lives: router and engine#

A fleet has two places to order requests, and they must agree:

ROUTER (flow control)                       ENGINE (per replica)
holds requests before any replica           orders its own waiting queue
decides which tenant or class goes next     decides which request is admitted next
sheds load when everything is full          picks the preemption victim
sees the whole fleet                        sees only its own memory
  • In the router. llm-d 1.0 (October 2026) has priority- and fairness-aware flow control with controlled load shedding. A request’s priority comes from an objective the platform defines (InferenceObjective, which moved from the Gateway API Inference Extension to llm-d in August 2026), selected by a request header.
  • In the engine. vLLM takes a priority integer per request when started with --scheduling-policy priority; lower values run first. SGLang’s priority scheduling runs higher values first by default (--schedule-low-priority-values-first reverses it). Map your classes explicitly for each engine.

They also differ in what priority can do. In vLLM, priority orders the waiting queue and picks who is evicted when memory runs out, but a newly arrived high-priority request does not preempt a running low-priority one; it waits for memory to free (17.c). SGLang can preempt running requests for an arrival whose priority is higher by at least --priority-scheduling-preemption-threshold (10 by default). If you need hard isolation for a premium tier, give it its own replicas.

Approximating shortest job first#

You cannot know the output length in advance, but you can estimate it:

SIGNALS
  max_tokens (the client's cap)            an upper bound
  prompt length                            weak
  task type (system prompt, endpoint)      moderate
  this tenant's history for this task      good
  a small model trained to predict length  research and early products

ESTIMATE
  expected_output ≈ min(max_tokens, tenant's p80 for this task type)
USE IT FOR                                 NOT FOR
✓ admission: will it fit in the KV cache?  ✗ strict ordering: a noisy estimate
✓ a light preference for short jobs           starves whatever it guesses wrong
✓ routing long generations to their own pool (20.f)

llm-d’s router goes a step further and scores replicas with a latency predictor trained on recent requests, choosing the replica expected to meet the request’s time-to-first-token and inter-token targets.

Deadline-aware scheduling#

IF CLIENTS SEND DEADLINES (a gRPC deadline, or a header):

  1. refuse at admission if the deadline cannot be met
       estimated_finish = now + expected queue wait + prefill estimate
                        + expected_output × inter-token latency
       if estimated_finish > deadline: reject now (fast 503)
  2. drop queued requests whose deadline has passed: pure waste
  3. order by earliest deadline among the rest

Deadline propagation is under-used, and fits agents well: each step of an agent’s task inherits a share of the task’s overall time limit.

Preemption policy#

When running requests outgrow the KV cache, someone is evicted:

VICTIM
  most recently admitted     least work lost; vLLM's choice under FCFS
  lowest priority            respects tiers; vLLM's choice under priority
                             (ties broken by latest arrival)
  largest KV                 frees most memory, but keeps hitting long requests

RECOVERY
  recompute: drop the KV, prefill again when re-admitted (vLLM's only mode)
             the prefix cache often keeps much of it, so the redo is cheaper than it looks
  swap:      copy KV to host memory and back; older engines did this (14.k for the costs)

Preemption is a signal, not just a mechanism. If more than about 1% of steps preempt, the engine is admitting more than its memory holds: lower the concurrency cap, add vLLM’s --watermark headroom, or add capacity (20.d).


6. Under the hood: one step with priorities in vLLM#

With --scheduling-policy priority, vLLM keeps the waiting queue as a heap ordered by (priority, arrival_time, request_id). Each step (17.a, 17.c):

pass 1  running requests get their next tokens, oldest first;
        if one cannot get a KV block, evict max(running, key=(priority, arrival_time))
        until it fits, or it evicts itself
pass 2  pop the waiting heap while the token budget and the KV cache allow;
        stop at the first request that does not fit (no evictions here)

Two consequences matter for policy:

  • Priority acts at admission and at eviction, not inside a step: running requests share the budget in admission order whatever their priority.
  • Because pass 2 stops at the first request that does not fit, a large high-priority request at the head of the heap holds back smaller ones behind it until memory frees.

7. Performance implications#

  • Priority moves latency; it does not remove it. Section 4: protecting the top class during a surge costs the bottom class minutes. Make sure the bottom class can afford it.
  • Fair share protects the quiet tenant. Without it, the tenant that sends the most takes the most during contention (21.f).
  • Mixing workload types in one scheduler compromises all of them. Each wants different settings:
WorkloadWhat mattersScheduler and engine settings
Interactive chatTime to first token, smooth streamingSmall token budget, headroom, rare preemption
Batch, offlineTokens per GPU-hourLarge budget and batch; preemption is cheap; run in quiet hours
Agents (many short turns, long shared prefix)Per-turn latency, cache reuseAffinity routing (20.f, 21.h) matters more than ordering; deadlines
Retrieval (long prompts, short answers)Prefill throughputLarge budget, prefix caching for repeated documents, own pool

When several large workloads share a model, give them separate pools with different settings (21.g) instead of one compromise scheduler.


8. Production implications#

  • Two or three priority classes with aging. Choose the aging rate to state the starvation bound.
  • Fair share between tenants inside a class (21.f).
  • Chunked prefill on (12.k) before tuning anything else here.
  • Decide where ordering happens: router flow control for fleet-wide fairness and shedding, engine priority for eviction order. Map the classes consistently.
  • Check the priority direction for each engine: vLLM low-first, SGLang high-first by default.
  • Estimate output length from tenant history; use it for admission and routing, not strict ordering.
  • Watch preemptions. Above about 1% of steps, fix the cause.
  • Honour client deadlines if you get them.
  • Separate pools for workload types with different goals.

9. Common mistakes#

  1. Strict priority without aging. The lowest class starves during every surge.
  2. Strict shortest-job-first on a noisy length estimate. Starvation for whatever it misjudges.
  3. Expecting priority to interrupt running work in an engine that does not preempt on arrival.
  4. Reversed priority numbers when moving between engines.
  5. Tolerating a high preemption rate. It wastes work; fix the cause.
  6. One scheduler configuration for every workload type.
  7. Ignoring client deadlines. Serving answers nobody will wait for.

10. Hands-on exercise#

A. Run the simulation. Run aging.go. Make the surge last 15 minutes instead of 5. What happens to the batch wait under strict priority, and under 10 s aging?

B. Choose an aging rate. Your batch SLO is “start within 2 minutes”. Which aging rate meets it during the 15-minute surge, and what does it cost the interactive p99?

C. Real priorities. Start vLLM with --scheduling-policy priority. Saturate it with priority: 10 requests, then send a stream of priority: 0 requests. Measure time to first token for each. Do the high-priority requests interrupt running ones? Check against 17.c.

D. Length estimation. From request logs, build a per-tenant, per-task output-length estimator. Measure its p50 and p90 error. Is it good enough for admission? For ordering?

E. Separate pools. Configure two pools, one for chat and one for retrieval, with different token budgets. Compare each workload’s SLO attainment against one shared pool.


11. Interview questions#

  1. What does the scheduler decide at each step?
  2. How do you prevent starvation with priority scheduling, and how do you choose the aging rate?
  3. Why not use shortest-job-first, and how would you approximate it?
  4. In vLLM, can a high-priority request preempt a running low-priority one? What about SGLang?
  5. Where should fairness between tenants be enforced in a fleet, and why there?
  6. What does a preemption rate above 1% tell you, and what do you change?
  7. What is deadline-aware admission, and what does it buy?
  8. Why would you put different workload types in separate pools?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

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