Load Balancing¶
SMG ships ten load balancing policies that decide which worker serves each request. Set one with --policy (default cache_aware); the right choice depends on your workload characteristics.
The policies place requests directly. With --grand-central on, the Grand Central policy engine places every request instead, under a policy document built by default from these same routing flags.
Whatever the policy, only available workers are candidates: healthy, not blocked by an open circuit breaker, and not excluded by overload protection.
Overview¶
Cache-Aware¶
Production default. Sends each request to a worker that already holds its prefix; when no worker does, or the holder is far busier than the rest, it picks the lowest expected wait among the workers that are not themselves far busier than the rest.
Least Load¶
Routes to the worker with the lowest expected wait: queued token work over throughput, plus a KV-cache pressure penalty. Intended for gRPC workers.
Power of Two¶
Samples two workers and routes to the one with the lower expected wait; a flag can switch the comparison to in-flight request counts or resident context tokens. Near-least-load placement for two load reads per request.
Consistent Hashing¶
Header-based routing with minimal redistribution on scaling. Ideal for session affinity.
Bucket¶
Request-length buckets with adaptive boundaries, for the prefill leg of PD disaggregation.
Passthrough¶
Forwards every request to the single available worker without reading load or cache state. For one-worker gateways.
Policy Comparison¶
| Policy | Load Aware | Cache Affinity | Session Affinity | Complexity | Best For |
|---|---|---|---|---|---|
cache_aware |
✓ | ✓ | ✗ | O(prefix) | Production LLM |
least_load |
✓ | ✗ | ✗ | O(n) | Load-aware routing on gRPC workers |
power_of_two |
✓ | ✗ | ✗ | O(1) | Load balancing on large fleets |
bucket |
✓ | ✗ | ✗ | O(n) | PD prefill leg |
consistent_hashing |
✗ | ✗ | ✓ | O(log n) | Session affinity |
prefix_hash |
✓ | Partial | ✗ | O(log n) | Lightweight caching |
manual |
✗ | ✗ | ✓ | O(1) | Stateful chat |
round_robin |
✗ | ✗ | ✗ | O(n) | Even distribution |
random |
✗ | ✗ | ✗ | O(1) | Testing |
passthrough |
✗ | ✗ | ✗ | O(1) | Single worker |
Complexity is the selection cost per request over n available workers; power_of_two becomes O(n) with the least_requests or resident_tokens comparison metric, which scores every available worker. Sticky sessions (--routing-key-override) add session affinity on top of any policy.
Load Signals¶
Load-aware policies read one or both of two signals:
- In-flight requests. The gateway counts the requests it has sent to each worker that have not finished yet; a streamed response counts until its body ends. The count is kept for every request under every policy, on the HTTP, gRPC and PD paths alike, and is exported as
smg_worker_requests_active. Each gateway replica counts only its own traffic.prefix_hashand thecache_awarespill gate compare these counts,least_loadandpower_of_twofall back to them for workers without a load report, and--power-of-two-load-metriccan make thempower_of_two's primary comparison. - Load reports. The gateway polls each worker's load every
--load-monitor-intervalseconds (default10). HTTP workers are asked for/v1/loadswhatever the engine, falling back to the engine's Prometheus/metrics(SGLang, vLLM) when that route does not answer; gRPC and ZMQ workers report over their engine connection (GetLoads). A report carries the worker's waiting requests and KV-cache usage, plus queued tokens, generation throughput and resident context tokens where the engine exposes them.least_load,power_of_twoandcache_awareread these reports. See Load Monitoring for the polling options.
In least_load, power_of_two and cache_aware, scores that tie exactly are broken uniformly at random, so equally idle workers share traffic instead of the first worker taking every tie.
Cache-Aware¶
The recommended policy for production LLM inference, and the default. It keeps a per-model prefix tree of the requests it has routed to each worker (for gRPC workers that publish KV-cache events, the engines' reported cache contents instead) and sends each request to a worker that already holds its prefix. When no worker holds enough of it (--cache-threshold in tree mode), or every holder is far busier than the fleet mean (over --balance-rel-threshold times the mean, and above it by an absolute margin sized to the pool's load and capped by --balance-abs-threshold), it picks by the same expected-wait score as least_load, among the workers under those same margins.
smg --policy cache_aware --worker-urls http://w1:8000 http://w2:8000✓ Advantages¶
- Reuses KV cache across requests that share a prefix
- Falls back to the lowest expected wait on a cache miss, skipping workers over its spill margins
- Spills requests off a holder that is far busier than the fleet
✗ Limitations¶
- Memory for one prefix tree per model (bounded by
--max-tree-size) - O(prefix) matching per request
- Needs the request's text or token IDs to route
Use when: Production workloads with repeated prefixes—multi-turn conversations, RAG applications, batch processing with templates.
Learn more about Cache-Aware Routing →
Bucket¶
Routes prefill requests by size in PD disaggregation. Each prefill worker owns a range of request lengths, counted in characters of prompt text or in tokens when the request carries token IDs; the last worker's range is open-ended. Every 5 seconds the policy re-checks the ranges. On the first check that sees traffic, and afterwards whenever the load per worker has changed by more than a factor of two since the last adjustment, it recomputes them from recent request sizes so each range carries a similar share of the traffic.
After an adjustment, every bounded range ends at a size some request in the last window of traffic had: the policy walks the window's distinct request sizes in ascending order, and each worker takes whole sizes until it reaches its share of the load. A size is never split between two workers, so traffic with few distinct sizes keeps the shares coarse.
A worker can be left without a range until the next adjustment, but only when the window saw fewer distinct sizes than workers. Each worker stops short of its share rather than leave the workers after it without a size, so even with one fewer distinct size than there are workers, every worker still owns a range. The partition stays contiguous from zero with the last range open-ended, so every request length has an owner, and the balance check below evens out the load in the meantime.
smg launch \
--pd-disaggregation \
--prefill http://prefill1:8000 9001 \
--prefill http://prefill2:8000 9002 \
--decode http://decode1:8000 \
--decode http://decode2:8000 \
--prefill-policy bucket \
--decode-policy power_of_two✓ Advantages¶
- Request-length awareness
- Adaptive boundary adjustment
- Falls back to the least-busy worker when imbalanced
✗ Limitations¶
- PD prefill leg only
- No cache locality
- Balances characters routed recently, not engine-reported load
Before it uses a request's bucket, the policy checks balance. The load it compares is the characters (or tokens) routed to each available prefill worker over the last 5 seconds: when the busiest and least busy workers differ by more than --balance-abs-threshold and the busiest exceeds --balance-rel-threshold times the least busy, the request goes to the least busy worker instead. Both flags are shared with cache_aware, but here they are measured in characters or tokens, not requests.
A prefill worker that is not currently available — draining before its removal, unhealthy, excluded by overload protection, stalled under a liveness veto, or behind an open circuit breaker — keeps its place in the partition, but requests of the sizes it owns go to the nearest available worker below it in the partition, or the nearest above when none below is available. On the gRPC router, a worker a retry may not return to — one that answered the request with its own 500, or a prefill worker whose silence made the request fail over — is walked past the same way, for that request's remaining attempts only. The characters routed this way count against the worker that serves them, and the balance check above compares only the workers the request may go to, so a walked-past owner neither trips the check nor draws the spill. If none of the partition's workers may take the request while other prefill workers may, the request goes to one of those at random.
When a prefill worker is removed — through the admin API, service discovery or worker auto-recovery — it leaves the partition: the neighbor below absorbs its range (the neighbor above, when the removed worker owned the lowest range), so the partition stays contiguous and every request length keeps an owner. The next 5-second check that sees traffic re-partitions the ranges among the remaining workers from recent request sizes, without waiting for the factor-of-two load change.
When a prefill worker joins — at startup, or added later through the admin API or service discovery — it is not fitted in beside the learned ranges: the partition returns at once to its starting shape, a fixed span of 4,096 characters (or tokens) split evenly among all the prefill workers, the newcomer included, with the last range open-ended. The workers that stay keep their recent-traffic counts; the newcomer starts at zero. As after a removal, the next 5-second check that sees traffic re-partitions the ranges from recent request sizes, without waiting for the factor-of-two load change.
Use when: PD disaggregation where prefill workers should specialize by prompt length, for example with a bimodal request length distribution.
Power of Two Choices¶
Samples two distinct available workers at random and routes to the one with the lower expected wait, using the same formula as least_load: queued token work over throughput plus the KV-pressure penalty, with credit for requests sent since the last load report. If neither sampled worker has a load report, it compares their in-flight requests. It approaches least-load placement while reading only two workers' load per request.
The expected wait is the default comparison; --power-of-two-load-metric can switch it to the gateway's own in-flight request counts or to the workers' resident context tokens.
smg --policy power_of_two --worker-urls http://w1:8000 http://w2:8000✓ Advantages¶
- Load-aware at two load reads per request
- Counts queue depth, KV pressure and in-flight work
- No full-fleet scan per request (except the
least_requestsandresident_tokensmetrics)
✗ Limitations¶
- No cache locality
- May miss the single least-loaded worker
- Always uses
least_load's default tuning; the--least-load-*flags do not apply
Comparison Metric¶
--power-of-two-load-metric sets what the policy compares its candidates by:
| Value | Candidates | Comparison |
|---|---|---|
expected_wait |
Two sampled at random | Lower expected wait wins (the default, described above) |
requests |
Two sampled at random | Fewer in-flight requests wins; the expected wait breaks a tie |
least_requests |
Every available worker | Keeps the workers with the fewest in-flight requests; the expected wait breaks a tie |
resident_tokens:<request_tokens> |
Every available worker | Fewest resident context tokens wins, with each request the worker holds priced at request_tokens more tokens |
smg --policy power_of_two --power-of-two-load-metric requests --worker-urls http://w1:8000 http://w2:8000Both in-flight metrics compare the gateway's own per-worker request counts (see Load Signals), read without any load report, so they balance on a live signal even where load reports are coarse or absent; only a tie goes on to the expected-wait score.
resident_tokens:<request_tokens> balances the memory-resident decode work instead: a worker's score is the resident context tokens (prompt plus output generated so far) its load report carries, plus the prompts the gateway has sent it since that report, plus request_tokens for every request it holds; in-flight requests that neither the report nor those prompts account for are estimated at the worker's mean context size. request_tokens is the per-request price in tokens and must be a non-negative integer — a bare resident_tokens is rejected at startup.
Engines whose load records carry the resident-token count report it; others leave it absent, and a worker's count is read only when every one of its DP ranks reports it. A worker without the count takes the best reporting worker's score plus a token charge for each of its own in-flight requests, so it neither attracts every request nor gets starved; when no candidate reports the count, the fewest in-flight requests decides.
least_requests and resident_tokens give up the policy's O(1) selection: they sample no pair and score every available worker. Whatever the metric, a single available worker is selected directly.
Use when: Large or heterogeneous fleets where cache locality doesn't matter and each pick should read only two workers' load.
Least Load¶
Scores every available worker by its expected wait, meaning how long the work already queued on it will take to drain, plus a penalty that rises steeply as its KV cache fills. It routes to the lowest score. Work sent since a worker's last load report counts too, so a burst that arrives between two polls spreads across workers instead of landing on the one that looked idlest.
smg launch \
--policy least_load \
--worker-urls grpc://worker1:50051 grpc://worker2:50052 \
--model-path meta-llama/Llama-3.1-8B-Instruct✓ Advantages¶
- Weighs requests by token work, not request count
- Steers away from workers near KV-cache exhaustion
- In-flight credit prevents herding between load polls
✗ Limitations¶
- No cache locality
- Scores every available worker on each request
- Estimates HTTP requests without token IDs at a mean size, so it is intended for gRPC workers
Expected-Wait Score¶
score = (queued_tokens + in_flight_tokens) / throughput
+ kv_pressure_weight * k / (1 - k)| Term | Meaning |
|---|---|
queued_tokens |
Uncached tokens waiting in the worker's queue, from its load report (summed across DP ranks). An engine that reports a queue depth but no token count, such as one scraped from Prometheus /metrics, is estimated at waiting requests × --least-load-mean-prefill-tokens |
in_flight_tokens |
Work this gateway has sent the worker since its last load report: each request's token count when its token IDs are known (gRPC workers, pre-tokenized requests), otherwise --least-load-mean-prefill-tokens. Every new report resets it |
throughput |
The worker's live generation rate: its reported generation throughput in tokens/s, summed over the DP ranks that have requests running. Dividing by it turns token work into seconds, so faster workers take proportionally more. Prefill workers and workers without a live rate are priced as described below |
k |
KV-cache usage from 0 to 1 (mean across DP ranks). k / (1 - k) stays small until the cache is nearly full, then climbs steeply |
Both terms are in seconds, so they add directly. Ties are broken uniformly at random.
For prefill workers, throughput is read as input tokens/s: prefill work consumes input tokens, which a generation rate cannot price. A prefill worker whose load report carries a measured prefill capacity on every DP rank — the uncached prompt tokens per second of active prefill its servicer measured on that rank — is priced at the sum of those rates. A worker whose report lacks the measurement — a rank without a valid rate, or a report that does not cover every rank — is priced at the mean measured rate of the candidates that have one; --least-load-default-throughput, still read as input tokens/s, stands in only when no candidate reports a measured rate.
The measured capacity is an observed service rate, not a hardware constant, and it ages out: each rank's samples expire after 60 seconds, and a rank reports a rate only while at least two valid samples remain, so a worker that has prefilled nothing for a minute returns to the fallback pricing above until fresh prefills rebuild its rate.
The measurement comes from the worker's servicer. The Rust vLLM servicer times each request's prefill from the engine's own scheduling events, which vLLM emits only with its scheduler stats (log_stats) enabled: uncached prompt tokens per second of active prefill, counting overlapping prefills' time once and skipping preempted requests and pure cache hits. The Rust SGLang, TokenSpeed and TensorRT-LLM servicers measure on their own clock instead, timing every request from hand-off to first output; seconds that several requests' intervals share — a wait in queue behind another prefill — count once. Their interval includes wire hops and, on a PD prefill worker, the KV transfer, so the reading errs low, never high. A worker whose reports never carry a rate — the Python servicers do not measure one — is always priced by the fallback chain above.
Missing signals degrade gracefully:
- A DP rank with no requests running contributes no rate — its throughput gauge holds whatever its last decode interval left behind, which is not a live rate. A worker with no live rate on any rank is priced at the mean live rate of the candidates that have one, so an idle worker beside busy peers reads as fast as they are, not slower;
--least-load-default-throughputstands in only when no candidate reports a live rate. A prefill worker without a complete measured capacity falls back the same way: the candidates' mean, then the configured default. - A worker that has not reported a load yet, such as one that just joined, scores as the best-scoring reporting worker plus its own in-flight requests, so it neither attracts every request nor gets starved.
- When no worker reports at all (a cold start, or engines that never report), the policy picks the worker with the fewest in-flight requests.
Waiting-Queue Cap¶
--least-load-max-waiting-requests N skips a worker once its reported waiting requests, plus the requests this gateway has sent it since that report, reach N. Workers without a load report stay eligible. Set N below the engine's max batch size. The default 0 turns the cap off.
When every worker is at the cap, least_load selects nothing and the request fails with 503 (no_available_workers) instead of deepening a backlog. The router does not retry the refusal internally (Never Retried); the response's Retry-After: 1 paces client retries.
For a per-worker ceiling that applies under every policy, see Overload Protection.
Tuning Flags¶
| Flag | Default | Description |
|---|---|---|
--least-load-kv-pressure-weight |
0.15 |
Weight of the KV-pressure term, in seconds. Raise it to steer harder away from nearly full KV caches; 0 removes the term |
--least-load-default-throughput |
2000 |
Fallback throughput (tokens/s) when no candidate reports a live rate (for prefill workers the live rate is a measured prefill capacity; for the others, a generation rate). Set it to your per-replica input rate for prefill, output rate otherwise; it co-tunes with the KV-pressure weight |
--least-load-mean-prefill-tokens |
1024 |
Tokens assumed per request when the real count is unknown |
--least-load-max-waiting-requests |
0 |
Per-worker waiting-queue cap; 0 disables it |
These flags tune only least_load; power_of_two and cache_aware use the same score with its default tuning. Loads are polled every --load-monitor-interval seconds (default 10), and the in-flight term covers the gap between polls. See Least Load Policy Options.
Use when: gRPC workers serve prompts of mixed sizes, cache locality doesn't matter, and you want each request on the worker with the shortest expected wait.
Consistent Hashing¶
Routes each request by its routing key on a consistent hash ring with 150 virtual nodes per worker. Minimizes redistribution when workers scale—only ~1/N keys move when adding/removing workers. Each model has its own ring; requests that name no model, such as /generate, use a ring that spans every worker.
smg --policy consistent_hashing --worker-urls http://w1:8000 http://w2:8000✓ Advantages¶
- Minimal redistribution on scaling
- Automatic failover to next healthy worker
- O(log n) lookup time
✗ Limitations¶
- No load awareness
- No cache locality
- Keyless requests go to a random worker
Routing Headers¶
| Header | Description |
|---|---|
X-SMG-Target-Worker |
Route to a worker by 0-based index into the model's currently available workers, so indices shift when a worker becomes unavailable. An index past the end of that list, or a value that is not a number, fails the request with 503 instead of falling back |
X-SMG-Routing-Key |
Hash this key onto the ring for session affinity. Names listed in --routing-key-headers are read first. Values must be non-empty UTF-8 of at most 128 bytes |
Priority order: X-SMG-Target-Worker → routing-key header → body rid (with --routing-key-override) → implicit keys (X-Forwarded-For, Cookie) → random fallback
Authorization is not an implicit key: a credential identifies a tenant or service account rather than a session, so every client sharing an API key would hash to the same worker. Requests whose only routing signal is an Authorization header use the random fallback.
See Sticky Sessions and Routing Keys for how routing keys are derived and validated.
Use when: Session affinity needed, user-to-worker pinning, or consistent routing for stateful applications.
Prefix Hash¶
A lightweight alternative to full cache-aware routing. Hashes the head of each request onto a consistent hash ring, so requests that start the same way land on the same worker, and moves a request off that worker only when it is clearly overloaded.
smg --policy prefix_hash --prefix-token-count 256 --worker-urls http://w1:8000 http://w2:8000✓ Advantages¶
- Predictable O(log n) performance
- Lower memory than cache_aware
- Groups requests that share a head
✗ Limitations¶
- Prefix grouping, not exact matching
- Less precise than cache_aware
- Load check sees only this gateway's in-flight requests
Hash Key¶
Each request is hashed on the first of these it carries:
- A valid routing-key header (
X-SMG-Routing-Keyby default), hashed as is - Token IDs (gRPC workers, pre-tokenized requests, or an
x-smg-routing-tokensheader): the first--prefix-token-counttokens - Prompt text: the first 4 ×
--prefix-token-countcharacters
A request with none of these goes to the least-loaded worker. On HTTP workers the prompt is available only when the gateway parses the request body. A request it streams to the worker unparsed, which can happen when router retries are disabled or the body exceeds --max-buffered-request-bytes, is hashed on one of the headers above or sent to the least-loaded worker.
With --cache-boundaries set (ascending token positions, for example 2048,8192), the key is the request's head up to the deepest boundary it reaches, counting 4 characters per token for text. A short turn and its longer follow-up that share a boundary-aligned head then hash together. Requests shorter than the smallest boundary keep the --prefix-token-count key.
Load Check¶
A ring worker counts as overloaded when its in-flight requests exceed both --prefix-hash-load-factor times the fleet average and the average plus --prefix-hash-balance-abs-threshold (default 10). The absolute margin keeps the check from firing on noise when each gateway replica sees only part of the traffic; 0 makes the check purely relative. For an overloaded target the policy first tries each shallower boundary (with --cache-boundaries), then falls back to the least-loaded worker that is not overloaded, or to the ring target anyway if every worker is overloaded. The fallback is counted in the load_balance_walk branch of smg_prefix_hash_policy_branch_total.
Comparison with Cache-Aware¶
| Aspect | prefix_hash | cache_aware |
|---|---|---|
| Lookup | O(log n) | O(prefix_len) |
| Memory | O(workers × virtual_nodes) | O(total_tokens) |
| Precision | Same head (fixed length or boundary) | Longest matching prefix |
Use when: Need some cache locality with predictable performance and lower memory footprint.
Manual¶
Pins each routing key to a worker in an explicit key-to-worker map. Keys come from the X-SMG-Routing-Key header, or from the request body's rid when --routing-key-override is also enabled. Unlike consistent hashing, adding workers never moves an existing key; a key moves only when its worker becomes unavailable or the key goes unused for --max-idle-secs.
smg launch --policy manual --assignment-mode min_load --worker-urls http://w1:8000 http://w2:8000✓ Advantages¶
- Strong session stickiness
- Failover to a second worker, and back once the original recovers
- Keys idle longer than
--max-idle-secsare evicted
✗ Limitations¶
- No load balancing for keys already pinned
- Requests without a key are spread by the assignment mode and never pinned
- Pins live in each gateway replica's memory
Assignment Modes¶
| Mode | Description |
|---|---|
random |
Randomly select from available workers (default) |
min_load |
Select the worker with the fewest in-flight requests |
min_group |
Select the worker with the fewest active routing keys |
delegate |
Same as min_load under this policy |
To pin conversations while another policy such as cache_aware decides where each one starts, use --routing-key-override instead. See Sticky Sessions and Routing Keys.
Use when: Stateful chat sessions where context is stored on workers, or when session continuity is critical.
Round Robin¶
Rotates through the available workers in order. The rotation is kept per candidate set, the exact list of workers a selection chooses from, so when one policy instance serves several sets (such as the decode partners of each PD prefill), each set is covered evenly. A worker that becomes unavailable changes the set, which then starts its own rotation.
smg --policy round_robin --worker-urls http://w1:8000 http://w2:8000✓ Advantages¶
- Even distribution within each candidate set
- Predictable routing pattern
- Small state (one counter per candidate set, at most 4,096 sets)
✗ Limitations¶
- No load awareness
- No cache locality
- Ignores request characteristics
Use when: All workers have equal capacity and you want predictable, even distribution.
Random¶
The simplest policy—each available worker has equal probability of selection. Zero state overhead.
smg --policy random --worker-urls http://w1:8000 http://w2:8000✓ Advantages¶
- Zero state overhead
- O(1) selection time
- Completely stateless
✗ Limitations¶
- No load awareness
- No cache locality
- Can create hot spots
Use when: Testing environments or completely homogeneous workloads where simplicity is preferred.
Passthrough¶
Forwards every request to the first available worker. It does no balancing and never reads worker load or cache state, and because only cache_aware subscribes to KV-cache events, it adds no event subscription either. It is built for a gateway in front of a single worker, where a balancing policy has nothing to choose between.
smg launch --policy passthrough --worker-urls http://w1:8000✓ Advantages¶
- No scoring or per-request state
- No load or cache state to maintain
- No KV-event subscription on gRPC workers
✗ Limitations¶
- With several workers, all traffic goes to the first available one
- Other workers take traffic only while the first is unavailable
- No load awareness or cache locality
If more than one worker is registered, the gateway logs a warning once and keeps sending everything to the first available worker. smg serve switches to passthrough on its own when it launches a single worker (--data-parallel-size 1, the default), overriding --router-policy. By default the gateway still polls worker loads, for engine metrics and overload protection; with --disable-load-monitoring it polls only when something else, such as --engine-metrics or overload protection, needs the data.
Use when: The gateway fronts exactly one worker.
Choosing a Policy¶
Decision Guide¶
| Requirement | Recommended Policy |
|---|---|
| Production LLM inference | cache_aware |
| Load-aware routing without cache affinity | least_load (gRPC workers) or power_of_two |
| Session affinity (sticky sessions) | manual or consistent_hashing, or sticky sessions on any policy |
| PD disaggregation | cache_aware or bucket for prefill, power_of_two for decode |
| Lightweight cache locality | prefix_hash |
| Even distribution | round_robin |
| A single worker | passthrough |
| Testing/development | random |
Scenario Guide¶
Conversational AI¶
Recommended: cache_aware
Maximizes KV cache reuse for multi-turn conversations with shared system prompts.
RAG Applications¶
Recommended: cache_aware
Exploits common document prefixes for faster Time to First Token.
Multi-Tenant Platform¶
Recommended: consistent_hashing or manual
User-to-worker affinity for tenant isolation or stateful sessions.
PD Disaggregation¶
Recommended: cache_aware or bucket (prefill) + power_of_two (decode)
Prefix affinity or length buckets for prefill, load-based selection for decode workers.
Mixed Prompt Sizes¶
Recommended: least_load
Scores token work rather than request counts, so long prompts don't pile onto one worker, and steers away from nearly full KV caches.
Single Worker¶
Recommended: passthrough
Nothing to balance, so skip the selection and cache bookkeeping entirely.
Policy Scope¶
Per-Model Policies¶
--policy applies to every model unless a worker names another policy. A worker registered with a policy label, for example "labels": {"policy": "least_load"} in its worker spec, sets the policy for its model. The first worker registered for a model decides, and the model keeps that policy until its last worker is removed.
A label that names the same policy as --policy gets a per-model instance built from your flags. A label naming any other policy gets that policy's built-in defaults, which can differ from the CLI defaults; its flags are not applied. In PD and EPD mode, the legs always use the leg policies below, whatever the labels say.
Under Grand Central, labels still apply when the gateway runs the document the routing flags mean, with the same first-registration rule. When the deciding label names a policy other than --policy, the gateway rebuilds the document with a binding that places that model's single requests under the named policy's profile — at the same built-in defaults as above — and puts the rebuilt document in force on the running engine. Every other model's placement is unchanged, and PD and EPD legs keep the plan's leg policies. When the model's last worker is removed, the document is rebuilt without the label. A label naming --policy itself adds nothing: that policy's profile, built from your flags, places the model already.
Under Grand Central, a label the gateway cannot build into the document — a model id containing *, for example — fails alone: the worker still registers, the document in force stays, one warning names the reason, and the label is not tried again while the model is served. On a gateway whose document binds no single requests (a single-router PD gateway over gRPC or ZMQ, which plans the pair alone), a label binds nothing. Beside a supplied --policy-spec, no label is read: the supplied document places every model's requests.
PD and EPD Legs¶
In PD mode, --prefill-policy and --decode-policy set each leg's policy and default to --policy. Both accept least_load. --decode-policy bucket is rejected at startup, and the Rust binary also rejects passthrough on either leg. Outside IGW mode, and without service discovery or --dp-aware (under which each URL registers one worker per DP rank), a leg given power_of_two through --prefill-policy or --decode-policy needs at least two workers on that leg, or startup fails. In EPD mode, --encode-policy accepts random, round_robin or consistent_hashing and defaults to consistent_hashing. See PD Disaggregation.
Grand Central¶
--grand-central on|off (default off) chooses who places requests. With off, the classic policies above place them. With on, the gateway starts Grand Central, a policy engine that places every request under a policy document: a description of placement built from profiles of filter, score and pick stages, bindings that tie profiles to models, and plans for PD pairs and EPD requests.
You do not have to write a document. With on alone, Grand Central runs the document your routing flags mean: each of the ten policies is a document preset of the same name, your policy's tuning flags land in the preset's stages, and the overload protection on/off switch and shed choice land on every binding. Placement follows your flags as before, now decided by Grand Central.
smg --grand-central on --policy cache_aware --worker-urls http://w1:8000 http://w2:8000In PD mode the prefill and decode presets are planned as a pair, with an admission filter in front of each side (capacity for prefill, room for decode); in EPD mode the encode preset joins them under the epd plan, with those two filters still in front of the pair's sides.
Over HTTP a PD gateway also places one request outside its pairs — the token-count request that takes one prefill worker — and its document binds that request behind the pair under the main policy's preset. A single-router PD gateway over gRPC or ZMQ counts tokens without a worker, and its document plans the pair alone.
The document in force is validated at startup, before the gateway opens its store or starts listening; if the document is refused, startup fails with the refusal's message. Grand Central itself starts last and follows worker registrations and removals, the newest load reports and the KV-cache events.
Printing the Document¶
--print-policy-spec prints the policy document your routing flags mean, as YAML on stdout, and exits. Nothing is started and no file is read, so the command runs without the secrets or keys a start would need. The routing flags, the discovery flags and the tenant header's name are checked as startup checks them; a Consul address and the Consul environment are resolved only at a real start.
A malformed flag value is refused first, and a setting that no document can express is named in one sentence on stderr, with a failing exit and nothing printed. The document is also checked as the gateway checks the document it runs: one the check refuses — for naming a stage this build of Grand Central does not run, or for reading the gateway's tenant header — still prints in full, with the refusal in one sentence on stderr and the same failing exit.
The printed document is the natural starting point for one you edit and supply with --policy-spec:
smg --policy least_load --print-policy-spec > routing.yaml--print-policy-spec cannot be combined with --policy-spec: it prints what the flags mean, never a supplied file.
Supplying a Document¶
--policy-spec FILE runs a supplied document in place of the one the routing flags mean. A file named .json is read as JSON, any other name as YAML. The flag requires --grand-central on: with Grand Central off, startup fails with a policy document is run by Grand Central: set --grand-central on.
The document replaces the routing flags. Typing any of the 43 flags it replaces beside --policy-spec is refused at startup with an error naming both flags — even when the typed value is the flag's default. The replaced flags are the policy names (--policy, --prefill-policy, --decode-policy, --encode-policy), every policy's own tuning flags, the overload-protection switch and shed flags, the cache-aware warm-up flags, --routing-key-override, --grouped-dp-sticky, --dp-minimum-tokens-scheduler and --pd-pairing-mode.
The routing flags the gateway still reads beside a document are --grand-central, --dp-aware, --routing-key-headers, --enable-igw and the two overload thresholds, --worker-overload-waiting-requests and --worker-overload-token-usage: no document carries a threshold (one that names a number is refused), and the gateway builds its workers with them when the document's overload blocks are on.
The supplied document decides, in its bindings' overload blocks, whether those thresholds veto at all and whether a request is shed when every worker it could use is vetoed. The gateway builds its workers with one default set of thresholds and its routes read one shed setting, so a document whose bindings disagree on either setting is refused; one that switches the block off leaves the two thresholds unused (per-worker overload blocks on a worker spec still apply).
A supplied document is validated at startup: one that names a stage this build does not run is refused by the stage's name, and one that reads the gateway's tenant header is refused by the header's name — the gateway keeps that header to itself.
In PD mode, the pairing strictness is read from the document's plans.pd-pair.pairing instead of --pd-pairing-mode.
Shadow Profiles¶
A supplied document can name a shadow on a binding: a second profile that decides the binding's requests beside the live profile, for comparison. Only the live profile's decision serves the request. The shadow reads the same worker rows, load counts and session pins the live decision read; it issues no lease, claims no session pin and writes no record of where the prompt went. A shadowed request waits for each shadow's decision on its path.
bindings[].shadow takes two forms. A single binding names one profile. A binding that plans a pair (pd-pair, or the pair in epd) names a profile per side — prefill, decode or both; a side the map leaves out is not shadowed, and the encode side takes no shadow. Each name must be a profile the document's profiles map defines:
bindings:
- match: { model: "chat-*" }
profile: live
shadow: candidate
- match: { model: "*" }
plan: pd-pair
profiles: { prefill: prefill, decode: decode }
shadow: { prefill: trial-prefill, decode: trial-decode }A form that does not match the binding's plan is refused; so are an empty map, a side other than prefill or decode, and a side written twice.
A single binding's shadow decides beside each of the binding's decisions. A pair's shadows decide by side beside the pair's first decision, and when the document sets plans.pd-pair.decode: after-prefill (see Under Grand Central), the decode side's shadow also decides beside the decode decided again.
A shadow that is due is sometimes not asked, and is then counted as skipped:
- A request with less than 1 ms of its stated time budget left skips its shadow and keeps the budget for its answer. A request that states no budget is never skipped for budget.
- A shadow profile that would need cached-block data of its own is skipped:
cache_awareis not shadowed behindleast_loadorrandom. - The shadow of a pair's side placed by the binding's sessions rule or by its picker's session assignment is skipped.
- A pair's shadow due beside a live decision that picked nothing — a pair that was shed, or a decode decided again that picked no decode — is skipped.
A shadow that panics costs its request nothing: the live decision serves the request as decided, and the panic counts in smg_policy_faults_total under kind="decision".
The shadow must be a profile no binding uses live — not one named as a binding's profile, nor under any side of its profiles — because stages may change their state when they decide; naming one is refused with a profile unused by live decisions. Build the shadow from the built-in stages: a shadow profile that holds a plugin stage is refused as not in this build, by the stage's name. A single binding whose match.phase list is non-empty and leaves out single would load a shadow that never runs, so its shadow is refused too.
Typically the shadow is a twin of the live profile — it agrees wherever its stages keep no state of their own — or the candidate profile you are evaluating before making it live.
The gateway publishes what each shadow said as smg_policy_shadow_decisions_total, by the binding's position, the side the shadow decided beside and how its decision stood against the live one (agreed, other-target, other-outcome or skipped). The counts are read from the engine at each scrape, never on a request's path, and every series a binding's shadow can count under is published at zero from the first scrape.
Settings Refused Under Grand Central¶
A setting that decides a placement but has no place in a document is refused at startup by its name, never silently dropped:
--dp-minimum-tokens-scheduleris refused whenever Grand Central is on: the document has no rank policy — under Grand Central, a data-parallel rank is a candidate of the profile.--routing-key-override(sticky sessions) lands in the document as a session rule under every policy exceptmanualandconsistent_hashing, which place keyed requests by the key themselves. The rule places single requests only, so under those eight policies the flag is refused in IGW mode, where the gateway serves pairs beside single requests, and in PD or EPD mode wherever such a policy serves a pair's side (the legs default to--policy).--grouped-dp-stickyis refused beside a supplied document: the pin reads the gateway's own routing key, and a supplied document names its own key sources. Under the document the flags mean, the pin still works: it runs after Grand Central's decision, on the worker the decision names.- On a gateway serving an external provider (an OpenAI-compatible, Anthropic or Gemini router) outside IGW mode, a supplied
--policy-specis refused: a provider mode places its requests by no routing policy.--grand-central onalone is not refused there — Grand Central does not start, the gateway serves as before, and startup says so in one log line.
Under Grand Central¶
- A worker's
policylabel still sets its model's policy under the document the routing flags mean: the gateway rebuilds the document with the label's binding and puts it in force on the running engine (see Per-Model Policies). Beside a supplied--policy-spec, no label is read. - An EPD request that carries media for the model's encode workers is refused with
501(encode_under_grand_central): whatever the document plans, the gateway asks Grand Central for prefill/decode pairs and for no encoder. The501is terminal for retries; send the request without media, or to a gateway with Grand Central off. EPD requests without media are still served as pairs. - A PD pair's two sides are picked in one decision under the document's
plans.pd-pair.decode: with-prefill— the default, and what the document the flags mean uses. A supplied document can setafter-prefill: the pair's first decision then books the prefill alone, and the decode is decided again once the prefill has answered, so a decode that became a poor choice while the prefill ran can move. A route that sends both sides at once keeps the first decision's decode. smg_worker_selection_totalcounts each selection under the document profile that picked it. Under the document the flags mean, a single request's selections keep the placing policy's name —--policy, or the policy a worker's label named; a pair's sides are counted asprefillanddecode.
Everything else stays the gateway's own, exactly as under the classic policies: the worker pools and their registration, service discovery, health probes, load polling, retries, circuit breakers, and the PD prefill admission queue. Overload protection is still enforced — its two thresholds stay the gateway's own, set on each worker as it registers, while the document carries its on/off switch and shed choice (see Supplying a Document).
Observability¶
smg_worker_selection_totalcounts every policy selection byworker_type,connection_mode,modelandpolicy.smg_cache_aware_policy_branch_total,smg_prefix_hash_policy_branch_total,smg_consistent_hashing_policy_branch_totalandsmg_manual_policy_branch_totalcount which branch each decision took (labelbranch), for example aprefix_hashrequest moved off its ring worker (load_balance_walk). The cache-aware counter covers tree-mode decisions only.smg_worker_requests_activeis the per-worker in-flight count that load-aware policies compare.- At
--log-level debug,cache_aware,prefix_hash,least_load,power_of_twoand sticky-session selections log each routing decision with the chosen worker. See Logging.
See the Metrics Reference for the full list.
What's Next?¶
Cache-Aware Routing¶
Deep dive into the radix tree architecture and routing algorithm.