Skip to content

[serve][llm] Sync KV load/sessions via Rust mesh and lifecycle via ZMQ - #67917

Open
jeffreywang88 wants to merge 17 commits into
masterfrom
serve-llm-kv-replica-mesh-zmq
Open

jeffreywang88 wants to merge 17 commits into
masterfrom
serve-llm-kv-replica-mesh-zmq

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

1. Description

Each LLMRouter keeps 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 every LLMServer broadcast 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:

  • Load reservations and session bindings sync through the selection service's Rust replica mesh, off the python event loop.
  • Lifecycle events go from the LLMServer straight to every LLMRouter'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). Screenshot 2026-11-05 at 12 59 00 PM
  1. Client → HAProxy. The request arrives at the ingress.
  2. HAProxy asks a router. It posts to any LLMRouter replica's /internal/route. That replica, A here, becomes the request's owner.
  3. A selects and books an LLMServer replica. A tokenizes the prompt, and its KVTokenTracker calls select_and_reserve on A's local SelectionService.
  4. [new] The mesh copies the booking to every peer. A's SelectionService publishes 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.
  5. A returns its decision. Next to replica_id, the decision headers now [new] include x-serve-router-kv-lifecycle-owner: tcp://<A's IP>:<port>, the address of A's lifecycle PULL socket.
  6. HAProxy forwards the request to that LLMServer replica. [new] RequestLifecycleOwnerMiddleware reads 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.
  7. [new] The engine reports to the owner only. LifecycleEventForwarder pushes 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.
  8. A applies the events, and the mesh copies them to peers. A's LifecycleReceiver hands each frame to KVTokenTracker.on_lifecycle_events, which updates the SelectionService. 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.

Screenshot 2026-11-16 at 3 57 49 PM
  1. Client → HAProxy. The request arrives at the ingress.
  2. HAProxy asks a router. It posts to any LLMRouter replica's /internal/route. That replica, A here, selects the request.
  3. A selects and books an LLMServer replica. A tokenizes the prompt, and its KVTokenTracker calls select_and_reserve on A's local SelectionService.
  4. [New] The mesh copies the booking to every peer. A's SelectionService publishes 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.
  5. A returns its decision (replica_id).
  6. HAProxy forwards the request to that LLMServer replica.
  7. [New] The LLMServer publishes lifecycle events to every router. LifecyclePublisher sends a msgpack frame on the LLMServer's PUB socket when the first token comes out (prefill complete) and once when the request finishes, fails or is cancelled.
  8. [New] Every router applies the events. A, B and C each receive the event directly from the LLMServer and apply it to their booking of the request inside their SelectionService. 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 LLMServers

Screenshot 2026-11-16 at 4 11 23 PM
  1. [New] Each LLMServer binds a lifecycle PUB socket on a port the OS picks and advertises it: record_routing_stats() includes {"kv_lifecycle_metadata": {"endpoint": "tcp://<ip>:<port>"}}.
  2. [New] Each router's SelectionService binds 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>"}}.
  3. The controller pushes both deployments. The tracker's LongPoll client already watched the LLMServer deployment. It now also watches the LLMRouter deployment and gets each running replica with its routing stats.
  4. [New] The tracker reconciles subscriptions. 2 _SubscriptionReconcilers keep the selection service's subscriptions equal to the latest snapshot: LLMServer lifecycle 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

  1. At most once: No acks or retries. A router misses events sent before it subscribes, or once KV_LIFECYCLE_ZMQ_SEND_QUEUE_LIMIT (2,000) events are queued for it. The selection service expires a booking whose free never arrives after DYN_ROUTER_ACTIVE_REQUEST_EXPIRY_SECS (300 s by default).
  2. In order per request: A request's events come from one 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.
  3. Idempotent: A repeated event, or one for an unknown request, changes nothing.

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.

    • 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.

2.5 What this PR assumes from Dynamo's selection service

2.5.1 Already in Dynamo main

  • Replica mesh. SelectionService(replica_sync_port=...) binds a PUB socket, and register_replica_peer / deregister_replica_peer / list_replica_peers connect its SUB socket to peer routers. Bookings and session bindings replicate over it on Rust threads, and a router ignores its own events.
  • Local changes are published. select_and_reserve publishes the booking. free_reservation publishes a Free, so a cancelled selection is released on peers too.
  • Deterministic session conflicts. When two routers bind the same session concurrently, the newer (sequence, writer_id) wins on every router (AffinityVersion).
  • Expiry as the backstop. A booking whose free never arrives expires after DYN_ROUTER_ACTIVE_REQUEST_EXPIRY_SECS (300 s by default). delete_worker frees the load of a departed LLMServer.
  • Load snapshot. loads() returns per-worker potential_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)

  • Worker publishers. register_worker_publisher / deregister_worker_publisher / list_worker_publishers subscribe the same SUB socket to LLMServer lifecycle PUB sockets. An endpoint stays connected while either set holds it.
  • Apply, never republish. An event sent by an LLMServer updates the router's booking, local or replicated, and is never re-sent on the mesh.
  • Early events are held. An event that arrives before its booking is kept for 30 s (up to 65,536). The late booking is then skipped (free) or starts in decode (prefill complete).

3. Validation 1: Scale up to 96 nodes with dynamo mocker engines

3.1 Benchmark setup

  • Stack: Ray Serve LLM + KVAwareRouter + Dynamo mocker engines.
  • Simulation: DSV4.1-Flash served by vLLM on B200 with TP4, based on InferenceX.
  • Compute: N m5.2xlarge nodes, each hosting 2 replicas to simulate an 8×B200 node. Sweep across 1, 16, 48, and 96 nodes.
  • Single-replica performance calibration: 370 tokens/s/chip per replica, p90 interactivity of 234 tokens/s/user, and p90 TTFT of 267 ms.
  • Traffic: AgentX with an average of 32 concurrent sessions per replica. Requests include X-Session-ID to enable sticky-session routing via KVAwareRouter.

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.

  • Blue: baseline (pre-PR)
  • yellow: initial approach, where each LLMServer only updates the LLMRouter that assigned its requests, relying on replica mesh to synchronize state across all LLMRouters.
  • green: 2561f16 where each LLMServer updates all LLMRouters directly to ensure fault tolerance.
Screenshot 2026-11-17 at 4 31 31 PM

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

4.2 Results

Concurrency per replica Configuration Throughput p90 TTFT p90 TPOT
64 InferenceX (single replica) 1481.6 343 8.40
Baseline 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 InferenceX (single replica) 2213.4 2577 14.45
Baseline 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
  • Scaling deployment size amplifies replica mesh benefits: With fewer nodes and replicas, the throughput and interactivity benefits of replica mesh over the baseline are less apparent. In the mocker benchmark, as the deployment size grows, replica mesh benefits throughput, interactivity, and TTFT more.
  • Higher per-replica concurrency amplifies routing optimizations: At higher per-replica concurrency, even with a small number of replicas, optimizations from replica mesh, tokenization cache, and reduced KV-router CPU overhead begin to pay off, improving throughput, TTFT, and interactivity.

5. Additional information

5.1 Known selection service mesh limitations

  • Missed startup updates are not recovered. A router only receives mesh updates and lifecycle events sent after its subscriptions connect, and updates for workers it hasn't registered yet are dropped. There is no replay/catch-up. For example, router A books worker W1 and binds session S while B is still connecting or discovering W1; after B catches up, it can still undercount W1's load and route S to W2. Likewise, if B's subscription to W1's lifecycle events connects late, B can miss the free for a request it booked and keep its load until expiry.
  • Peer session bindings can expire during an active request. Bindings received from a peer do not hold active-request leases, so their idle TTL runs while the selecting router's request is active. For example, with a 60-second affinity TTL and a 90-second stream on W1, a concurrent turn or retry reaching a peer after 60 seconds can rebind the session to W2. This is a known gap in the session replication added by Dynamo PR #16969.

5.2 Claude artifact

https://claude.ai/artifact/Wwbi8tRxwizQ1Et5aQq7vu?sk=-0QgxgIFgzhmrOf7LRqUag#architecture

@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Nov 6, 2026
@jeffreywang88
jeffreywang88 requested review from a team as code owners November 6, 2026 20:01

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-replica-mesh-zmq branch from 0af82ed to d944e28 Compare November 10, 2026 17:35
@jeffreywang88
jeffreywang88 requested a review from a team as a code owner November 10, 2026 17:35
@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-replica-mesh-zmq branch from d944e28 to 0af82ed Compare November 10, 2026 17:40

@kouroshHakha kouroshHakha left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
Loading

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 _requests tracking, 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.
  • Fewer moving parts. We'd no longer need the owner header, RequestLifecycleOwnerMiddleware and 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 SelectionService would consume events on Dynamo's threads, which is roughly where the "have SelectionService bind 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_stats are 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-owner is read from request headers on the LLMServer. 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 any tcp:// 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 inbound x-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?

@jeffreywang88
jeffreywang88 removed this pull request from stack #67970 November 13, 2026 19:54
@jeffreywang88

Copy link
Copy Markdown
Contributor Author

Noticed a pre-existing gap: A peer router can overcount prefill load.

LLMServer tells every LLMRouter when a request's prefill completes, and that can reach a peer before the owner's reservation broadcast does. the peer has no record of the request yet, so it ignores the event. when the reservation arrives, the peer counts the full prompt as outstanding prefill and keeps it through decode until the request finishes.

completion already handles this race by remembering requests that finished early. prefill needs the same. i'll address this as part of this PR.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@jeffreywang88

jeffreywang88 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author
  1. Engines publish lifecycle events to all routers, with no owner hop.

agreed. I've updated the PR to follow this design: 2561f16. It's more resilient because the LLMRouter that selected a request is no longer a single point of failure for releasing its load, and every LLMRouter is treated the same.

this depends on an upstream change to allow each LLMRouter's SelectionService to subscribe to LLMServer lifecycle publishers.

when a peer is removed via deregister_replica_peer, what happens to the bookings that came from it?

deregistering a peer just disconnects from its mesh endpoint and doesn't touch its bookings. with the new design, every router gets the free directly from the LLMServer that served the request, so those bookings are released when the request finishes. only if that free is lost do they stick around until expiry (300 s by default).

@jeffreywang88

jeffreywang88 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Derring these to a follow-up, tracked by #64389 (under the "reliability" section).

  • "2. Validation: routers joining under load"
  • "3. Follow-up: networking assumptions"

Possible attack vector: x-serve-router-kv-lifecycle-owner

this is no longer applicable after 2561f16 because a request now reports its prefill / request completion events to all LLMRouters, not just the LLMRouter that made its routing assignment.

@jeffreywang88

jeffreywang88 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor Author
  1. Question: concurrent session bindings

we used to pass session_replication_writer_id, and now each SelectionService uses its own random replica id (generate_process_id, passed as writer_id). session bindings are ordered by AffinityVersion:

/// Ordering for replicated bindings: higher wins, ties broken by writer.
#[derive(..., PartialOrd, Ord)]
pub struct AffinityVersion {
    pub sequence: u64,
    pub writer_id: u64,
}

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.

@jeffreywang88

Copy link
Copy Markdown
Contributor Author
  1. Mesh peer sync failures aren't retried

this is now fixed in 2561f16 -- instead of registering / deregistering once, we now reconcile periodically in _SubscriptionReconciler so failed calls are retried with 1-30 s backoff until the registration matches what the long poll advertises.

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.

@jeffreywang88

Copy link
Copy Markdown
Contributor Author
  1. Dynamo version requirement

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.

@jeffreywang88
jeffreywang88 force-pushed the serve-llm-kv-replica-mesh-zmq branch from 16644ec to afca201 Compare November 17, 2026 07:59
Comment on lines +277 to +281
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"]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 282 to 307
)
for _ in range(output_blocks):
tracker._svc.add_output_block(reservation_id, decay_fraction=decay_fraction)
return reservation_id

@jeffreywang88 jeffreywang88 Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

jeffreywang88 added a commit that referenced this pull request Nov 18, 2026
## 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]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ 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.

jeffreywang88 added a commit that referenced this pull request Nov 19, 2026
## 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]>
jeffreywang88 added a commit that referenced this pull request Nov 19, 2026
…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]>
jeffreywang88 and others added 3 commits November 19, 2026 15:48
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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants