Skip to content

[serve][llm] Don't block the router event loop on the prefix tree actor - #66671

Merged
ArturNiederfahrenhorst merged 8 commits into
ray-project:masterfrom
ArturNiederfahrenhorst:serve-llm-prefix-router-nonblocking
Oct 22, 2026
Merged

ArturNiederfahrenhorst merged 8 commits into
ray-project:masterfrom
ArturNiederfahrenhorst:serve-llm-prefix-router-nonblocking

Conversation

@ArturNiederfahrenhorst

@ArturNiederfahrenhorst ArturNiederfahrenhorst commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

PrefixCacheAffinityRouter called ray.get on its prefix tree actor inside choose_replicas (one or two round trips per routing attempt) and in on_request_routed, update_replicas and on_replica_actor_died. Each call stalled the router's event loop, which every DeploymentHandle in the process shares, so routing throughput was capped by the actor round trip and other requests' queue length probes waited behind it.

  • Await the tree lookup instead of calling ray.get, and send it before the load check so the round trip overlaps with any queue length probes.
  • Do the prefix match and the smallest-tenants fallback in one actor call, prefix_match_or_smallest_tenants. Empty text now falls back to the smallest tenants instead of raising ZeroDivisionError.
  • Don't wait on insert, add_tenants, remove_tenants or start_eviction_loop. The actor runs one caller's tasks in submission order, so later lookups from this process still see them.
  • Drop tree results for replicas that left while the lookup was in flight.

Benchmark

The release test added here, llm_serve_prefix_router_overhead_benchmark (release/llm_tests/serve/prefix_router_overhead_benchmark.py): 2 replicas behind PrefixCacheAffinityRouter (default kwargs) that reply immediately, so only routing costs time. Prompts are ~1 KiB from 8 shared system prompts; closed-loop clients for 5 s per concurrency level. handle is handle.remote(), as OpenAiIngress calls LLMServer; direct is handle.choose_replica(..., _reserve=False), as the direct-streaming LLMRouter does. "Loop stall" is the p99 oversleep of a 1 ms heartbeat on the router's event loop.

Run on the release test's setup (Anyscale m5.2xlarge, anyscale/ray-llm:nightly-py312-cu130 at master a4a924c1c5), 5 rounds alternating the image's router with this PR's (prefix_aware_router.py and prefix_tree.py at f4ea105b04 copied over the installed ones). Median of 5, master → this PR:

path concurrency req/s p50 ms p99 ms router loop stall p99 ms
handle 1 192 → 213 5.1 → 4.6 7.3 → 7.0 1.9 → 1.1
handle 8 249 → 316 31.5 → 24.7 42.9 → 36.7 14.3 → 5.6
handle 32 260 → 315 121.8 → 100.8 146.3 → 132.1 54.8 → 12.7
handle 64 256 → 312 242.5 → 202.9 320.4 → 238.9 143.1 → 13.1
direct 1 357 → 436 2.7 → 2.1 5.1 → 5.1 3.8 → 1.6
direct 8 375 → 645 21.1 → 11.4 31.6 → 29.9 21.6 → 5.0
direct 32 379 → 596 83.0 → 49.2 118.2 → 111.7 85.4 → 12.0
direct 64 370 → 794 165.7 → 71.6 461.6 → 366.3 455.2 → 36.1

On master, throughput is flat in concurrency and the loop stall grows with it. In every round, this PR had higher throughput and a lower loop stall than master at every level. The nightly includes #66489, so direct picks also insert into the tree (with a blocking ray.get on master). Because routing is now concurrent, a new prefix's first request can be routed before earlier inserts reach the tree: on the handle path the 8 prefixes split 5/3 across the 2 replicas in 2 of 5 runs with this PR and 4/4 in all runs on master; on the direct path, 4/4 in all runs for both.

Tests

python -m pytest --noconftest --import-mode=importlib -q \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py
68 passed

Run locally on macOS (--noconftest because the llm conftest.py imports vLLM). New tests: TestNonBlockingTreeCalls (3) and TestPrefixTreePrefixMatchOrSmallestTenants (4). All but test_replica_removed_during_tree_lookup_is_not_chosen, which guards a window master doesn't have, fail on master.

No existing issue or PR does this (searched open PRs for PrefixCacheAffinityRouter, prefix_aware_router, get_smallest_tenants, "prefix tree actor ray.get"); #64577 fixes the same ZeroDivisionError. Written with AI assistance (Claude Code).

🤖 Generated with Claude Code

PrefixCacheAffinityRouter called ray.get on its prefix tree actor inside
choose_replicas (one or two round trips per routing attempt) and in
on_request_routed, update_replicas and on_replica_actor_died. Each call
stalled the router's event loop, which every DeploymentHandle in the
process shares, so routing throughput was capped by the actor round trip
and other requests' queue length probes waited behind it.

- Await the tree lookup instead of calling ray.get, and send it before
  the load check so the round trip overlaps with any queue length probes.
- Do the prefix match and the smallest-tenants fallback in one actor
  call, prefix_match_or_smallest_tenants. Empty text now falls back to the
  smallest tenants instead of raising ZeroDivisionError.
- Don't wait on insert, add_tenants, remove_tenants or
  start_eviction_loop. The actor runs one caller's tasks in submission
  order, so later lookups from this process still see them.
- Drop tree results for replicas that left while the lookup was in
  flight.

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@ArturNiederfahrenhorst
ArturNiederfahrenhorst marked this pull request as ready for review October 5, 2026 09:49
@ArturNiederfahrenhorst
ArturNiederfahrenhorst requested a review from a team as a code owner October 5, 2026 09:49

@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 refactors the prefix-aware router to prevent blocking the event loop on synchronous Ray actor calls by making tree lookups, insertions, and tenant updates asynchronous or non-blocking. It also introduces a combined prefix_match_or_smallest_tenants method to reduce actor round trips. Feedback on these changes highlights a potential routing issue where the fallback to the smallest tenants does not filter by available_tenants, potentially selecting unavailable replicas. Additionally, a type annotation mismatch was identified where not_in_cache is typed as List[ReplicaID] but populated with RunningReplica objects.

… match

The test gave both tenants the same text, so the filter never changed the
match. Now the filter shortens the match, and a 50% threshold turns it into
a fallback to the smallest tenant, which also catches a match rate computed
from the unfiltered match.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue llm labels Oct 5, 2026
@ArturNiederfahrenhorst

ArturNiederfahrenhorst commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor Author

https://gist.github.com/ArturNiederfahrenhorst/44be7bef6710576e4c598973a5654779

It is 100% Claude generated and I'm attaching it only for completeness.
I did not check it myself but am trusting Claude with the benchmark results.

…refix_aware_router.py

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@kouroshHakha

Copy link
Copy Markdown
Contributor

@ArturNiederfahrenhorst I think this PR is sound. For the benchmark, can you take a pass and rewrite a reusable version (not pr hacky based, etc) and make it a release test or sth?

@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Oct 6, 2026
# Empty text (e.g. image-only messages) has no prefix to match.
match_rate = len(matched_text) / len(text) if text else 0.0
if match_rate < match_rate_threshold:
return self.get_smallest_tenants()

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.

could we pass available_tenants to the fallback when integrating #66660? its filtered helper still searches all tenants if called without that argument, so the combined lookup can return a replica outside the candidates. we can strengthen the existing filtered-match test by making an excluded tenant the globally smallest one.

candidate_replica_ids_strings = [
r.replica_id.to_full_id_str() for r in candidate_replicas
]
tree_lookup = self._tree_actor.prefix_match_or_smallest_tenants.remote(

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.

could we skip this lookup when cached load already shows an imbalance? we now submit actor work and discard its result on every such attempt which adds work to the shared tree actor.

self, candidate_replicas: List[RunningReplica]
) -> bool:
"""Returns whether replica queue lengths differ by more than the threshold."""
# Start Sphinx tag: __begin_load_balance_component__

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.

with the default float("inf") threshold, we can return immediately because load cannot be imbalanced. that would avoid scanning the cache and probing replicas for this check.

)
# Let the routing task send its lookup, which will match r2, then
# remove r2 while the lookup is still in flight.
await asyncio.sleep(0.1)

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.

could we wait for a signal (similar to the following pattern) and hold the lookup until after the replica is removed to make this race deterministic?

class SignalActor:

…ityRouter

Measure routing cost with PrefixCacheAffinityRouter on a CPU node, with replicas
that reply immediately: throughput, latency and router event loop stalls, at
several concurrency levels, for handle.remote() and for the direct-streaming
choose_replica(_reserve=False) path. Runs weekly.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@ArturNiederfahrenhorst
ArturNiederfahrenhorst requested a review from a team as a code owner October 6, 2026 15:23
ArturNiederfahrenhorst and others added 3 commits October 6, 2026 16:29
…result isn't used

With the default imbalanced_threshold, load can't be imbalanced, so don't scan
cached queue lengths or probe replicas for the check. With a finite threshold,
check cached queue lengths before sending the prefix tree lookup: probes can only
widen their range, so if they already differ by too much, skip the lookup that
the router would discard. Otherwise the lookup still goes out before the probes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
The test removed a replica after a fixed sleep and assumed the slow tree lookup
was still in flight; on a slow machine the lookup might not have been sent yet,
and the test passed without exercising the race. Hold the lookup on a signal
until the replica is removed.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
…mallest_tenants

On a weak match, prefix_match_or_smallest_tenants returned the smallest tenants
in the whole tree, so the router could pick a replica outside the request's
candidates, e.g. one without the requested LoRA adapter. Give get_smallest_tenants
an available_tenants argument and pass it through. The helper and its test are
copied unchanged from ray-project#66660, so the two PRs make the same change there.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@jeffreywang88

Copy link
Copy Markdown
Contributor

@jeffreywang88 jeffreywang88 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.

Does the release test ever fail? What are the symptoms when the release test doesn't go as expected and what actions should we take?

Comment on lines +1 to +29
"""Routing overhead benchmark for PrefixCacheAffinityRouter.

Measures how much routing costs with PrefixCacheAffinityRouter, separate from
any model work: the replicas reply immediately, so routing is the only cost.

Methodology:
- NUM_REPLICAS replicas behind PrefixCacheAffinityRouter with its defaults.
- Requests carry ~1 KiB prompts that share one of NUM_SYSTEM_PROMPTS system
prompts, so the router's prefix tree has matches to find.
- Closed-loop load: at each concurrency level, that many clients send requests
back to back for DURATION_S, after a WARMUP_S warmup.
- Two paths, each on a fresh deployment:
- handle: ``handle.remote()``, as Serve LLM's OpenAI ingress calls LLMServer.
- direct: ``handle.choose_replica(..., _reserve=False)``, as the
direct-streaming LLMRouter picks a replica for HAProxy to forward to.

Measures per path and concurrency:
- Throughput (requests or picks per second)
- p50 and p99 latency
- p99 router event loop stall: how much a 1 ms sleep on the event loop that
routes every DeploymentHandle in the process oversleeps. Blocking calls on
that loop delay all routing in the process.

Usage (CI):
python prefix_router_overhead_benchmark.py

Usage (manual):
python prefix_router_overhead_benchmark.py --smoke-test -o /tmp/results.json
"""

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.

nit: can we simplify the comments?

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.

Yep! Thanks

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
@ArturNiederfahrenhorst

Copy link
Copy Markdown
Contributor Author

Does the release test ever fail? What are the symptoms when the release test doesn't go as expected and what actions should we take?

The test only fails if the script errors (because some import breaks or whatever).
The test just records performance metrics (see the table in the PR description for a master → this PR comparison).
I don't have access to the Databricks table that feeds the dashboard for any of the release tests but my hope was that, with this release tests, you'd be able to spot any regressions over time.

@ArturNiederfahrenhorst
ArturNiederfahrenhorst merged commit 35661db into ray-project:master Oct 22, 2026
6 checks passed
ArturNiederfahrenhorst added a commit to ArturNiederfahrenhorst/ray that referenced this pull request Oct 24, 2026
Resolves the conflicts with ray-project#66671, which moved the router's tree lookup
into one non-blocking prefix_match_or_smallest_tenants call:
- The router passes the request's key prefix to that call. The tree
  counts only text matched after the key prefix toward the match rate,
  which this PR did in the router before.
- The prefix tree insert stays fire-and-forget and keeps the key prefix.
- Drops the Sphinx tags ray-project#66671 moved: no docs include them since ray-project#57787.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
ArturNiederfahrenhorst added a commit that referenced this pull request Oct 24, 2026
Before this PR: 

choose_replicas called apply_multiplex_routing or apply_locality_routing
twice per attempt: once inside PowerOfTwoChoicesRequestRouter's
choose_replicas for the fallback, then again for prefix matching. Both
advance per-request state, so the second call returned the next tier's
candidates. A multiplexed request, such as one for a LoRA adapter, was
prefix-matched among the replicas with the fewest models loaded instead
of the replicas that have the adapter.

That spread adapters across replicas by accident and hid two more
problems. Serve loads a multiplexed model onto more replicas only when
the replicas that have it reject requests, and with Serve LLM's default
max_ongoing_requests they never do, so a popular adapter's traffic
queues on the replicas that loaded it first. And the prefix tree keyed
on prompt text only, so a LoRA request could match text cached under
another adapter, which saves nothing because vLLM's prefix cache keys
blocks by LoRA ID.

After this PR: 

Compute the candidates once, so prefix matching and the power of two
choices fallback use the same candidates. The fallback is only drawn
when prefix matching finds no replica.
With availability zone locality on, the default for DeploymentHandles,
the first attempt now prefix-matches among replicas in the caller's zone
instead of all replicas.

When the replicas chosen for a multiplexed request have more than
`multiplex_spill_threshold` (default 64) more ongoing requests than the
least busy candidate or replica with the fewest models loaded, the
request is routed among those by load, so a busy adapter spreads to more
replicas. A multiplexed request's text goes into the prefix tree under
its model ID, and only text matched under the model counts toward the
match rate. On a low match rate, the fallback picks the smallest tenant
among this attempt's candidates instead of among all replicas.

Also removes the router's unused Sphinx tags: the docs stopped including
this file in #57787.

### Benchmark

This PR adds a weekly release test,
`llm_serve_prefix_router_lora_benchmark`
(`release/llm_tests/serve/prefix_router_lora_benchmark.py`), that sends
LoRA traffic through the router to fake Ray Serve LLM replicas on
Serve's real `@serve.multiplexed`, on a CPU node. 4 replicas, 32
adapters, at most 16 loaded per replica, 2 s to download an adapter (a
replica loads one at a time), vLLM-style `max_loras=4` and a prefix
cache keyed by adapter, replicas never reject. Open-loop Poisson traffic
at 40 req/s for 180 s, identical for both routers; `cold` is the first
60 s, `last-60s` the final 60 s. Workloads: `uniform`, `zipf` (the top
adapter gets 28% of traffic) and `shared-prompt` (all adapters share 2
system prompts). Below is the release test on its setup (Anyscale
m5.2xlarge, `anyscale/ray-llm:nightly-py312-cu130` at master
`0fe2388b9d`) with master's router and with this PR's (its
`prefix_aware_router.py` and `prefix_tree.py` copied over the installed
ones), 3 seeds; placement metrics (after the cold start) are means,
latencies medians. Master → this PR:

| workload | adapter ready | evictions | KV hit | busiest replica | cold
p99 s | last-60s p50 s | last-60s p99 s |
|---|---|---|---|---|---|---|---|
| uniform | 67% → 100% | 1422 → 0 | 79% → 100% | 33% → 30% | 57.7 → 60.9
| 3.9 → 1.9 | 7.2 → 5.6 |
| zipf | 87% → 100% | 554 → 0 | 90% → 100% | 51% → 29% | 46.9 → 43.1 |
1.0 → 1.1 | 4.9 → 5.0 |
| shared-prompt | 49% → 100% | 1875 → 0 | 56% → 100% | 26% → 30% | 66.3
→ 60.2 | 5.0 → 1.9 | 8.6 → 5.2 |

The cold start is 6% slower on uniform traffic: the spill downloads
adapters onto more replicas while queues build.

`multiplex_spill_threshold` (the release test's
`--multiplex-spill-threshold`), as uniform / zipf / shared-prompt:

| threshold | evictions | busiest replica | replicas per adapter | cold
p99 s | last-60s p99 s |
|---|---|---|---|---|---|
| 16 | 66 / 5 / 77 | 28% / 28% / 28% | 2.77 / 2.08 / 2.92 | 57.4 / 39.2
/ 57.1 | 5.2 / 5.2 / 5.4 |
| 32 | 8 / 0 / 18 | 30% / 32% / 29% | 2.18 / 1.84 / 2.35 | 58.1 / 39.7 /
57.8 | 5.6 / 5.2 / 5.5 |
| **64** (default) | 0 / 0 / 0 | 30% / 29% / 30% | 1.97 / 1.98 / 1.96 |
60.9 / 43.1 / 60.2 | 5.6 / 5.0 / 5.2 |
| 128 | 0 / 0 / 0 | 30% / 29% / 30% | 1.98 / 1.86 / 2.00 | 64.6 / 44.4 /
62.7 | 5.4 / 4.7 / 5.7 |
| inf (no spill) | 0 / 0 / 0 | 31% / 70% / 31% | 1.77 / 1.16 / 1.79 |
98.6 / 138.1 / 93.5 | 5.8 / 42.4 / 6.0 |

64 is the lowest tested threshold that evicts no adapters in any
workload. Lower thresholds keep spilling after the cold start, which
costs evictions for a 2–4 s faster cold start. Without the spill, the
hot zipf adapter stays on one replica: the busiest replica takes 70% of
requests and the last-60s p99 is 42.4 s (12.2–67.3 s across seeds).

### Tests

```
python -m pytest --noconftest --import-mode=importlib -q \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py \
  python/ray/llm/tests/serve/cpu/deployments/test_prefix_tree.py
69 passed
```

Run locally on macOS (`--noconftest` because the llm `conftest.py`
imports vLLM). New tests, all fail on master:
`TestPrefixAwareLogic::test_multiplexed_request_matches_replicas_with_model`,
`TestPrefixAwareLogic::test_image_only_request_uses_smallest_tenant`,
`TestMultiplexedRouting::test_prefix_match_is_per_model`,
`TestMultiplexedRouting::test_low_match_rate_uses_smallest_candidate`,
`TestMultiplexedRouting::test_spills_from_busy_replica` (2 cases),
`TestMultiplexedRouting::test_spill_reaches_replica_without_cached_queue_len`
(with Serve's queue length cache on) and
`TestPrefixTreeGetSmallestTenants::test_get_smallest_tenants_among_available`.
The prefix-aware routing guide documents `multiplex_spill_threshold`.

The release test passes on its setup with both routers and every
threshold above, in about 10 of its 60 minutes, and `ray_release`
validates the new `release_tests.yaml` entry.

No existing issue or PR covers this (searched open PRs for
`PrefixCacheAffinityRouter`, `prefix_aware_router`, multiplex,
`get_smallest_tenants`). #66671 adds the same
`get_smallest_tenants(available_tenants)` for its own fallback, so
whichever lands second needs a rebase: the router conflicts, and this
PR's adapter-key match rate moves into #66671's combined tree lookup.
Written with AI assistance (Claude Code).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Signed-off-by: Artur Niederfahrenhorst <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
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 llm serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants