Chapter 21
Scheduling, Batching, and Admission Control
On this page
The scheduler allocates compute time, KV memory, and latency slack across requests whose work is revealed incrementally. It is a policy engine with explicit invariants, not a queue attached to a GPU.
With phase costs and KV lifetime established, the scheduler is where they collide. Every iteration must divide the replica between the token cadence promised to active requests and the first-token latency promised to queued ones - the running service's two SLOs are exactly that tension, and its roughly 200-conversation KV capacity is the budget being divided.
Iteration-level scheduling¶
Autoregressive requests finish at different output lengths. A static batch keeps completed slots idle until the batch finishes; an implementation that also waits to return results can delay short responses further. Iteration-level scheduling rebuilds the active batch at token or bounded-chunk boundaries. Finished and cancelled requests leave; newly admitted work can enter.
Continuous batching fills freed decode slots over time. The scheduler gains efficiency but must decide admission, phase mixing, fairness, and shape compatibility at every boundary.
An iteration may contain decode tokens, prefill chunks, encoder work, or verification tokens. The engine exposes feasible work units; the scheduler chooses a set under budgets for tokens, sequences, memory, execution time, graph shape, and distributed compatibility.
Scheduler state¶
Track per request:
- phase and tokens already processed;
- prompt remainder and generated length;
- deadline, priority, tenant weight, and arrival time;
- estimated next-iteration and remaining work;
- current KV blocks, reserved growth, and prefix ownership;
- model, adapter, sampling, grammar, and speculative mode;
- compatible engine/graph variants and device placement;
- cancellation and client-backpressure state.
Track global state such as free and reserved KV blocks, active batch composition, queue age, measured iteration-time curves, cache locality, device health, adapter residency, and SLO risk.
Token and time budgets¶
A maximum sequence count is a weak batching control because one prefill token and one long-context decode token have different cost. Use one or more measured budgets:
- total uncached prefill tokens;
- active decode sequences grouped by context bucket;
- predicted iteration time;
- KV blocks allocated now and at the next horizon;
- communication volume or pipeline microbatches;
- verification tokens for speculation.
Cost estimates need not be perfect, but they should be calibrated from telemetry and bounded conservatively near deadlines. When estimates drift after an engine or model update, the scheduler can violate SLOs even though kernels improved.
Phase mixing and chunked prefill¶
Decode-first scheduling protects token cadence but can starve new prefills under sustained generation. Prefill-first scheduling reduces queue delay for new arrivals but can create generation stalls. Chunked prefill bounds interference and creates a tunable compromise.
A robust policy first reserves enough decode work to protect imminent deadlines, then fills remaining predicted iteration time with prefill chunks. Aging increases the priority of waiting prefills. Batch jobs may use a separate queue and consume explicitly allocated slack rather than opportunistically overwhelming interactive traffic.
Pipeline-parallel execution may prefer iterations with similar compute to reduce bubbles. Chunk size should therefore consider stage balance as well as a single-device token budget.
The running service shows why the compromise matters. If an uninterrupted 2,000-token prefill takes more than 100 ms, it can push active decodes past the gap threshold. Chunks of a few hundred tokens are a starting hypothesis; only measured iteration times show whether they protect cadence and how much first-token delay they add. Even small chunks do not guarantee a gap bound when decode, collectives, and host work already consume the budget.
Fairness and priorities¶
FIFO is predictable but allows a huge prompt to delay many small requests. Shortest-remaining-processing-time improves mean latency but can starve large jobs and relies on unknown output length. Earliest-deadline-first protects explicit deadlines when service time is estimable. Weighted fair service can allocate token or compute time across tenants.
Charge service in a resource-correlated unit, not requests. One long-context decode step can cost far more than a short-context step; one prefill can consume thousands of tokens. Maintain deficit or virtual-time accounting and add aging so low-priority work eventually progresses.
Priority inversion appears when a high-priority request depends on a low-priority resource: an adapter load, a shared prefix owner, a pipeline peer, or memory held by a paused request. The scheduler must either inherit priority, preempt or evict safely, or route around the dependency.
Admission control¶
Admission determines whether a request can enter without breaking promises already made. Estimate:
- prompt and encoder work;
- minimum and worst-credible KV growth;
- model and adapter residency;
- deadline slack and queue position;
- compatible replica capacity;
- tenant quota and global reserve.
Possible outcomes are admit, defer, route, downgrade under an explicit policy, truncate if the API allows it, or reject quickly with a retry signal. Do not admit unlimited work into an invisible queue. An honest overload response protects existing requests and gives upstream systems a chance to shed or reroute load.
Reserve memory for at least the next scheduling horizon. Reserving maximum output for every request wastes capacity; reserving nothing risks mid-generation failure. A probabilistic growth model can improve utilization, but keep a hard safety reserve and define what happens when predictions are wrong.
Cancellation and backpressure¶
Cancellation is a capacity feature. Propagate it from disconnected client to gateway, queue, scheduler, worker, and KV allocator. If a kernel cannot be interrupted, mark the request and release resources at the next safe boundary. Avoid publishing unaccepted speculative state or streaming tokens after cancellation.
A slow client can make stream buffers grow while the GPU continues generation. Set bounded buffers and a policy: pause the request, reduce its scheduling share, spill within limits, or cancel. Paused requests still occupy KV memory, so waiting indefinitely is not free.
Executable scheduling and ownership traces¶
examples/serving_trace.py implements bounded chunked prefill, round-robin service, full prompt-plus-output reservation, rejection, and release. Each synthetic tick executes one unit; it makes no claim about GPU batching efficiency or milliseconds. A long prefill and a short request both progress; an oversized concurrent request is rejected before allocation.
Example status: Runnable reference; standard library only.
from examples.serving_trace import Request, simulate
report = simulate([Request("long", 0, 12, 3),
Request("short", 1, 2, 2),
Request("overload", 1, 20, 4)], capacity=24)
assert report["requests"]["overload"]["status"] == "rejected"
assert report["requests"]["short"]["tokens"][0] < report["requests"]["long"]["tokens"][0]
assert report["peak_reserved_tokens"] <= 24
The same module implements shared-page reference counts and copy-on-write. Fork a prefix ending in a partial page, append on one branch, cancel the other, and verify the survivor's contents before final reclamation. The test uses distinct physical page identities after divergence. Reading logical tokens in physical allocation order would fail when the page table is permuted.
A decode-only priority policy has no progress guarantee for waiting prefills under a continuous decode load. The toy's rotating queue supplies such progress for a finite admitted population, at the cost of decode gaps. A production scheduler must budget that tradeoff using measured phase costs and token deadlines. Fair ordering does not make an infeasible admitted load schedulable.
Overload and headroom¶
Queueing latency can grow sharply near saturation. Variable output lengths increase service-time variability; whether the distribution is heavy-tailed must be established from the workload rather than inferred from variability alone. Operate with headroom sized for bursts, node loss, and estimation error. The right utilization target is the highest level that preserves goodput and recovery reserve, not a universal percentage.
During overload, apply a declared hierarchy: protect in-flight interactive sequences, stop low-value prefills, enforce tenant quotas, shed batch traffic, reduce optional speculative or best-of work, and reject new requests before memory is exhausted. Quality-changing degradation requires product authorization and telemetry.
Design Exercises¶
- Design an iteration-level scheduler for mixed interactive and batch traffic.
- How do you prevent long prefills from breaking token cadence without starving them?
- What should admission control do when KV memory is nearly full?
- How would you measure and enforce fairness across tenants with different request shapes?
- Explain cancellation and slow-client handling end to end.
- Why can intentionally lower accelerator utilization improve fleet goodput?
Worked Solutions¶
1. Mixed scheduler¶
Maintain separate objective classes but one global capacity and memory governor. At each boundary, reserve imminent interactive decodes by deadline, add aged interactive prefills in bounded chunks, and spend declared slack on batch work using weighted service accounting. Predict iteration time and KV growth, group compatible shapes, and reserve before launch. Enforce tenant quotas, propagate cancellation, and expose quick rejection during overload. Evaluate goodput and starvation, not only average throughput.
2. Long prefills¶
Split them into cost-bounded chunks. Reserve decode time against the token-gap SLO, then schedule chunks in remaining capacity. Increase a waiting prompt's virtual priority with age and allocate a minimum service share under the admitted-load policy so continuous decode load cannot starve it. Adapt chunk size to measured phase cost and pipeline balance; report both the observed gap distribution and the added first-token latency paid by the long request.
3. Near-full KV¶
Stop admitting requests whose reserved growth would consume the safety margin. Reclaim cancelled and expired state, evict low-value reusable prefixes or inactive sessions, route to a replica with capacity, and shed lower-priority queued work according to policy. Protect memory promised to active requests. Do not rely on an eventual allocator failure; return a bounded retry or overload response before the pool is exhausted.
4. Fairness¶
Charge tenants in predicted or measured compute-time/KV-time units rather than raw request count. Use weighted deficit or virtual-time scheduling, cap burst debt, and age waiting work. Track service share, queue delay, SLO attainment, rejections, and starvation by tenant and shape class. Account for shared-prefix savings consistently so a cache hit does not accidentally grant unlimited priority or penalize the tenant twice.
5. Cancellation and backpressure¶
The gateway propagates cancellation with request identity; queues remove unstarted work; the scheduler marks in-flight work and excludes it at the next safe boundary; the worker stops sampling and streaming; and the allocator releases private and shared references exactly once. Stream buffers are bounded. A slow client is paused, deprioritized, or cancelled by policy, with its KV occupancy still charged. Races are tested around token commit and speculative rollback.
6. Lower utilization¶
Near saturation, queue delay and tail risk rise sharply, bursts cannot be absorbed, and a node failure can overload the remainder of the fleet. Huge batches may maximize hardware throughput while violating first-token and cadence SLOs. Leaving headroom can admit urgent work sooner, reduce generation stalls, preserve failure reserve, and therefore increase the number of requests completed within contract even though average device utilization is lower.