25.4 Routing, cascades, and failover
Until now the gateway has had one upstream, written in its configuration. A real deployment has several engines: two decode workers and a prefill worker in the disaggregated layout of Disaggregated prefill and decode (in AI Engineering), a small and a large model, and soon a canary of a new model version (ModelRelease: gates, canary, burn check, and rollback). Engines come and go: a pod is rescheduled, a node is drained, a worker crashes mid-stream (the drill in A decode worker dies mid-stream, in Systems Engineering).
Concepts from other sections (15)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Prefix cache: a map from token prefixes of past prompts to the KV blocks already computed for them. Read more: 21.4 A radix prefix cache
- commitment boundary: the point (the status line) after which a proxy can no longer retry a request elsewhere. Read more: 25.3 The SSE streaming proxy
- composition root: the one place (here
main) where independent components are constructed and wired together. Read more: 25.2 The server skeleton - Request id: a caller-chosen id that makes a signal idempotent; stored in run state rebuilt from history. Read more: 7.8 Signals, cancellation, and sagas in Systems Engineering
- Bytes per token: total UTF-8 bytes over total tokens; the compression ratio. Read more: 7.6 Tokenizer metrics
- server-sent events (SSE): a
text/event-streamresponse ofdata: ...\n\nevents over one long HTTP response. Read more: 25.1 The tracer gateway - memory-bound: limited by the rate at which data can be read, not by arithmetic throughput. Read more: 22.7 Fused int4 and int8 dequantize-matmul in C
- PCG32: an LCG whose output is a permutation (xorshift, then a state-chosen rotation) of the old state. Read more: 12.3 Modular arithmetic, hashing, and PCG32 in Python in Mathematics
- greedy decoding: taking the single most likely token at every step; a beam of size 1. Read more: 10.4 Beam search, generic over a step function
- Consistent hashing: placing nodes and keys in one hash space so that a membership change moves only nearby keys. Read more: 15.9 A consistent hash ring with bounded loads in Programming and Algorithms
- Trie: a rooted tree whose edges carry characters so that each node spells the string on its path. Read more: 12.2 Trees and tries, longest-prefix match in Mathematics
- usage ledger: the durable per-request record of tenant, key, model, status, tokens, and latency. Read more: 25.5 The usage ledger and admin API
- uncommitted failure: an upstream failure before anything was written to the client, which a caller may retry on another worker. Read more: 25.3 The SSE streaming proxy
- KV pool: the GPU memory left for KV cache after weights and activation headroom; it sets maximum concurrency. Read more: 20.4.6 Load tests and the deployment runbook
- tie rule: the fixed backtrace preference (diagonal, deletion, insertion) that makes the S, D, I split deterministic. Read more: 15.5 Multimodal eval metrics: WER, CER, VQA, captions, zero-shot
The gateway therefore needs to know who is alive, pick a worker per request in a way that keeps prefix caches warm without overloading anyone, move away from a dead worker before the client notices, and never stitch two workers’ tokens into one answer. This section builds that router. Together with the SSE streaming proxy and the usage ledger, it turns the one-upstream proxy into a gateway over a fleet.
It builds on several earlier pieces: A consistent hash ring with bounded loads in Programming and Algorithms; the server skeleton; API keys and scopes, for the debug scope; the streaming proxy’s Forward and its commitment boundary; and the Rust engine’s Prefill and Release gRPC endpoints from the disaggregated serving section. Useful background reading is the queueing and balls-into-bins problems in Probability problem set, part d: hypothesis tests, regression, queueing, balls into bins (in Mathematics) and the Model routing and cascades chapter.
The solution is four files: registry.go (Registry, the tl.control.v1 heartbeat server, eviction, drain); route.go (Router, the policies, PickBackend, PrefixKey, ParseAcceptIf, LogprobsOf, CascadeCurve); handler.go (Middleware, the route stage; Proxy, with failover, cascades, and disaggregated prefill and decode; EngineTokenizer); and admin.go (WorkersHandler, RoutesHandler, DrainHandler). The package uses the generated gRPC code in contracts/go/gen (module openlearn.urmzd.com/tl/contracts) and google.golang.org/grpc. The gateway’s composition root serves controlv1.RegisterWorkerRegistryServer(grpcServer, registry) on registry_listen, puts route.Middleware(router) in the chain’s Router slot and route.Proxy(router, route.Options{}) in its Proxy slot, and uses router.Ready as Deps.Ready.
The contracts are course/contracts/proto/tl/control/v1/control.proto (served), engine.proto and kv.proto (called), Route, Worker, and the routes and drain rules of admin.v1.yaml, and the [gateway] keys route_policy, affinity_load_factor, heartbeat_miss_limit, and routes in runtime.schema.json.
Learning objectives
- Decide liveness from heartbeats with an exact eviction rule, and explain why the gateway’s clock is the one that counts.
- Compare
least_outstanding,weighted, andaffinityrouting, and trace each by hand.- Route a canary split deterministically from the request id, and separate “unknown model” (404) from “no capacity” (503).
- Fail over before the first byte, and only then.
- Evaluate a cascade’s cost and accuracy across thresholds, and orchestrate disaggregated prefill and decode so its output equals a unified engine’s.
The registry
Section titled “The registry”Routing starts with knowing who exists. Each engine sends tl.control.v1.WorkerRegistry/Heartbeat(WorkerStatus) every 2 s: its id, addresses (HTTP, the EngineControl gRPC port, the KV port of a decode worker), role (unified, prefill, decode), model, queue depth, running sequences, free and total KV blocks, and whether it is draining. The registry stores the latest status and the time it arrived, taken from the gateway’s Clock. Three quantities decide liveness:
| Symbol | Meaning | Value |
|---|---|---|
| heartbeat interval | 2 s | |
heartbeat_miss_limit | 3 | |
| arrival time of a worker’s last heartbeat | from the clock |
A worker is live while and is evicted (removed) once : at 5.999 s after its last heartbeat it is still there, at 6 s it is gone. A worker is routable when it is live, not reporting draining, and its model is not being drained by the admin API (POST /admin/v1/models/{model}:drain, which also sets drain: true in that worker’s next HeartbeatAck).
Load and the policies
Section titled “Load and the policies”Every policy picks among the routable workers of the right model and role. To do that it needs a notion of how busy a worker is. A worker’s load is the gateway’s own in-flight count for it plus the engine’s reported queue depth. In-flight reacts at once; the queue depth catches load from other gateways and requests that are waiting rather than running. With load defined, the three policies are:
| Policy | Picks | Good at |
|---|---|---|
least_outstanding | the minimum load, ties to the smallest id | equalizing queues when requests differ in size |
weighted | smooth weighted round robin with weight = KV capacity (kv_total_blocks): add each worker’s weight to its counter, pick the largest counter, subtract the total from it | spreading in proportion to capacity without runs |
affinity | the hash ring’s GetBounded on the prefix key, with load as above and = affinity_load_factor | prefix cache hits, with a cap on hot prefixes |
Smooth weighted round robin with weights 1 (small) and 3 (big) gives big, big, small, big, repeating: the same 1:3 split as a weighted random choice, but deterministic and interleaved.
Affinity and the prefix key
Section titled “Affinity and the prefix key”The affinity policy needs a key that predicts which worker has useful cache. The engine’s prefix cache (Radix prefix cache, Block manager with prefix cache) hashes the prompt in KV blocks of 16 tokens; two requests share cached KV only if they share whole leading blocks. The gateway has no tokenizer, so it uses the leading 64 bytes of the rendered prompt, about one block of 16 tokens at about 4 bytes per token. The rendered prompt is the completions prompt, or the chat messages written as role\ncontent\n in order.
Requests that open with the same system prompt share their key, land on the same worker (reason affinity), and hit its cache. When that worker’s load reaches , bounded loads move the next one clockwise (reason load). With 4 workers, , and 3 requests in flight on the owner (none elsewhere), the cap is , so the owner is skipped.
Routes, canaries, and model ids
Section titled “Routes, canaries, and model ids”So far the client’s model has named the workers directly. The route table ([[gateway.routes]], or PUT /admin/v1/routes) adds a layer: it maps a public model id and its aliases to what serves it, through three fields.
backends is a weighted split over served model ids, which is how a canary works (smol-v3 0.9, smol-v4 0.1). The draw is scaled to the total weight (the hash ring’s hash, top 53 bits), so one request id always lands on the same backend and the split is exact in expectation. cascade is a list of steps, described below. targets is ["unified"] (the default) or ["disaggregated"], also described below.
A model with no route is its own route. The engine knows only its served id, so the request body’s model is rewritten per attempt (withFields), leaving every other field as the client sent it. A model unknown everywhere (no route, no worker) is 404 model_not_found; a model that is known but has no routable worker is 503 no_capacity.
The route table uses optimistic concurrency on the admin API. GET returns an ETag; a PUT needs If-Match with it (428 if_match_required without, 412 etag_mismatch when stale), replaces the whole table, and increases the epoch sent in heartbeat acks.
Failover before the first byte
Section titled “Failover before the first byte”A routing decision can turn out wrong: the chosen worker may have just died. Proxy sends each attempt with the streaming proxy’s Forward, with Retry503 set. If the attempt fails uncommitted (refused, reset, or a 503 from a draining or full engine), the worker is added to the request’s exclusions and Route is asked again. At most 3 workers are tried; after that the client gets 503 no_capacity. If the attempt fails committed, the streaming proxy has already sent an SSE error event and the request ends there. A worker that just died is also evicted 6 s later by the registry; failover covers the requests in between.
Cascades
Section titled “Cascades”A cascade spends less by asking a small model first. Name the quantities:
| Symbol | Meaning |
|---|---|
| token logprobs of the small model’s answer | |
mean logprob (mean_logprob); min_logprob is | |
the threshold in accept_if, for example mean_logprob > -1.2 | |
| cost of a small call relative to a large one |
For a non-streamed request, each step except the last asks its model (with logprobs forced on) and keeps the answer when accept_if holds; otherwise it escalates. An answer with no tokens is never accepted. A streamed request goes straight to the last step, because once a stream starts it cannot be taken back.
Over an evaluation set, each threshold gives three numbers: the fraction escalated , the cost (every prompt pays the small call, escalated ones also the large), and the accuracy. On the fixture’s 200 prompts with , a sweep gives:
| escalated | cost | accuracy | |
|---|---|---|---|
| 0.000 | 0.100 | 0.540 | |
| 0.190 | 0.290 | 0.660 | |
| 0.640 | 0.740 | 0.865 | |
| 0.820 | 0.920 | 0.935 | |
| 1.000 | 1.100 | 0.935 |
At the cascade matches always-large accuracy (0.935) at 92% of its cost. Always-large costs 1.0, and the full sweep shows where the knee is for a given pair of models.
Disaggregated prefill and decode
Section titled “Disaggregated prefill and decode”The last routing target splits one request across two workers. Prefill (processing the prompt) is compute-bound; decode (one token at a time) is memory-bound. Running them on different workers lets each be sized for its job. For a route with targets = ["disaggregated"] the gateway picks a decode worker D (by the policy) and a prefill worker P (least loaded), then:
- Tokenizes the prompt (
Tokenizer; the referenceEngineTokenizerasks P’sPOST /v1/tokenize). - Fixes the seed. If the client sent none, the gateway draws one and puts it in both the
Prefillrequest and the body sent to D. P samples the first token from its PCG32 stream; D must continue the same stream (rng_draws_consumedtells it how far), so without a shared seed a sampled disaggregated stream would differ from a unified one. - Calls
EngineControl/Prefillon P with the prompt ids, the sampling parameters (every field, with the contract’s defaults for omitted ones, since proto3 has no “unset”), anddecode_targetset to D’s KV address. P runs prefill, pushes the prompt’s KV blocks to D overtl.kv.v1, and returns aKvHandle. - Sends the request to D’s HTTP surface with
X-TL-KV-Handle: <handle_id>. D resumes from the pushed KV, emits the first token, and continues. The stream passes through the streaming proxy like any other. - If that stream does not finish, calls
KvTransferService/Release(handle)on D, so the pushed blocks return to D’s pool instead of waiting for a timeout.
Working it by hand
Section titled “Working it by hand”A short sequence exercises both load and liveness. Three unified workers of smol heartbeat at with queue depths a = 2, b = 0, c = 1, and the policy is least_outstanding.
- Request
r1: loads are (nothing in flight yet), so it goes to b. - Two requests are now in flight on
b: loads , so requestr2goes to c. aheartbeats again at s and s;bandcsend nothing more.- At s,
bandchave missed fewer than 3 heartbeats (): all three are listed. - At s, :
bandcare evicted, whilea’s last heartbeat was 2 s ago. Requestr3goes to a.
The interface
Section titled “The interface”package route // import "tinyllm/gateway/route"
type Worker struct { ID, HTTPAddress, GRPCAddress, KVAddress, Role, Model string; KVFormat uint32 QueueDepth, Running, KVFreeBlocks, KVTotalBlocks int; Draining bool; LastHeartbeat time.Time }func NewRegistry(clock server.Clock, missLimit int) *Registry // implements controlv1.WorkerRegistryServerfunc (r *Registry) Heartbeat(ctx context.Context, s *controlv1.WorkerStatus) (*controlv1.HeartbeatAck, error)func (r *Registry) Snapshot() []Worker; func (r *Registry) Routable() []Worker; func (r *Registry) Drain(model string)
type InferenceRequest struct { Model, RequestID string; PrefixKey []byte; Stream bool }type Exclusions map[string]booltype Target struct { Worker Worker; Prefill *Worker; ServedModel, Reason string; CascadeStep int }func NewRouter(reg *Registry, policy string, c float64, routes []config.Route) *Routerfunc (rt *Router) Route(ctx context.Context, req *InferenceRequest, ex Exclusions, step int) (Target, error)func (rt *Router) SetRoutes([]config.Route) uint64; func (rt *Router) Routes() ([]config.Route, uint64)func (rt *Router) Acquire(id string); func (rt *Router) Release(id string); func (rt *Router) Ready(ctx context.Context) errorfunc PickBackend(r config.Route, requestID string) stringfunc PrefixKey(body []byte) []bytefunc ParseAcceptIf(s string) (Accept, error); func LogprobsOf(body []byte) ([]float64, error)func CascadeCurve(samples []CascadeSample, taus []float64, smallCost float64) []CurvePoint
func Middleware(rt *Router) server.Middleware // the route stage; also answers GET /v1/modelsfunc Proxy(rt *Router, o Options) http.Handler // the proxy stage once routing existstype Options struct { Client *http.Client; Tokenizer Tokenizer; MaxAttempts int Dial func(addr string) (grpc.ClientConnInterface, error) }func WorkersHandler(reg *Registry, rt *Router) http.Handler // GET /admin/v1/workersfunc RoutesHandler(rt *Router) http.Handler // GET, PUT /admin/v1/routesfunc DrainHandler(reg *Registry) http.Handler // POST /admin/v1/models/{model}:drainRoute takes the cascade step and returns a Target. The cascade’s Accept is parsed from the route’s accept_if strings rather than given as a Go function, because routes arrive through the admin API as JSON. X-TL-Route carries the chosen worker id only for keys with the debug scope.
Building it step by step
Section titled “Building it step by step”Seven observations shape the router:
- Liveness has to be decided by the gateway’s clock, not by the worker. A dead worker sends nothing, so the only evidence is absence. The registry stores the arrival time of each heartbeat and calls a worker live while . The strict
<is the whole off-by-one: at exactly the worker has missed heartbeats and is gone. - Eviction can be lazy. Nobody needs a dead worker removed at the instant it dies; they need it absent from the next routing decision. So
Snapshotevicts while it reads, no background timer is needed, and tests can drive the clock. - Load must combine what the gateway knows now with what the engine reported. In-flight counts move the instant a request is sent; queue depth is up to 2 s stale but sees other gateways’ traffic. Their sum is the load every policy uses. (In the hand example, step 1’s loads of come from queue depth alone.)
- Determinism is a feature. Ties go to the smallest id (candidates are sorted), the weighted policy is a deterministic round robin, and the canary draw is a hash of the request id. The same inputs route the same way, so a retried request id lands on the same canary backend and a routing decision can be explained after the fact.
- Retrying is safe only while nothing was sent. This is the streaming proxy’s commitment boundary; routing adds the loop: exclude the failed worker, ask
Routeagain, at mostMaxAttemptstimes. - A cascade can only judge a complete answer. It needs the small model’s logprobs over the whole answer before deciding, so that answer is captured, not streamed; a streamed request skips straight to the last step.
- Disaggregation is two calls that must agree. P samples the first token and D continues. For the result to equal a unified engine’s, both must use the same seed and the same sampling parameters, and P must push KV to the address D’s KV service listens on. If D’s stream fails, nobody else will free the pushed blocks, so the gateway calls
Release.
The registry
Section titled “The registry”In registry.go, a heartbeat overwrites the worker’s record and stamps it with the gateway’s clock (step 1), and the ack carries the drain request back:
func (r *Registry) Heartbeat(ctx context.Context, s *controlv1.WorkerStatus) (*controlv1.HeartbeatAck, error) { r.mu.Lock() defer r.mu.Unlock() r.workers[s.GetWorkerId()] = &Worker{ ID: s.GetWorkerId(), /* ... addresses, role, model, queue, KV blocks ... */ Draining: s.GetDraining(), LastHeartbeat: r.clock.Now(), // arrival time, not the worker's claim } return &controlv1.HeartbeatAck{Drain: r.drain[s.GetModel()], RouteEpoch: r.epoch}, nil}
func (r *Registry) live(w *Worker, now time.Time) bool { return now.Sub(w.LastHeartbeat) < time.Duration(r.missLimit)*r.interval // 5.999 s live, 6 s gone}
func (r *Registry) Snapshot() []Worker { now := r.clock.Now() // ... lock for id, w := range r.workers { if !r.live(w, now) { delete(r.workers, id) // lazy eviction (step 2) continue } out = append(out, *w) // copies: callers never see a record change under them } sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out}Routable filters a snapshot further: not Draining (the worker’s own report) and not a model drained through the admin API.
Choosing a backend and a worker
Section titled “Choosing a backend and a worker”In route.go, the canary draw maps the request id to with the ring’s hash and walks the cumulative weights:
func Unit(s string) float64 { return float64(ring.Hash64([]byte(s))>>11) / float64(uint64(1)<<53) // 53 bits: exact in a float64}
func PickBackend(r config.Route, requestID string) string { if len(r.Backends) == 0 { return r.Model // a model with no route is its own route } // ... total = sum of weights u := Unit(requestID) * total acc := 0.0 for _, b := range r.Backends { acc += b.Weight if u < acc { return b.ServedModel } } return r.Backends[len(r.Backends)-1].ServedModel // guards rounding at the top end}The three policies live in one pick, called with the router’s lock held so in-flight counts and round-robin state cannot change mid-decision:
func (rt *Router) load(w Worker) int { return rt.inflight[w.ID] + w.QueueDepth // step 3}
func (rt *Router) pick(cands []Worker, key []byte) (Worker, string) { switch rt.policy { case PolicyAffinity: // ... rebuild the ring (160 virtual nodes each) only when the candidate set changed owner, _ := rt.ring.Get(key) id, _ := rt.ring.GetBounded(key, func(n string) int { return rt.load(byID[n]) }, rt.c) if id != owner { return byID[id], "load" // the owner was over its cap: moved clockwise } return byID[id], "affinity" case PolicyWeighted: // Smooth weighted round robin (nginx): weight = KV capacity. total, best := 0, -1 for i, w := range cands { wt := max(w.KVTotalBlocks, 1) // a worker reporting 0 still gets a turn rt.smooth[w.ID] += wt total += wt if best < 0 || rt.smooth[w.ID] > rt.smooth[cands[best].ID] { best = i } } rt.smooth[cands[best].ID] -= total return cands[best], "load" default: // least_outstanding best := 0 for i, w := range cands { if rt.load(w) < rt.load(cands[best]) { // strict <: ties keep the smallest id best = i } } return cands[best], "load" }}Trace the weighted case with small = 1 and big = 3 (total 4). Counters start at 0. Round 1: , pick big, leaving . Round 2: , a tie; the first in id order with the larger counter stays, so big again (big sorts before small), leaving . Round 3: , pick small, leaving . Round 4: , pick big, leaving : back to the start, giving big, big, small, big.
Route puts it together: resolve the route, pick the served model (canary or cascade step), separate 404 from 503, then pick a worker:
func (rt *Router) Route(ctx context.Context, req *InferenceRequest, ex Exclusions, step int) (Target, error) { r := rt.Lookup(req.Model) served := PickBackend(r, req.RequestID) // ... reason "canary" with more than one backend if len(r.Cascade) > 0 { step = min(max(step, 0), len(r.Cascade)-1) served, reason, cstep = r.Cascade[step].Model, "cascade", step } ws := rt.reg.Routable() // known: some routable worker serves `served`; routed: the table names req.Model if !known && !routed { return Target{}, fmt.Errorf("%w: %s", ErrModelNotFound, req.Model) // 404: a typo, do not retry } disagg := len(r.Targets) > 0 && r.Targets[0] == "disaggregated" role := "unified" if disagg { role = "decode" // the policy picks D; P is chosen below } cands := candidates(ws, served, role, ex) // minus exclusions, sorted by id if len(cands) == 0 { return Target{}, fmt.Errorf("%w %s (%s)", ErrNoCapacity, served, role) // 503: try later } // ... lock; w, why := rt.pick(cands, req.PrefixKey) if disagg { // ... P = the least-loaded prefill worker of the same model, not excluded } return t, nil}Failover
Section titled “Failover”In handler.go, attempts is step 5 as a loop. The first attempt uses the target the route stage already picked; later ones route again with the failed workers excluded:
for attempt := 0; attempt < p.o.MaxAttempts; attempt++ { if attempt > 0 { t, err = p.rt.Route(r.Context(), &rd.ir, excl, step) if err != nil { lastErr = err break // nobody left to try } note(ex, w, r, t) } err := p.once(w, r, rd, ex, t, proxy.ExchangeObserver(ex)) if err == nil { return } var ue *proxy.UpstreamError if !errors.As(err, &ue) || ue.Committed || r.Context().Err() != nil { return // after the first byte (or the client left): never retried } lastErr = err excl[t.Worker.ID] = true // never the same worker twice if t.Prefill != nil { excl[t.Prefill.ID] = true }}if r.Context().Err() == nil { server.WriteError(w, http.StatusServiceUnavailable, "server_error", "no_capacity", "", /* ... lastErr */)}once sends one attempt. It counts the worker as in flight for exactly the attempt’s duration, sets Retry503 so a draining engine’s 503 comes back unwritten, and rewrites only model in the body. (withFields decodes to map[string]json.RawMessage, so every other field passes through byte for byte.)
att := proxy.Outbound{Method: rd.out.method, Path: rd.out.path, RawQuery: rd.out.rawQuery, Header: rd.out.header.Clone()}att.Retry503 = trueset := map[string]any{"model": t.ServedModel} // engines know only their served idp.rt.Acquire(t.Worker.ID)defer p.rt.Release(t.Worker.ID)if t.Prefill == nil { att.Body = withFields(rd.req.Body, set) return proxy.Forward(r.Context(), w, "http://"+t.Worker.HTTPAddress, &att, p.o.Client, obs)}The disaggregated branch
Section titled “The disaggregated branch”The rest of once is step 7:
seed := uint64(0)if rd.req.Seed != nil { seed = uint64(*rd.req.Seed)} else { // ... 8 random bytes seed = binary.LittleEndian.Uint64(b[:]) >> 1 // fits a JSON int64 set["seed"] = seed // D must draw from the same stream as P}ids, err := p.o.Tokenizer.Tokenize(r.Context(), *t.Prefill, t.ServedModel, rd.req.Body)// ... errors before the stream are uncommitted: failover may pick another pairpre, err := enginev1.NewEngineControlClient(conn).Prefill(r.Context(), &enginev1.PrefillRequest{ RequestId: ex.RequestID, Model: t.ServedModel, PromptIds: ids, Sampling: sampling(rd.req.Body, seed), // every field, contract defaults filled in DecodeTarget: t.Worker.KVAddress, // D's KV port, not its HTTP address // ... deadline, priority})// ...handle := pre.GetHandle().GetHandleId()att.Body = withFields(rd.req.Body, set)att.Header.Set("X-TL-KV-Handle", handle)err = proxy.Forward(r.Context(), w, "http://"+t.Worker.HTTPAddress, &att, p.o.Client, obs)if err != nil { // D holds the pushed blocks under the handle until it resumes or is told to let go. if kc, derr := p.dial(t.Worker.KVAddress); derr == nil { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) // the client's ctx may be gone _, _ = kvv1.NewKvTransferServiceClient(kc).Release(ctx, &kvv1.ReleaseRequest{HandleId: handle}) cancel() }}return errsampling starts from Temperature: 1, TopP: 1, RepetitionPenalty: 1 and overrides only fields the client sent, because proto3 cannot express “unset”: a zero temperature would mean greedy decoding, not “default”.
Cascades
Section titled “Cascades”ParseAcceptIf turns "mean_logprob > -1.2" into a function. The returned closure starts with len(lp) > 0 &&, so an empty answer (whose mean would be NaN) is never accepted. cascade runs every step but the last with logprobs forced on, into a capture writer, and writes the first accepted answer:
for step := 0; step < len(steps)-1; step++ { accept, err := ParseAcceptIf(steps[step].AcceptIf) // ... route to this step's model body := rd.req.Body if _, has := lpField["logprobs"]; !has { body = withFields(body, force) // logprobs: true (chat) or 1 (completions) } c := &capture{h: http.Header{}} // nothing reaches the client yet (step 6) if err := p.once(c, r, &local, ex, t, obs); err != nil || c.code != http.StatusOK { continue // a failed step escalates } lps, err := LogprobsOf(c.body.Bytes()) if err != nil || !accept(lps) { continue } // ... copy the captured headers (keeping the gateway's X-Request-Id), record usage, write the body return true}// ... route to the last step; false: the caller's attempts() sends it with failoverCascadeCurve is the same decision offline: every prompt pays smallCost, an escalated prompt also pays 1, and accuracy counts the answer actually kept. At it gives 0.82 escalated, cost , and accuracy 0.935, the row in the sweep above.
The admin routes
Section titled “The admin routes”In admin.go, RoutesHandler serializes PUTs with a mutex so the If-Match check and the replacement are atomic, and the ETag is the epoch ("routes-<n>"), which SetRoutes increments on every replacement. Without the mutex, two operators holding the same ETag could both pass the check.
The full solution is in registry.go, route.go, handler.go, and admin.go.
Why this design
Section titled “Why this design”Each decision is cheap. Routable copies and sorts the worker list ( for workers, a handful to a few hundred), and every policy is or, for affinity, a ring lookup () plus bounded-load probing. The ring is rebuilt only when the candidate set changes. All of this is microseconds next to a model call.
Push heartbeats beat polling health endpoints. Engines already know their queue and KV state; pushing it every 2 s gives the router load information for free, and absence is a liveness signal. A poller would need its own timeouts and would still be stale.
Load is in-flight plus queue, rather than either alone. In-flight alone misses work from other gateways and long engine queues; queue depth alone reacts only every 2 s, so a burst would all go to the worker that looked idle at the last heartbeat.
For affinity, consistent hashing with bounded loads beats both plain hashing and least-loaded. Plain hashing makes one hot system prompt a hot spot; least-loaded scatters a shared prefix over every worker and loses the cache. Bounded loads keep both properties, with as the dial.
Smooth weighted round robin beats weighted random: the same proportions, but no runs, and reproducible. And hashing the request id for the canary beats a random draw: the split is exact in expectation, retries of the same request stay on one version, and a support ticket’s request id tells you which version served it.
Note: Three tradeoffs are accepted. Eviction is lazy, so a dead worker stays in memory until the next read, which is harmless. Failover tries at most 3 workers, bounding the added latency of a widespread outage. And the cascade adds the small model’s full latency to every escalated request, which is why streams skip it.
What can go wrong
Section titled “What can go wrong”The tests cover these cases, each tied to something that depends on it:
| Case | Kind of check | What must hold | Why it matters downstream |
|---|---|---|---|
| the hand example | unit | picks b, then c, eviction exactly at 6 s, then a | the definition of load and liveness |
| heartbeats over real gRPC | conformance | a heartbeat makes a worker routable; drain sets drain in the ack and removes it; a worker reporting draining is not routable | the engine’s heartbeat client talks to this |
| unknown model, dead model | unit | unknown model 404 model_not_found; routed but down 503 no_capacity; Ready fails with no worker | conformance route.model; /readyz |
| affinity | unit, property | 20 requests sharing a system prompt land on one worker (affinity), 40 distinct prefixes spread over at least 3 of 4 workers, an overloaded owner is skipped (load) | warm prefix caches without hot spots |
| weighted by capacity | unit | capacities 1 and 3 give big, big, small, big twice | proportional and interleaved |
| canary split | statistical | 0.1 of 10000 request ids within 4 sd; one id, one backend; no backends means the route’s model | the model release’s canary weight |
| aliases and served ids | unit | an alias reaches the engine as the served model id | engines answer only their own id |
| failover before the first byte | fault | a refused worker and a 503 worker are each tried once and the request completes on the next | conformance and the kill-decode drill |
| a worker that dies after one token | fault | the client gets that token and an SSE error event; no other worker is called | no repeated or spliced tokens |
X-TL-Route | unit | only for the debug scope | internal topology stays internal |
GET /v1/models | unit | lists route and worker models; an unknown id is 404 | conformance schema.models on the gateway |
| the prefix key | unit | the rendered chat prefix; 64 bytes at most | the affinity key |
accept_if parsing | boundary | mean_logprob and min_logprob with > and >=; empty answers rejected; malformed rules refused | cascade rules from the admin API |
| a cascade | unit | a confident small answer is kept (large never called, logprobs requested); an unsure one escalated; a streamed request goes to the last step | cost savings without wrong answers |
| the cascade curve | conformance, golden | the sweep over the recorded 200-prompt set reproduces escalation, cost, and accuracy at all 13 thresholds | the cost and quality curve above |
| disaggregated equals unified | differential | the disaggregated stream equals the unified one; prompt ids, defaults, decode_target = D’s KV address; a generated seed reaches D | disaggregated serving in the engine |
| D dies mid-stream | fault | Release is called with the handle and nothing stays held | KV blocks do not leak |
| the routing admin API | unit, conformance | workers with the epoch; routes 428, 412, 400 for a bad cascade, 200 with a new ETag; drain 404 and 202 | the usage ledger’s admin API mounts these handlers |
These are the mistakes that most often break a router, with the symptom each produces:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
eviction and draining off by one: <= on the deadline, draining workers still routable | a dead worker gets traffic for one more interval; a rollout keeps sending to the pod it drains | live uses strict <; Routable drops Draining workers and drained models |
| retrying after the first byte | the client reads “The cat The cat sat”: tokens repeated or spliced | attempts returns on a committed UpstreamError |
| load from in-flight counts only | a worker with a long engine queue keeps receiving work | load is in flight plus QueueDepth |
| affinity without bounded loads | one hot system prompt saturates one worker while others idle | GetBounded with = affinity_load_factor; the reason becomes load |
| failover that relays a 503, or retries the same worker | clients see 503s while healthy workers sit idle | Retry503 on every attempt; the failed worker joins excl |
disaggregation details: decode_target set to D’s HTTP address, no shared seed, no Release on failure | prefill cannot push KV; sampled outputs differ from unified; D’s pool leaks blocks | DecodeTarget: t.Worker.KVAddress, a generated seed sent to both, Release on any decode error |
| canary and model ids: weights ignored, the public id sent upstream, an unknown model answered 503 | the canary gets half the traffic; engines answer 404; clients retry a typo forever | PickBackend walks cumulative weights; withFields sets the served model; Route returns ErrModelNotFound when neither table nor workers know it |
| cascade mistakes: accepting everything, cascading a stream, accepting an empty answer, a cost that forgets the small call | quality drops silently; streams stall; the curve understates cost | accept_if parsed per step; streams start at the last step; len(lp) > 0 in the closure; CascadeCurve adds smallCost for every prompt |
X-TL-Route for every key | worker ids leak to every client | note sets it only when the principal has the debug scope, and deletes it otherwise |
PUT /admin/v1/routes without the If-Match check | two operators’ edits overwrite each other silently | 428 without If-Match, 412 when stale, the check and the swap under one mutex |
Where this leads
Section titled “Where this leads”The router draws on five earlier pieces. The consistent hash ring supplies GetBounded for the affinity policy and Hash64 for the canary draw. The server skeleton supplies the Router and Proxy slots, the Exchange (worker id, route attributes), and Deps.Ready. API keys and scopes supplies the debug scope that gates X-TL-Route. The SSE streaming proxy sends every attempt through Forward, and only its uncommitted failures are retried. And disaggregated serving implements the Prefill and Release gRPC endpoints that disaggregated routing calls.
Looking ahead, The usage ledger and admin API builds WorkersHandler, RoutesHandler, and DrainHandler into gateway.Admin, puts Middleware in the chain through gateway.Deps, and keys the cache by ETag(epoch). Usage policy enforcement matches on the parsed route.InferenceRequest (model, prompt). And three later pieces exercise routing over HTTP: the open-loop load generator, the kill-decode drill, and the model release canary.
Further reading
Section titled “Further reading”- Affinity in production: llm-d and KServe KV-cache-aware schedulers and the SGLang router score workers by the KV blocks they actually hold, not by a hash. See llm-d (free) and the SGLang router (free).
- Backends and failover in production: saige
provider/router, with immutable model configurations, sticky selection for prompt-cache affinity, and failover only before commitment. - Cascades: Chen et al., FrugalGPT (2023), and RouteLLM (free), learned routers that predict which model a prompt needs.
- Disaggregated orchestration: Zhong et al., DistServe (OSDI 2024), and Patel et al., Splitwise (ISCA 2024); in production, vLLM disaggregated prefill, NVIDIA Dynamo (free), and Mooncake (free), with KV transfer over RDMA, a global KV pool, and prefill scheduling across nodes.
- Mitzenmacher, The Power of Two Choices in Randomized Load Balancing (2001).
Key terms
Section titled “Key terms”- heartbeat: a periodic status message from a worker; its absence is the liveness signal.
- live / routable: a worker whose last heartbeat is within / a live worker that is not draining and whose model is not drained.
- load: the gateway’s in-flight count for a worker plus the worker’s reported queue depth.
- smooth weighted round robin: a deterministic, interleaved selection in proportion to weights.
- bounded loads: a consistent-hashing variant that skips a key’s owner once its load exceeds .
- canary split: a weighted division of one public model’s traffic across served model versions.
- cascade: asking a cheaper model first and escalating when its confidence (
accept_if) fails. - disaggregated serving: prefill on one worker, decode on another, connected by a KV transfer.
- KV handle: the id under which a decode worker holds KV blocks pushed by a prefill worker.
Summary
Section titled “Summary”- Engines announce themselves with a heartbeat every 2 s; a worker that misses
heartbeat_miss_limit(3) in a row is evicted at exactly s after its last one. - Three policies pick among the routable workers of a model:
least_outstanding(fewest in flight plus queued),weighted(smooth weighted round robin by KV capacity), andaffinity(the hash ring with bounded loads on the first prompt block, so shared prefixes hit a warm cache until that worker is over its fair share). - Before the first byte, a worker that is down or answers 503 is excluded and the request routed again; after it, nothing is retried or spliced.
- A cascade asks the small model first and keeps its answer only when its mean token logprob passes
accept_if; sweeping the threshold trades cost for accuracy, and the curve on fixture data is reproduced exactly. - Disaggregated serving runs
Prefillon a prefill worker that pushes the prompt’s KV to a decode worker, then streams from the decode worker withX-TL-KV-Handle; with one seed for both, the output equals a unified engine’s.
Review questions
Section titled “Review questions”-
Why is liveness
now - last < k*Tand not<=, and why is it measured with the gateway’s clock?Answer
At exactly after the last heartbeat the worker has missed in a row, which is the eviction rule;
<=keeps a dead worker routable for one more instant (or, with a coarse clock, one more interval). The gateway’s clock is used because a dead or skewed worker cannot be trusted to timestamp its own heartbeats. -
In the weighted trace, why does round 2 pick
bigon a 2:2 tie, and what would happen if ties went to the last candidate?Answer
The scan replaces
bestonly on a strictly larger counter, so the first candidate in id order with the maximum wins, which isbig. With ties to the last, round 2 pickssmall, and the sequence becomesbig, small, big, big: still 1:3 over four requests, but a different order, so any recorded expectation of the order (and reproducibility across gateways) depends on the tie rule being fixed. -
Why does
attemptsstop onr.Context().Err() != nileven when the error is uncommitted?Answer
A cancelled client context makes every upstream call fail before the first byte. Retrying would route the dead request to other workers for nobody, and writing a 503 would go to a closed connection.
-
What goes wrong in disaggregated mode if the client sent no seed and the gateway does not generate one?
Answer
P samples the first token from its PCG32 stream with one seed, and D, seeded differently, continues from a different stream. The output is a valid sample but not the one a unified engine would produce for the same request, so the disaggregated stream no longer equals the unified one and results are not reproducible.
-
Why does
samplingdefault temperature to 1 instead of using the zero value of a missing JSON field?Answer
proto3 has no field presence, so the engine cannot tell “unset” from 0. Temperature 0 means greedy decoding, so sending the zero value would silently change the request’s meaning; the gateway fills in the contract’s defaults instead.