Repository navigation
[serve][llm] Sync KV load/sessions via Rust mesh and lifecycle via ZMQ - #67917
jeffreywang88 wants to merge 17 commits into
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01W1q3r4FZA7CxGbmEApPJFS Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
…a-mesh-zmq Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request replaces the peer-to-peer broadcast mechanism for request lifecycle events and session bindings in the KV-aware router with a replica-mesh replication model using Dynamo and ZMQ. It introduces a LifecycleReceiver and LifecycleEventForwarder to route lifecycle events directly to the selecting router, and synchronizes router endpoints via LongPoll to replicate bookings and session bindings over Dynamo's replica mesh. The review feedback highlights a critical bug where del is defined as async def in LLMRouter, which will not be awaited by Python's garbage collector and will leak sockets and tasks; implementing an explicit shutdown method is recommended. Additionally, the reviewer suggests adding defensive checks in _sync_replica_peers to prevent AttributeError when self._svc is None, and making ZmqPushSender.close more robust during interpreter shutdown.
Signed-off-by: Jeffrey Wang <[email protected]>
0af82ed to
d944e28
Compare
d944e28 to
0af82ed
Compare
kouroshHakha
left a comment
There was a problem hiding this comment.
A couple of main architectural comments:
1. Proposal: engines publish lifecycle events to all routers, with no owner hop
Right now the path is engine → owner router (ZMQ PUSH) → owner applies → mesh copies to peers. Every router already subscribes to every LLMServer's KV-event PUB socket. What if engines published lifecycle events (prefill done, finished, failed, cancelled) on that same channel, so each router's SelectionService gets them directly?
The mesh would then only carry what only the router knows: the booking itself and the session binding.
sequenceDiagram
participant HA as HAProxy
participant W as LLMServer W1
participant A as Router A
participant B as Router B
HA->>A: /internal/route for request R
A->>B: booking(R on W1) via mesh
HA->>W: R (streams directly, router not on data path)
Note over A: A scales down / restarts / crashes
Note over W: R keeps streaming for minutes
alt Current: owner + mesh
W--xA: on_request_completed(R) pushed to dead owner, dropped
Note over B: R's load stays booked on W1 until Dynamo expiry
else Proposed: engine-to-all
W->>B: on_request_completed(R) via KV-event PUB
Note over B: R's load freed immediately
end
What this gets us:
- No dependence on the owner staying alive. The router isn't on the data path, because HAProxy streams straight to the
LLMServer. With the owner design, if the owner scales down, restarts or crashes mid-stream, the prefill-done and free events for its requests have nowhere to go.- Peers keep those bookings until Dynamo's expiry clears them. This PR removes peer-side
_requeststracking, so the owner's TTL sweep can't clear them either. - That puts the expiry TTL in a bind. If it's shorter than a long agentic stream, live load is freed early and undercounted. If it's long, dead owners leave phantom load behind.
- Router churn is routine with autoscaling, so this happens in normal operation, not just on failures. With engine-to-all delivery, every router gets the free directly, whichever router made the booking.
- Peers keep those bookings until Dynamo's expiry clears them. This PR removes peer-side
- Fewer moving parts. We'd no longer need the owner header,
RequestLifecycleOwnerMiddlewareand the contextvar, the per-router PULL socket, or the forwarder's LRU of PUSH sockets. - Nothing serialized through one router's Python event loop. Each router's
SelectionServicewould consume events on Dynamo's threads, which is roughly where the "haveSelectionServicebind the lifecycle port" follow-up is heading anyway.
Related question for the current design: when a peer is removed via deregister_replica_peer, what happens to the bookings that came from it? If they're dropped, live streams lose their load. If they're kept, they last until expiry. Either way the accounting is wrong while the owner is gone.
2. Validation: routers joining under load
A router that joins mid-load starts with an empty view of in-flight load, and there's no catch-up (listed under known limitations).
- It also isn't in the mesh until its
routing_statsare recorded and sent out through LongPoll. - During that time it sees busy workers as idle, and it will herd requests onto them until the existing requests finish.
- With very long-context or agentic sessions, that can last minutes, and it happens on every router scale-up, not only at cluster start.
I don't think this has to block the PR, but the current benchmarks use a fixed set of routers, so we don't know how bad it gets. Could we add a run that scales routers up and down mid-load, using long-context traffic, and measure:
- load-accounting error: booked load per worker vs. what the engine actually reports
- TTFT p90/p99 around scale events
If the effect is significant, the fix is a follow-up: some form of state recovery for a new router, such as a snapshot from a peer on join or seeding from engine-reported load.
3. Follow-up: networking assumptions and the owner header
- Kubernetes networking: both the lifecycle endpoint and the mesh endpoint are
tcp://<get_node_ip_address()>:<random port>. That needs pod-to-pod TCP on arbitrary ports, engine → router and router ↔ router. Does this hold under typical Kubernetes NetworkPolicy setups? It should at least be documented as a deployment requirement. Related: on hosts with more than one network interface,get_node_ip_address()may not return the address peers can reach. - Possible attack vector:
x-serve-router-kv-lifecycle-owneris read from request headers on theLLMServer. If a client sets it and it isn't stripped at ingress, for example on HAProxy's fallback path, the engine will open PUSH sockets to anytcp://address the client names. That's an outbound connection to an attacker-chosen host, and it can also churn the forwarder's socket LRU. Can we confirm HAProxy strips inboundx-serve-router-*headers, or have the engine accept only endpoints that belong to known routers?
4. Question: concurrent session bindings
The old session_replication_writer_id tie-break (newest (sequence, writer_id) wins) is removed, and conflicts are now left to Dynamo. What does Dynamo do when two routers bind the same session to different workers at about the same time, for example a client retry or a concurrent turn? Is the result deterministic across all routers?
5. Mesh peer sync failures aren't retried
+1 to the cursor bot comment on _on_router_targets / _sync_replica_peers. _replica_sync_peers is committed before the register/deregister calls succeed, and later snapshots with the same set are skipped. One transient Dynamo error therefore cuts a peer off until membership changes. Suggest reconciling periodically, or only committing the desired set after the calls succeed.
6. Dynamo version requirement
This relies on new Dynamo SelectionService APIs: replica_sync_port, register_replica_peer / deregister_replica_peer / list_replica_peers, and shutdown_async. I don't see a Dynamo version bump or minimum-version check in this PR. Can we pin the required version, or fail with a clear error on older Dynamo builds? Otherwise users on an older wheel get a TypeError at router startup.
Nit: port probe race
Probing a free port with find_free_port() and then binding it races, which is already acknowledged in the code comment. It's fine for now. Could the comment link the upstream Dynamo issue for binding port 0 and returning the assigned port, so the workaround can be removed later?
|
Noticed a pre-existing gap: A peer router can overcount prefill load.
completion already handles this race by remembering requests that finished early. prefill needs the same. i'll address this as part of this PR. |
…outer Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jeffrey Wang <[email protected]>
agreed. I've updated the PR to follow this design: 2561f16. It's more resilient because the this depends on an upstream change to allow each
deregistering a peer just disconnects from its mesh endpoint and doesn't touch its bookings. with the new design, every router gets the |
|
Derring these to a follow-up, tracked by #64389 (under the "reliability" section).
this is no longer applicable after 2561f16 because a request now reports its prefill / request completion events to all |
we used to pass The sequence works like a Lamport clock: each router advances past every sequence it receives (observe_replica_sequence). A peer's binding replaces ours only if its version is newer (apply_replica_update), so two concurrent binds converge on the same worker on every router once the bindings arrive. |
this is now fixed in 2561f16 -- instead of registering / deregistering once, we now reconcile periodically in caveat: If the router process dies mid-pass, its selection service dies with it, and the restarted replica rebuilds from a fresh snapshot. The background task dying on its own is rare (all its calls are inside its error handling, and only shutdown cancels it), so it's out of scope here. |
updated the dynamo version pinned in the release test. dynamo isn't installed by default in the ray-llm image yet as i'd prefer stabilizing the implementation before including it. |
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
16644ec to
afca201
Compare
| for model in self._svc.loads( | ||
| model_name=SELECTION_MODEL_NAME, routing_group=SELECTION_ROUTING_GROUP | ||
| ): | ||
| for load in model["loads"]: | ||
| outstanding_prefill_tokens += load["potential_prefill_tokens"] |
There was a problem hiding this comment.
Note: Prior to this PR, python maintained a separate prefill-token counter and updated it through request lifecycle callbacks. With events now handled directly inside Dynamo, those Python callbacks no longer run, so that counter would become stale.
We preserve the snapshot API and metric, but calculate the value from Dynamo’s current per-worker prefill loads via loads() whose return value includes per-worker uncached prefill load. Callbacks publish immediately after local selection and periodically using RAY_SERVE_LLM_AUTOSCALING_METRIC_PUSH_INTERVAL_S (default: 10 seconds). This keeps autoscaling snapshots consistent with the state used for routing and removes duplicate Python bookkeeping.
| ) | ||
| for _ in range(output_blocks): | ||
| tracker._svc.add_output_block(reservation_id, decay_fraction=decay_fraction) | ||
| return reservation_id |
There was a problem hiding this comment.
Note: I'm removing all decode-progress related code / tests in #68258. Will get that merged first so that this PR doesn't have to deal with any decode-progress code.
## Description Removes decode load progress from the KV-aware router: the opt-in `RAY_SERVE_LLM_ENABLE_DECODE_BLOCK_PROGRESS` flag, the engine-side output-token counting behind `on_decode_progress`, and the router's `add_output_block` bookkeeping. Engine replicas now report only prefill completion and request completion. ### Why #67917 moves request load tracking into the selection service, taking it off the python event loop. Each `LLMRouter`'s selection service tracks load from two sources: - Bookings shared between`LLMRouter`s over the replica mesh, and - Prefill-complete and free events each `LLMServer` publishes directly to every`LLMRouter` over ZMQ (ai-dynamo/dynamo#18903). Neither source can carry decode progress: - **`LLMServer`s can't send it to the selection service.** The publisher in ai-dynamo/dynamo#18903 sends only prefill-complete and free. Its event type has no output-block variant ([wire.rs](https://github.com/ai-dynamo/dynamo/blob/4a046dfdd89a7d60123669e7b7194e2f1a6424c1/lib/router/slot-tracker/src/wire.rs#L67-L79)), so the selection service would drop such a message as malformed. Supporting it would mean changing dynamo's protocol, which deliberately leaves output blocks out. - **`LLMRouter`s don't share it.** Routers sync only three events with each other: `AddRequest`, `MarkPrefillCompleted` and `Free`. Output blocks are left out on purpose, because they change too often to be worth the network cost. When a router calls `add_output_block`, only that router's selection service sees it ([multi_worker.rs](https://github.com/ai-dynamo/dynamo/blob/4a046dfdd89a7d60123669e7b7194e2f1a6424c1/lib/router/slot-tracker/src/multi_worker.rs#L1202-L1210)). The only way to keep decode progress would be a separate python method call from every `LLMServer` to every `LLMRouter`, so each router can call `add_output_block`. #67917 removes exactly this kind of load-tracking work on the python event loop. The flag is off by default and not used anyways. Default routing doesn't change. ### Changes - Remove `RAY_SERVE_LLM_ENABLE_DECODE_BLOCK_PROGRESS` and its row in the KV-aware routing guide. - `enable_token_tracking` / `RequestTokenTracker`: drop `report_decode_progress` and token counting. The first output token still reports prefill completion, and the stream's `finally` still reports completion. - `KVTokenTracker`: remove `on_decode_progress`, `_get_decay_fraction`, `get_block_size`, and the `RequestLifecycle` fields only they used (`prompt_tokens`, `expected_output_tokens`, `output_tokens`, `total_blocks`). `expected_output_tokens` is still passed to `select_and_reserve`. - Docs: the request lifecycle and decode load descriptions now match the code. - Tests: remove the decode-progress tests and update the state assertions. The release decode-load test now books blocks the probe doesn't share, since decode load no longer grows with output. **Behavior change:** the engine wrapper skipped `CUMULATIVE` output only because decode progress summed token counts, which would over-count `CUMULATIVE` chunks. With decode progress gone, the skip is removed. - Normal Ray requests (chat, completions, responses, transcription) never use `CUMULATIVE` as vLLM sets `DELTA` or `FINAL_ONLY`. - Exception: beam search (`use_beam_search`), which vLLM runs as several internal `generate` calls with the default `CUMULATIVE` kind. Before, those calls reported nothing, so the router held the request's load for up to an hour (`REQUEST_TRACKING_TTL_S`). Now each call reports under the request's serve id, so the load is freed when the first call finishes, before the beam search ends. Freeing it when the whole request finishes needs request-level tracking, left for a follow-up. ## Related issues - Prerequisite for #67917. - Related: ai-dynamo/dynamo#18903. AI assistance (🤖 Claude Code) was used to prepare this PR. --------- Signed-off-by: Jeffrey Wang <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 4627b13. Configure here.
## Description Reduce per-request CPU overhead in `LLMRouter`: - Parse JSON with `msgspec` instead of `json.loads`. `msgspec` is faster because it parses UTF-8 bytes directly. `json.loads(body)` first decodes the entire byte buffer into a python string, adding an allocation and processing pass. [msgspec reads the buffer directly](https://github.com/msgspec/msgspec/blob/main/src/msgspec/_core.c), while [CPython performs that conversion first](https://github.com/python/cpython/blob/3.12/Lib/json/__init__.py#L307). - Encode token IDs with `array.array("I")` instead of constructing a numpy array. `array.array("I", ids)` allocates a flat buffer and converts the integers in one C loop. `np.asarray(ids, dtype="<u4")` first discovers the input’s shape, then allocates and fills the array through its general conversion machinery. - Return vLLM’s token list directly, avoiding concatenation and copying for single-prompt requests (multi-prompt requests aren't supported anyways). These changes optimize existing behavior, so they reuse existing correctness coverage: - `test_tokenizer_exactness.py` compares chat/completion tokens against transformers and exercises Anthropic token staging and reuse. - `test_token_channel.py` verifies token IDs survive encoding, ZMQ delivery, decoding, and forwarding to the selected replica. - Existing router tests cover request-body parsing and routing. ## Benchmark ### 1. Mocker engine Setup follows #67917. This PR's optimization results in **7-10 ms TTFT reduction**. | | Client TTFT p50 / p90 (ms) | Client → engine arrival p50 / p90 (ms) | -- | -- | -- | | N=1 (this PR) | 67.0 / 289 | 13.8 / 34.0 | | N=1 (pre-PR) | 74.3 / 294 | 19.3 / 52 | | N=16 (this PR) | 76.7 / 441.3 | 15.1 / 38.4 | | N=16 (pre-PR) | 86.3 / 448.2 | 20.9 / 59.2 | Client TTFT: from the AgentX client sending the request to receiving the first token. ### 2. Realistic LLM deployments: AgentX + 8 replicas across 2 nodes with DSV4.1-Flash on B200s | Concurrency per replica | Configuration | Throughput | p90 TTFT | p90 TPOT | | --- | --- | --- | --- | --- | | 64 | Master | 1318.1 | 708 | 8.22 | | | + Replica mesh #67917 | 1319.7 | 691 | 8.23 | | | + Tokenization cache #67940 | 1329.2 | 608 | 8.15 | | | + KV-router CPU #67981 | **1334.8** | **570** | **8.11** | | 128 | Master | 2009.9 | 3296 | 15.70 | | | + Replica mesh #67917 | 2008.1 | 3106 | 15.69 | | | + Tokenization cache #67940 | 2055.0 | 2313 | 15.56 | | | + KV-router CPU #67981 | **2069.3** | **2109** | **15.50** | KV-router CPU overhead reduction alone results in **9% p90 TTFT reduction** on top of tokenization cache. ## Related issues > Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234". ## Additional information > Optional: Add implementation details, API changes, usage examples, screenshots, etc. Signed-off-by: Jeffrey Wang <[email protected]>
…izer caching (#67940) ## Description Multi-turn requests can reach different LLMRouter replicas and repeatedly tokenize shared conversation prefixes. This PR routes a session to a stable ingress router and configures fastokens’ native segment cache to reuse tokenized segments across turns and branches. - Use HAProxy’s native hash-type **consistent** (algorithm) **sdbm** (hash function) **avalanche** (post-processing). Deterministic server IDs derived from replica names keep mappings consistent across HAProxy processes, regardless of server ordering or local IP rewriting. - Route consultations with session IDs through a private Unix-socket listener (see diagram below) so the existing Lua request flow can use HAProxy’s native backend selection. - Requests without a session use local round robin. Cross-process affinity requires matching router membership, weights, and health views. ```mermaid sequenceDiagram participant C as Client box One HAProxy process participant P as Public listener / Lua participant B as Private Unix listener + hash backend end participant R as LLMRouter participant S as LLMServer / vLLM C->>P: Inference request + session ID Note over P: Original request waits P->>B: Consultation over local Unix socket B->>R: Hash session ID, POST /internal/route Note over R: Reuse tokenized segments<br/>Choose an LLMServer R-->>B: Selected replica ID + routing headers B-->>P: Consultation result P->>S: Forward original inference request S-->>P: Generated tokens P-->>C: Stream response ``` ### Configurations - Default `FASTOKENS_SEGMENT_CACHE` to 1024 MiB per native cache. Configuration in `LLMConfig.runtime_env.env_vars` takes precedence over the inherited environment. Fastokens enablement remains controlled by `VLLM_USE_FASTOKENS`, keeping the router and engine on the same tokenizer backend. ## Benchmark ### 1. AgentX + mocker engines Setup follows #67917. This PR optimizes work at the ingress router, so the benefits shouldn't compound as the deployment scales. I'm sweeping across deployment sizes to confirm this. <img width="1144" height="339" alt="Screenshot 2026-11-07 at 12 20 31 AM" src="https://github.com/user-attachments/assets/39e1ace6-93e1-45ca-b67f-cfafd2382abb" /> Note: We use mocker engines to filter optimization candidates and realistic LLM deployments below to validate the benefits brought by the optimization. ### 2. AgentX + 8 replicas across 2 nodes with DSV4.1-Flash on B200s #### Setup - **Stack:** Ray Serve LLM, with HAProxy ingress (direct streaming) and `KVAwareRouter` session affinity. Real vLLM 0.33.0 engines with `VLLM_USE_FASTOKENS=1`. - **Model:** DSV4.1-Flash FP4 + MTP (DSpark, 5 speculative tokens, synthetic acceptance length 3.51), with engine flags matching [InferenceX](https://github.com/SemiAnalysisAI/InferenceX/actions/runs/40269923234/attempts/1) DEP2 + DRAM KV. - **Compute:** 2 B200 nodes, plus a CPU-only head node. 8 replicas of DEP2 (TP1 × DP2 + EP). - **Engine config:** - `max_num_seqs` 48, `max_num_batched_tokens` 4096, `gpu_memory_utilization` 0.955. - Native CPU KV offload, 32 GiB per rank. - DeepGEMM MegaMoE. - **Variants:** baseline (master, session pinning) → + replica mesh (#67917) → + tokenization cache (#67940) → + KV-router CPU (#67981). - **Traffic:** - AgentX: 3600 s profiling window, seed 42, 393 traces. - 64 or 128 concurrent sessions per replica, so 512 or 1024 in total. - Requests carry `X-Session-ID` for sticky-session routing through `KVAwareRouter`. #### Results | Concurrency per replica | Configuration | Throughput | p90 TTFT | p90 TPOT | | --- | --- | --- | --- | --- | | 64 | Master | 1318.1 | 708 | 8.22 | | | + Replica mesh #67917 | 1319.7 | 691 | 8.23 | | | + Tokenization cache #67940 | **1329.2** | **608** | **8.15** | | | + KV-router CPU #67981 | 1334.8 | 570 | 8.11 | | 128 | Master | 2009.9 | 3296 | 15.70 | | | + Replica mesh #67917 | 2008.1 | 3106 | 15.69 | | | + Tokenization cache #67940 | **2055.0** | **2313** | **15.56** | | | + KV-router CPU #67981 | 2069.3 | 2109 | 15.50 | Tokenization cache alone, with replica mesh as the baseline, results in up to **25% p90 TTFT reduction** (c128). ## Related issues Follow-up to #67917, adding ingress affinity and tokenization reuse on top of the replica mesh and lifecycle work. ## Additional information ### Validation - Determinism: 100,000 session IDs across three HAProxy processes and 1,000 configured routers; zero mismatches over 400,000 requests, including restart. Varied addresses, ordering, and thread counts. - Failover and recovery: Both proxies excluded a stopped router and restored its original session assignments after recovery. --------- Signed-off-by: Jeffrey Wang <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
ai-dynamo/dynamo#18903 merged the worker publisher as WorkerSequenceEventPublisher (was ActiveSequenceEventPublisher) and dropped its block_size argument; selectors no longer match worker events on block size. Rename the class and stop passing block_size. Rebuild the release-test wheel from dynamo main @ 28697ef5c4 with --features select-service and point the KV router BYOD at it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Jeffrey Wang <[email protected]>

1. Description
Each
LLMRouterkeeps cluster-wide state for KV-aware routing: load reservations, session bindings and request lifecycle (on_prefill_complete/on_request_complete). Before this PR, every router shared that state by broadcasting serve RPCs to every other router from its python event loop, and everyLLMServerbroadcast lifecycle events to every router the same way. That work competes on the event loop with the router's tokenization and replica selection work.This works on a few nodes but breaks down at scale. This PR removes the serve RPC fan-out:
LLMServerstraight to everyLLMRouter's selection service over ZMQ PUB/SUB. No router relays them after 2561f16, so a router failing doesn't leave its peers holding load.2. Approach
Original request journey, before 2561f16 (lifecycle events to the selecting router only).
LLMRouterreplica's/internal/route. That replica, A here, becomes the request's owner.LLMServerreplica. A tokenizes the prompt, and itsKVTokenTrackercallsselect_and_reserveon A's localSelectionService.SelectionServicepublishes the booking, and the session binding when session affinity is on, on its PUB socket. Each peer's SUB socket receives it and applies it on dynamo's Rust threads, so no router's python event loop does this work. Every router subscribes to every other router.replica_id, the decision headers now [new] includex-serve-router-kv-lifecycle-owner: tcp://<A's IP>:<port>, the address of A's lifecycle PULL socket.LLMServerreplica. [new]RequestLifecycleOwnerMiddlewarereads the owner header into a contextvar that lasts through the handler and the response stream. A request without the header, such as HAProxy's fallback path, reports no events.LifecycleEventForwarderpushes a msgpack frame to A when the first token comes out (prefill done) and when the request finishes, fails or is cancelled. One PUSH socket per owner keeps a request's events in order.KVTokenTracker.on_lifecycle_events, which updates theSelectionService. The service replicates prefill done and free to B and C over the mesh.Why it changed: the owner was a single point of failure on the lifecycle path. If A died mid-request, B and C never got the free and kept the load until expiry. Now every router gets lifecycle events directly from the
LLMServer.2.1 Request journey
Prior to this PR, (4), (7) and (8) were done with serve handle calls, coupling with the router event loop in python. Now they're done natively by the selection service in Rust.
LLMRouterreplica's/internal/route. That replica, A here, selects the request.LLMServerreplica. A tokenizes the prompt, and itsKVTokenTrackercallsselect_and_reserveon A's localSelectionService.SelectionServicepublishes the booking, and the session binding when session affinity is on, on its PUB socket. Each peer's SUB socket receives it and applies it on the selection service's Rust threads, so no router's python event loop does this work. Every router subscribes to every other router.replica_id).LLMServerreplica.LLMServerpublishes lifecycle events to every router.LifecyclePublishersends a msgpack frame on theLLMServer's PUB socket when the first token comes out (prefill complete) and once when the request finishes, fails or is cancelled.LLMServerand apply it to their booking of the request inside theirSelectionService. No router re-sends it, and no python runs per event. If an event arrives before the booking it belongs to, the selection service holds it for 30 s and applies it when the booking shows up.2.2 How routers find their peers and
LLMServersLLMServerbinds a lifecycle PUB socket on a port the OS picks and advertises it:record_routing_stats()includes{"kv_lifecycle_metadata": {"endpoint": "tcp://<ip>:<port>"}}.SelectionServicebinds the mesh PUB socket on a free port. Dynamo rejects port 0, so the tracker probes a port and retries up to 3 times if the bind races.LLMRouter.record_routing_stats()returns{"kv_replica_sync_metadata": {"endpoint": "tcp://<ip>:<port>"}}.LLMServerdeployment. It now also watches theLLMRouterdeployment and gets each running replica with its routing stats._SubscriptionReconcilers keep the selection service's subscriptions equal to the latest snapshot:LLMServerlifecycle publishers (register_worker_publisher) and peer routers (register_replica_peer). Each pass diffs against the service's actual set and retries failures with backoff. The selection service connects one SUB socket to every endpoint.2.3 Delivery semantics
KV_LIFECYCLE_ZMQ_SEND_QUEUE_LIMIT(2,000) events are queued for it. The selection service expires a booking whose free never arrives afterDYN_ROUTER_ACTIVE_REQUEST_EXPIRY_SECS(300 s by default).LLMServer's PUB socket, in order. An event can arrive before the replicated booking, since they travel on different sockets; the selection service holds it until the booking arrives.2.4 Other changes
Python per-request state removed. The router no longer mirrors requests in python (
_requests, the 3,600 s TTL sweep). The selection service holds the bookings and expires them.Decode progress removed.
RAY_SERVE_LLM_ENABLE_DECODE_BLOCK_PROGRESS(off by default) relied on the python lifecycle path. We don't enable in production anyways because it can saturate network bandwidth easily. I'll follow up on removing code related to tracking decode progress entirely in the next PR.Autoscaling snapshot ([Serve][LLM][1/3] Token based autoscaling: track autoscaling workload in KV router #67937) now reads outstanding prefill tokens from
SelectionService.loads()instead of python state. The API is unchanged.We preserve the snapshot API and metric, but calculate the value from Dynamo’s current per-worker prefill loads via
loads()whose return value includes per-worker uncached prefill load. Callbacks publish immediately after local selection and periodically usingRAY_SERVE_LLM_AUTOSCALING_METRIC_PUSH_INTERVAL_S(default: 10 seconds). This keeps autoscaling snapshots consistent with the state used for routing and removes duplicate Python bookkeeping.2.5 What this PR assumes from Dynamo's selection service
2.5.1 Already in Dynamo main
SelectionService(replica_sync_port=...)binds a PUB socket, andregister_replica_peer/deregister_replica_peer/list_replica_peersconnect its SUB socket to peer routers. Bookings and session bindings replicate over it on Rust threads, and a router ignores its own events.select_and_reservepublishes the booking.free_reservationpublishes aFree, so a cancelled selection is released on peers too.(sequence, writer_id)wins on every router (AffinityVersion).DYN_ROUTER_ACTIVE_REQUEST_EXPIRY_SECS(300 s by default).delete_workerfrees the load of a departedLLMServer.loads()returns per-workerpotential_prefill_tokens, which the autoscaling snapshot sums.2.5.2 Added by ai-dynamo/dynamo#18903 (merged into Dynamo main, not yet in a release)
register_worker_publisher/deregister_worker_publisher/list_worker_publisherssubscribe the same SUB socket toLLMServerlifecycle PUB sockets. An endpoint stays connected while either set holds it.LLMServerupdates the router's booking, local or replicated, and is never re-sent on the mesh.3. Validation 1: Scale up to 96 nodes with dynamo mocker engines
3.1 Benchmark setup
KVAwareRouter+ Dynamo mocker engines.m5.2xlargenodes, each hosting 2 replicas to simulate an 8×B200 node. Sweep across 1, 16, 48, and 96 nodes.X-Session-IDto enable sticky-session routing viaKVAwareRouter.3.2 Results
With the serve RPC implementation, p90 TTFT and interactivity degrade significantly. This PR performs much better, though still lagging behind the single-node baseline. Ideally, TTFT / interactivity should stay constant as cluster size grows.
LLMServeronly updates theLLMRouterthat assigned its requests, relying on replica mesh to synchronize state across allLLMRouters.LLMServerupdates allLLMRouters directly to ensure fault tolerance.Note: Each node’s generator replays traces picked by its own random seed. The 1-node run uses only 1 seed; at 64 nodes, the other 63 seeds produce longer replies on average, and therefore higher output token throughput.
4. Validation 2: 8 replicas across 2 nodes with DSV4.1-Flash on B200s
4.1 Benchmark setup
KVAwareRoutersession affinity. Real vLLM 0.33.0 engines withVLLM_USE_FASTOKENS=1.max_num_seqs48,max_num_batched_tokens4096,gpu_memory_utilization0.955.X-Session-IDfor sticky-session routing throughKVAwareRouter.4.2 Results
5. Additional information
5.1 Known selection service mesh limitations
5.2 Claude artifact
https://claude.ai/artifact/Wwbi8tRxwizQ1Et5aQq7vu?sk=-0QgxgIFgzhmrOf7LRqUag#architecture