Scheduling & Coalescing
The worker's scheduler decides which model runs next whenever the GPU is free, and how many queued requests one execution should serve. It is a weighted-fair, coalescing dispatch engine: concurrent requests land on per-model queues, a single dispatch loop runs exactly one GPU execution at a time, same-model requests are merged into one batched execution at a compiled size, and GPU time is shared by relative model weight, each model charged the device time it is measured to use. It holds the model registry, the backend, the device memory pool, the SchedulerConfig, per-model dispatch state, and the optional weight cache. Submit work with ReactantServer.infer and read observability counters with ReactantServer.scheduler_metrics.
Because it serializes the GPU, the scheduler is the component that turns a burst of concurrent requests into a steady stream of full batches. This page covers that worker-side engine and the coalescing it performs. Routing a model's requests across several workers, including the gateway scheduling modes (round_robin, least_outstanding, lpt_packing), is the gateway's job; see Multi-GPU Gateway. Where model weights live and how on-demand loading works is covered in On-demand Weights.
How a request flows through the worker
Each gRPC request arrives on its own task. The request runs its preprocess hook on that task, then is queued on its model's queue (FIFO, so the front is always the oldest request). The dispatch loop wakes when work is available, selects a model, coalesces that model's queued requests into one execution at a compiled batch size, runs it, and hands each caller back its raw output slice; the caller's task runs the postprocess hook on that slice. The loop runs no model.jl code itself, so user hooks never serialize against the GPU.
gRPC requests (one task each)
|
preprocess hook runs on the caller's task
|
per-model queues (FIFO, one per model)
|
+---------+---------+
| dispatch loop | one GPU execution at a time
| select -> coalesce -> run -> slice
+---------+---------+
|
per-request output slices
|
postprocess hook runs on the caller's task
|
replies to clientsA request becomes visible to the dispatch loop only after its preprocess has returned, so the loop never executes a request whose hook work has not finished. Because the hooks run on the per-request tasks rather than on the loop, the CPU-side pre/post work of many requests proceeds in parallel and overlaps the single, serialized GPU execution: while the loop runs one model on the GPU, other requests are being pre/post-processed on other threads.
A single Threads.Condition guards all mutable scheduler state (the per-model queues and the virtual-time, EMA and cost fields) and signals the dispatch loop when work arrives. The loop holds the lock only to select and dequeue; the actual execution runs outside the lock, so producers keep enqueuing during GPU work, and the lock is re-taken briefly afterwards to record the dispatch. Only one execution runs at a time by design, which keeps memory and concurrency reasoning simple.
The dispatch loop runs on its own thread
The supervisor starts each worker with --threads=<compute_threads>,1: a default pool sized to the worker's share of the host for the per-request pre/post tasks, plus one interactive thread. The scheduler pins its GPU dispatch loop to the interactive thread when one exists, so the GPU dispatch is scheduled promptly and is never starved by the hook tasks that saturate the default pool. With no interactive thread the default pool is used; correctness is unaffected, only the overlap.
How long a caller waits
A caller waits for its request's result for at most scheduler.dispatch_timeout_seconds (30 s by default; 0 disables it), counted from submission, so queueing and execution together. Past it the request is withdrawn and the call fails with DEADLINE_EXCEEDED: a request still queued is dropped when the dispatch loop reaches it, without running, and one already executing finishes but its result is discarded. This is the bound that holds when nothing else does. A request whose model's weights read stops making progress fails sooner, with UNAVAILABLE, once the read is abandoned after scheduler.weight_read_stall_seconds (20 s by default, below the dispatch timeout so that such a request can fail over; see On-demand Weights). A client deadline is enforced separately, before dispatch (see edf).
A gRPC call whose client cancels it withdraws its request the same way and is answered CANCELLED, so cancelled work is not run. That depends on gRPCServer reporting the cancellation; gRPCServer 0.1.2 does not yet, so until a release that does, a cancelled call runs as before.
Status codes
Every way a request can fail has one gRPC status, chosen by the kind of failure, so a client and the gateway can act on it (back off, try another replica, give up, re-register shared memory):
| Status | When |
|---|---|
RESOURCE_EXHAUSTED | the model's queue holds max_queue_depth requests, or the worker is at its max_concurrent_requests cap, or /dev/shm has no room for the pages of a shared-memory region the request reads or writes (see Deployment) |
UNAVAILABLE | the worker is shutting down or draining (see Stopping), its dispatch loop has died, (externally managed residency) the model is not resident on this worker, the model cannot be placed on this worker's device now (see On-demand Weights), or the model's weights cannot be read now because reading them, or reading weights on this worker at all, has stalled (see On-demand Weights) |
NOT_FOUND | the model is not served here: never loaded, or unloaded or replaced while the request waited |
DEADLINE_EXCEEDED | the deadline passed before dispatch (the edf laxity drop included), or the dispatch timeout did |
CANCELLED | the client cancelled the call |
INVALID_ARGUMENT | the request itself is wrong: malformed, an input that does not match the model, a requested output the model does not produce, an output larger than its shared-memory slot, or data a preprocess hook rejects with InvalidInputError |
FAILED_PRECONDITION | a shared-memory region this worker does not know (it restarted since the client registered): re-register and retry. Also a region whose object the client has shrunk since registering it, so that it no longer covers what the request reads or writes; registering that object again is refused (INVALID_ARGUMENT) while it is smaller than the window |
INTERNAL | anything else: a failure on the server's side, logged on the worker with its backtrace under a request id; the client is told that id (and the exception text only under grpc.error_detail: full, see Node Configuration) |
The worker's worker_requests_total{status} counts each request under the same status the client receives. Its model label (and that of worker_request_latency_seconds) is the model's name only when the worker serves a model of that name; a request for any other name, unknown or empty, counts under model="_unknown", so names a client makes up add no series. The name is reserved: a worker refuses to load a bundle named _unknown (see Bundles).
If the dispatch loop itself fails with an error no single request can be held to, the worker logs it with its backtrace, reports itself not live and not ready (ServerLive, ServerReady, ModelReady, /healthz, /readyz), answers every queued and later request UNAVAILABLE, and exits with a nonzero code so the node supervisor restarts it.
Decision order
Each time the GPU frees up, the scheduler decides in this order:
- Dispatch a committed meta sub-call first, if one is pending. A meta model's orchestration runs off the dispatch loop and re-enters the scheduler for each sub-call (see Meta Models); those continuations are committed and jump ahead of the discipline scan, at most one per in-flight meta, so a meta already in progress is not stalled behind newly arrived work.
- Otherwise select the next model, according to the configured
discipline:fair(the least device time used for its weight, the default),fifo(oldest queued request), oredf(soonest deadline). - Coalesce the winner. The selected model's queued requests are taken in FIFO order and packed into the largest compiled batch size that fits, padding a partial batch up to the smallest size when needed and always making forward progress on at least the oldest request. The remainder stays queued for the next round.
Disciplines
The discipline selects which model is dispatched next. Coalescing applies underneath all three: whichever model wins, its queue is coalesced in FIFO order.
fair (default)
Each model has a relative weight (default 1.0), and the models that have work queued share the device's time in proportion to their weights. The scheduler does this with start-time fair queueing over measured device time:
- Every dispatch charges its model the time it held the dispatch loop (the measured execution, plus any on-demand weight upload that preceded it) divided by the model's weight. The running total is the model's virtual time.
- When the device frees up, the model with queued work and the least virtual time is dispatched next. Ties go to the model with the oldest queued request, then to the lower name.
- A model that joins the competition (it was idle, is newly loaded, or was waiting for its weights to be read into host memory) starts at the virtual time of the most recent dispatch, never below it. It neither banks credit for the time it was away nor pays for capacity it used while it ran alone.
The discipline is work-conserving: only models with queued work compete, so a model alone in the queue is always served, however much it used before. Because each dispatch is charged its measured time, differences in cost between models are accounted for exactly: a 1 ms model and a 100 ms model of equal weight each get half of the device while both are busy, the cheap one in many short dispatches. Batch size is accounted for the same way: a coalesced dispatch is charged its measured time at the compiled size, padding included.
Guarantees. Let C_i be model i's longest single dispatch and w_i its weight, and let S be the total weight of the models with work queued. While model i has work queued:
- Its wait for its next dispatch is at most
sum over j != i of (C_j + (w_j / w_i) * C_i): one dispatch of each other model, plus the time the others need to catch up withi's own last charge. - Over a stretch of
Tseconds it receives at least(w_i / S) * T - (w_i / S) * sum over j != i of ((w_j / w_i) * C_i + C_j)seconds of device time: its share, less about one dispatch per competing model. - For any two models
iandjthat both stay backlogged, the device timesW_iandW_jthey receive satisfy|W_i / w_i - W_j / w_j| <= C_i / w_i + C_j / w_j, whatever either did before.
The bounds have limits worth knowing:
- They cover only the dispatch-loop time the discipline controls. A committed meta sub-call runs ahead of the discipline (it is charged to its sub-model afterwards, so the sub-model pays for it in later contention), and control commands (residency changes, hot loads, compaction), a weight upload whose dispatch then fails, and anything else that holds the loop uncharged come out of every model's share.
- Selection does not consider the size of the dispatch about to run, so the lag above is up to one dispatch at the model's largest compiled batch;
max_batch_sizebounds it. - Dispatches are not preemptible, so a model with a long program delays every other model by up to that program's length;
C_iin the wait bound is the longest dispatch of each model. - Shares are relative to the models with work queued, not to every loaded model: the share of an idle model goes to the busy ones and cannot be reclaimed later.
recency_penalty_cap and coalescing_discount, the knobs of the recency-deficit ranking this discipline replaced, are still accepted and validated so existing node files load unchanged, but they have no effect. ema_halflife_seconds now only sets the half-life of the recent-compute moving average that ReactantServer.scheduler_metrics reports.
fifo
Under fifo, per-model weights are ignored. The model whose oldest queued request is the oldest overall is served first, with ties broken by model name for determinism. This is the discipline to use when the worker sits behind a gateway that is already doing placement; see "Which discipline to use" below.
edf
Under edf (earliest-deadline-first), the model whose most-urgent queued request has the soonest deadline is served first. The deadline comes from the request's remaining-budget timeout; a request with no deadline is treated as least urgent. Ties break by the model's oldest queued request and then by name, so when all queued requests share a deadline (the common case) edf is exactly fifo. It diverges only to promote a model carrying a request with less budget left, so a meta's sub-call, which inherits the meta's deadline, is served ahead of fresher regular work. Queues stay arrival-ordered (never reordered), and coalescing still draws FIFO from the front, so a request deep behind the batch size advances over successive dispatches of its model rather than jumping the batch.
edf also sheds work it cannot finish in time. Before GPU work begins, a request whose deadline has already passed is dropped under every discipline; under edf a laxity check is added: a request is also dropped if it cannot finish within this dispatch's learned compute cost, so the GPU is not spent on work that will miss anyway (the classic EDF overload failure mode). Dropped requests receive a DeadlineExceeded error (gRPC DEADLINE_EXCEEDED upstream); only feasible requests run, and when none are feasible the execution is skipped entirely. The cost estimate is learned from prior dispatches of the same program (see "Cost learning" below), and the laxity drop is a no-op until the program has been measured. Committed meta sub-calls skip the laxity drop (their earlier stages already spent GPU time) but still honor the hard deadline check.
A dropped request runs nothing, so it measures nothing: an estimate that had grown above every client's budget would shed the program for good. To prevent that, when the laxity margin alone would drop every request of a dispatch and the program's estimate has not been refreshed for 10 seconds, the oldest of those requests runs anyway to measure the program again; the others are still dropped. This happens at most once per 10 seconds per program, so a model whose estimate is right and whose clients' budgets are genuinely too short costs at most one wasted dispatch per interval, while a model shed on an inflated estimate is back in service within one interval.
Note that because edf derives urgency solely from the deadline, issuing different per-client deadlines for the same model reorders that model's service and therefore affects fairness across clients; keep deadlines uniform to retain fifo-like fairness.
Which discipline to use
fair is for workers with no upstream placement authority: a single-GPU worker, or a fleet behind the round-robin gateway, where the worker itself must stop one model from crowding out the rest. Behind a gateway running lpt_packing, the gateway is the fairness and placement authority (see Multi-GPU Gateway), and the worker must run fifo or edf so the two do not fight; fair would double-book GPU time against the gateway's placement decisions. edf is for deadline-sensitive serving, and it degrades gracefully to fifo when clients use uniform deadlines.
Coalescing
Coalescing merges same-model requests into one GPU execution. The selected model's queue is scanned in FIFO order, the requests that fit are concatenated along the batch axis into a single compiled-batch-size dispatch, the execution runs once, and the outputs are sliced back per caller (zeros padding a partial fill are dropped). The remainder stays queued for the next round. The batch sizes themselves come from the bundle's manifest batching spec: a bundle may carry several compiled batch sizes that share one set of weights, and the scheduler picks the executable that matches each coalesced batch without duplicating parameters.
When a model can coalesce
A model coalesces multiple requests only when every executable input and every output carries a batch axis (an all-or-nothing requirement that mirrors the loader's manifest check). Inputs are then concatenated along that axis and outputs split back per request. Otherwise the model serves one request per dispatch. Single unbatched modules (the batch-0 executable) are never coalesced. Inputs without a batch axis are taken from the first request, since they do not vary across the batch.
Only requests that resolve to the same input-shape variant coalesce together. A model compiled for several input shapes (aspect-ratio variants) keeps one executable set per variant over a single shared set of weights, and different shapes cannot be concatenated along the batch axis. The coalescing window is the leading run of same-variant requests at the front of the queue, which keeps the taken set a contiguous prefix (so it can be removed in one step) and preserves FIFO order. A request whose shape has no compiled executable dispatches alone so that the caller gets the precise "no compiled program for input shape" error.
A request also coalesces only when its batched inputs agree on their batch extent, each measured along its own batch axis after preprocessing. A request that sends three rows of one input and two of another (or whose preprocess hook drops a batched input) never shares a dispatch: merged with other requests, its rows would pair with a neighbor's, and the merged shapes could still line up, so the program would run and hand other callers mixed rows. Such a request ends the coalescing window and dispatches alone, with its inputs passed through unpadded, so it fails its own execution with a shape error and the requests queued around it are unaffected. Request validation does not reject it, because preprocess may change an input's row count; the check reads the preprocessed inputs.
Sizing the batch
The scheduler chooses the largest compiled batch size that the queued rows can fill; a partial fill pads up to the smallest compiled size (the compiled shape may therefore exceed the queued rows, and the dispatch runs padded). Coalescing uses only what is queued now; there is no look-ahead.
A per-model max_batch_size caps how many rows are coalesced into one dispatch. The cap does not change compiled shapes: a partial fill still pads up to the smallest compiled size, and a single request larger than the cap is never split, so it dispatches alone (growing the chosen size to the smallest compiled batch that fits it when necessary). Forward progress is guaranteed: an indivisible front request that exceeds the batch size or the cap still dispatches alone rather than being held back, so the oldest request is always served within a bounded number of rounds. A lone request that already fills the dispatch passes its inputs straight through with no concatenation or padding.
Requests larger than every compiled size
A request whose batch exceeds the largest compiled size for its shape variant is split before it is queued. The inputs are cut into pieces of at most the largest compiled size, the pieces are submitted as separate requests so they coalesce with each other and with other traffic exactly as if the client had sent them separately, and the outputs are joined back along each output's batch axis and post-processed once. The whole request's deadline rides along on every piece. This is coalescing run in the other direction: a client that batches 32 against a bundle compiled for [1] gets an answer rather than an error.
Splitting is only sound when the bundle's preprocess hook keeps one client row per executable row (a hook that changes the row count, cropping per image say, breaks the correspondence) and every executable output carries a batch axis to join along. A request whose batched inputs disagree on their batch extent (see above) is never split either, since no one row count cuts every input. A request that cannot be split runs whole and fails at execution with the shape error, as before. This mechanism is separate from max_batch_size, which caps how many rows coalesce into one dispatch and never splits a request.
Why coalescing is the throughput lever
Packing many requests into one execution amortizes the fixed per-launch overhead and, for a model that had to be loaded on demand, the one-time weight transfer, across every item in the batch, so a full batch costs less per item than the same items run one at a time. Coalescing is therefore the reason a worker can absorb bursts: concurrent requests pile onto a model's queue and the loop converts them into a small number of full dispatches instead of paying launch cost once per request.
Turning coalescing off
scheduler.coalescing: false (the default under the regulated profile) makes every dispatch serve exactly one request: the front of the queue, at the smallest compiled size that fits it, padded with zero rows. A request's rows then occupy the same slots of the same program no matter what else is queued, which is what a validated deployment needs; see Reproducibility & Regulated Use. A client's own pre-batched request still runs as one dispatch, and an oversize request is still split into pieces, each of which runs alone.
The cost is the throughput lever above: concurrent requests to a model are served one dispatch each. The gateway does not yet know whether its workers coalesce, so under lpt_packing it still concentrates a model's requests on one replica at a time to feed coalescing that no longer happens. A fleet with coalescing off should prefer routing_fill_mode: spread; see Multi-GPU Gateway.
Cost learning
The scheduler measures the real GPU time of each execution and learns a cost estimate for each compiled program, that is for each input-shape variant and batch size of a model. Variants are kept apart because they can differ in cost far more than batch sizes do (a detector's aspect ratios, say), and one variant's cost says nothing about another's. The estimate feeds the edf laxity check, and decides which programs are long enough (50 ms or more, or not yet measured) to run off the dispatch loop's thread so they do not hold up request intake. The fair discipline does not use it: it charges each dispatch the time it was measured to take.
The estimate is built to resist the outliers a laxity check would otherwise shed on:
- A program's first run is not used. The first execution of a program in the worker process pays one-time costs (lazy initialization, autotuning, cold caches), so it is not taken as the program's cost: the second run seeds the estimate, at the smaller of the two times. At startup, under the fair discipline, warmup runs each compiled variant and size twice on zero-filled inputs for this reason; when the weight cache is enabled with auto-sizing, the startup isolation probe does the same and doubles as this warmup. A program left unmeasured (a failed warmup, or a discipline without warmup) is measured by its first real dispatches, and the
edflaxity check does not shed on it until then. - One measurement moves it a bounded amount. After seeding, the estimate moves toward each measurement as an exponential moving average whose weight depends on time, not on the number of runs:
cost_ema_alpha(default 0.2) for back-to-back runs, rising toward 1 as the estimate ages (the old value's weight halves every 2 s since it was last refreshed), so a program measured once a minute does not hold on to a value from many minutes ago. A rise is capped at a quarter of the estimate per measurement, however slow the run or old the estimate, so one GC pause or cold cache moves it by 25% at most. A fall is not capped, since timing noise makes runs slower, not faster; the estimate never drops below the measurement. - Weight load time is excluded. The measured
compute_timecovers only the model execution, not the on-demand weight load that preceded it, so the estimate reflects steady-state (resident) execution rather than cold-call latency. The fair discipline still charges the load to the model, since it held the dispatch loop.
Per-model configuration
Most models need no tuning: with the default fair discipline, all-default weights yield uniform shares. When you want to change that, per-model overrides live under scheduler.models in the node file, which builds the ModelSchedConfig entries:
global:
scheduler:
models:
resnet50:
weight: 2.0 # relative compute share under fair (default 1.0)
max_batch_size: 8 # cap on rows coalesced per dispatch (default uncapped)weight sets the model's fair share; it must be a positive finite number, and the worker refuses the node file otherwise. residency is also settable per model (the initial residency floor); see On-demand Weights for what the floors mean. max_batch_size caps coalescing rows per dispatch, as described above; it does not change compiled shapes and never splits a request. The full node-file surface, including the global scheduler: block, is in Node Configuration.
max_queue_depth caps each model's queue independently: a full model rejects new requests without affecting admission for the others, so one backlogged model cannot starve the rest of the worker.
Live policy changes
The control plane can adjust scheduling policy on a running worker. ReactantServer.set_policy! updates a model's live weight (consulted by the fair discipline; it raises on an unknown model, and on a weight that is not positive and finite, which the SetModelPolicy RPC answers with INVALID_ARGUMENT). ReactantServer.set_residency! moves a model to a target residency floor; the worker accepts it only under model_control_mode: explicit. Both run on the dispatch thread, the sole mutator of residency, and block until applied; control commands are drained ahead of dispatch selection, so a residency transition takes effect before the dispatch that may depend on it. ReactantServer.compact! frees the resident non-pinned weights so the allocator coalesces its free list, then reloads the listed models, defragmenting the device arena; see On-demand Weights.
Observability
ReactantServer.scheduler_metrics snapshots per-model state: dispatch count, requests served, rows served, total compute, the current recent-compute EMA, queue depth, queue-wait P50/P99, the histogram of dispatched batch sizes, the effective max batch, and residency. The counters are cumulative over the worker's lifetime, so deltas between polls give rates; dispatch_count counts coalesced batch executions, requests_served counts individual requests (at least one per dispatch, more under coalescing), and rows_served counts batch-axis rows, the effective batch size actually executed.
The worker exports these as Prometheus series (worker_dispatch_total, worker_compute_seconds_total, worker_queue_depth, worker_queue_wait_seconds, worker_requests_served_total, worker_rows_served_total, worker_model_max_batch_size, and the residency gauges), tagged per model and per GPU, and the node's metrics endpoint aggregates them. See Monitoring for scraping them.
ReactantServer.control_status is the control-plane view a gateway reads: the worker's residency mode and discipline, and for each model its weight, queue depth, cumulative serving counters, effective max batch, and the wire-facing batch axis (the input name and 1-based axis a gateway can count items on without decoding a request). A meta is reported as a single unit whose footprint is the sum of its sub-models, so the gateway packs and routes the group as one. See Meta Models and Multi-GPU Gateway.
Configuration reference
The scheduler: block in the node file maps to SchedulerConfig, and entries under scheduler.models map to ModelSchedConfig. The discipline enum is SchedulingDiscipline. Defaults and YAML keys:
global:
scheduler:
discipline: fair # fair | fifo | edf (fair is the default)
ema_halflife_seconds: 30.0 # half-life of the reported recent-compute EMA (no scheduling effect)
recency_penalty_cap: 0.25 # accepted for compatibility; no effect
coalescing_discount: 0.10 # accepted for compatibility; no effect
cost_ema_alpha: 0.2 # weight of a new measurement in the learned per-program cost
max_queue_depth: 1024 # per-model queue cap; a full model rejects new requests
dispatch_timeout_seconds: 30.0 # longest a caller waits for its result; 0 = no limit
compaction_interval: 0 # worker-local memory compaction every N on-demand loads
coalescing: true # merge queued requests per dispatch (false under regulated)
weight_read_stall_seconds: 20.0 # abandon a weights read with no progress this long; 0 = never
models: {} # per-model overrides (weight, residency, max_batch_size)Every field is also settable with an INFERENCE_SERVER_SCHEDULER_* environment variable (for example INFERENCE_SERVER_SCHEDULER_DISCIPLINE=fifo). See the API Reference for the full SchedulerConfig documentation.