Skip to content

Serve [2/2] Apply per-deployment locality routing in routers (with env fallback if not set) - #66580

Open
wanadzhar913 wants to merge 17 commits into
ray-project:masterfrom
wanadzhar913:bugfix/locality-routing-router-59929
Open

wanadzhar913 wants to merge 17 commits into
ray-project:masterfrom
wanadzhar913:bugfix/locality-routing-router-59929

Conversation

@wanadzhar913

@wanadzhar913 wanadzhar913 commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR makes proxies and replica handles actually honor prefer_local_node_routing and prefer_local_az_routing from DeploymentConfig, with the same precedence as before:

  1. Explicit deployment config (when the option is in user_configured_option_names)
  2. Process-local env vars (RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING / RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING) when the user did not set the option
  3. Existing default routing behavior otherwise

Why the env-var guard: DeploymentConfig defaults for these fields are evaluated at import time in the driver (or the controller build task). Routers run in proxy/replica processes with their own env imports, so an unconfigured deployment must not let the driver’s copied default override the router’s env vars (fixes regressions like test_cluster.py::test_proxy_prefers_replicas_on_same_node).

Related issues

Additional information

Testing

python3 -m pytest python/ray/serve/tests/test_gang_scheduling.py \
    python/ray/serve/tests/test_deployment_scheduler_downscale.py \
    pytest python/ray/serve/tests/test_cluster.py \
    python/ray/serve/tests/unit/test_handle_options.py \
    python/ray/serve/tests/unit/test_pow_2_request_router.py \
    python/ray/serve/tests/unit/test_router.py

E2e test run locally:

python -m pytest python/ray/serve/tests/test_cluster.py::test_node_local_routing_between_deployments -v
# PASSED in 88.50s

RAY_SERVE_USE_PACK_SCHEDULING_STRATEGY=1 python -m pytest python/ray/serve/tests/test_cluster.py::test_node_local_routing_between_deployments -v
# PASSED in 88.68s

Negative control: forcing the downstream flag off made _assert_node_local_routing fail with a cross-node hop, then the change was reverted.

@wanadzhar913
wanadzhar913 force-pushed the bugfix/locality-routing-router-59929 branch from 39725a8 to 2a280d5 Compare September 29, 2026 18:01
@wanadzhar913
wanadzhar913 marked this pull request as ready for review September 29, 2026 18:40
@wanadzhar913
wanadzhar913 requested a review from a team as a code owner September 29, 2026 18:40
@jeffreywang88 jeffreywang88 self-assigned this Sep 29, 2026

@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 introduces prefer_local_node_routing and prefer_local_az_routing configuration options to support node and availability zone locality routing across Ray Serve deployments. These changes update the deployment configurations, schemas, routers, and protobuf definitions, alongside adding comprehensive tests. The review feedback highlights two important improvements: first, ensuring the new fields are properly serialized and deserialized in the to_proto and from_proto methods of DeploymentConfig to prevent configuration loss over gRPC; second, optimizing the test suite by using a shared httpx.Client session to avoid inefficient connection overhead during concurrent requests.

Comment on lines +261 to +269
prefer_local_node_routing: bool = Field(
default=RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING,
update_type=DeploymentOptionUpdateType.LightWeight,
)

prefer_local_az_routing: bool = Field(
default=RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING,
update_type=DeploymentOptionUpdateType.LightWeight,
)

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.

high

Since prefer_local_node_routing and prefer_local_az_routing are added to DeploymentConfig and serve.proto, they must also be added to the to_proto and from_proto methods of DeploymentConfig in python/ray/serve/_private/config.py. Without updating these serialization methods, the new configuration options will be lost when the deployment configuration is sent to the controller or other actors via gRPC/protobuf.

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.

Hi! DeploymentConfig.to_proto() builds the proto from model_dump() via DeploymentConfigProto(**data), and from_proto() goes through _proto_to_dict() then cls(**data), so scalar fields pass through generically. So we don't need updates for the serialization methods.

Comment on lines +649 to +660
with ThreadPoolExecutor(max_workers=num_requests) as pool:
futures = [
pool.submit(httpx.get, url, timeout=WAIT_TIMEOUT_S)
for _ in range(num_requests)
]
pairs = []
for fut in futures:
response = fut.result()
assert response.status_code == 200, response.text
upstream, downstream = response.text.split("|")
pairs.append((upstream, downstream))
return pairs

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.

medium

Calling httpx.get directly for each request in the thread pool creates and closes a new connection pool/session for every single request. This is highly inefficient and can lead to socket exhaustion or high latency under load. Using a shared httpx.Client as a context manager is much more efficient and idiomatic.

Suggested change
with ThreadPoolExecutor(max_workers=num_requests) as pool:
futures = [
pool.submit(httpx.get, url, timeout=WAIT_TIMEOUT_S)
for _ in range(num_requests)
]
pairs = []
for fut in futures:
response = fut.result()
assert response.status_code == 200, response.text
upstream, downstream = response.text.split("|")
pairs.append((upstream, downstream))
return pairs
with httpx.Client() as client:
with ThreadPoolExecutor(max_workers=num_requests) as pool:
futures = [
pool.submit(client.get, url, timeout=WAIT_TIMEOUT_S)
for _ in range(num_requests)
]
pairs = []
for fut in futures:
response = fut.result()
assert response.status_code == 200, response.text
upstream, downstream = response.text.split("|")
pairs.append((upstream, downstream))
return pairs

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

Comment thread src/ray/protobuf/serve.proto Resolved
Comment thread python/ray/serve/deployment.py Resolved
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Sep 29, 2026
@wanadzhar913
wanadzhar913 force-pushed the bugfix/locality-routing-router-59929 branch 3 times, most recently from 36c679b to 437ca76 Compare October 2, 2026 11:16

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

Comment thread python/ray/serve/_private/router.py Resolved
@wanadzhar913
wanadzhar913 force-pushed the bugfix/locality-routing-router-59929 branch from 437ca76 to 3c6b343 Compare October 2, 2026 18:44
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

You can always ask for help on our discussion forum or Ray's public slack channel.

If you'd like to keep this open, just leave any comment, and the stale label will be removed.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Oct 17, 2026
@wanadzhar913

Copy link
Copy Markdown
Contributor Author

/unstale

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 17, 2026
@wanadzhar913
wanadzhar913 force-pushed the bugfix/locality-routing-router-59929 branch 2 times, most recently from 9f377a4 to 70eb3a1 Compare October 19, 2026 12:51

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

Comment thread src/ray/protobuf/serve.proto Resolved

@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 and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit b4d15c3. Configure here.

Comment thread src/ray/protobuf/serve.proto Resolved
@wanadzhar913
wanadzhar913 force-pushed the bugfix/locality-routing-router-59929 branch from b4d15c3 to 8033d80 Compare October 27, 2026 16:16
abrarsheikh pushed a commit that referenced this pull request Nov 5, 2026
)

## Description

`AutoscalingConfig.target_ongoing_requests` is typed
`Optional[PositiveFloat]`, so `None` passes validation, both in
`@serve.deployment(autoscaling_config=...)` and as
`target_ongoing_requests: null` in a config file. The readers I checked
all expect a number: the default policy computes
`config.get_target_ongoing_requests() * num_running_replicas`
(`autoscaling_policy.py:337`), the config-file override path compares
`max_ongoing_requests < get_target_ongoing_requests()`
(`application_state.py:2087`), and the autoscaling state sets a gauge to
it (`autoscaling_state.py:662`). The first raises a `TypeError` on every
controller loop iteration.

The `Optional` type and the `None` mapping in `from_proto` date from the
rename in #43454, when `None` meant "fall back to
`target_num_ongoing_requests_per_replica`". #46392 removed that field
and the fallback, so `None` has had no meaning since.

The failure is not limited to the misconfigured app. I deployed a
healthy app, then an app with `target_ongoing_requests=None`, then a
second healthy app, on a local cluster on master. The controller logged
2,217 `TypeError: unsupported operand type(s) for *: 'NoneType' and
'int'` errors in about 4 minutes. The second healthy app never showed up
in the controller log, and `serve.status()` did not return before the
script was stopped after 4 minutes. This was one run, with the script
below. Why one deployment's policy exception stalls the whole loop is a
separate question that this PR does not change.

Behavior change: `@serve.deployment(autoscaling_config={...,
"target_ongoing_requests": None})` now raises `ValidationError` when the
class is decorated, instead of being accepted. A `null` in a config file
still passes schema parsing, because the schema keeps
`autoscaling_config` as a plain dict, and the app fails when it is
built, as it already did on master, now with a `ValidationError` from
`AutoscalingConfig`. One setup that works today would break: a
deployment defined in Python with a custom autoscaling policy that never
reads this field. The gauge skips `None`, and the `application_state.py`
comparison only runs for config files, so that setup runs with `None` on
master. A proto with 0.0, which a client cannot set on purpose because
the field must be positive, now gets the default of 2 instead of `None`.
A config object that already holds `None` and is restored by unpickling
is not revalidated (checked with `cloudpickle`), so it behaves as on
master.

Changes:
- `config.py`: type the field as `PositiveFloat`, so `None` is rejected
when an `AutoscalingConfig` is built (when the class is decorated, or
when a config-file app is built): `target_ongoing_requests: Input should
be a valid number [type=float_type, input_value=None,
input_type=NoneType]`.
- `_private/config.py`: `from_proto` replaced a 0.0
`target_ongoing_requests`, the proto3 default when the field is not set,
with `None`. It now drops the key so the field default (2) applies, the
same way the `request_router_config` fields above it are handled.

## Related issues

None. I searched issues and PRs for "target_ongoing_requests None",
"target_ongoing_requests null" and "autoscaling NoneType" and found no
report. Open PRs that edit `serve/config.py` or `_private/config.py`
(#67507, #67440, #66855, #66798, #66580, #66512) do not change this
field's type or its `from_proto` handling.

## Additional information

Tests added to `python/ray/serve/tests/unit/test_config.py`:
- `test_target_ongoing_requests_none_rejected`:
`AutoscalingConfig(target_ongoing_requests=None)`, and the same value
passed through `DeploymentConfig`, raise `ValidationError`.
- `test_target_ongoing_requests_proto_default`: a proto without the
field gives the default of 2, and a value of 7 survives a proto round
trip.

Commands, run locally on macOS arm64 with the nightly wheel,
`setup-dev.py` and Pydantic 2.14.2:
- `pytest python/ray/serve/tests/unit/test_config.py -k target_ongoing`:
3 passed (the two new tests and the existing
`test_target_ongoing_requests`). On master 541bd56: the two new tests
fail.
- `pytest` on `test_config.py`, `test_schema.py`,
`test_autoscaling_policy.py`, `test_application_state.py`,
`test_deployment_state.py` and `test_autoscaling_metrics_merge.py`, all
in `python/ray/serve/tests/unit/`: 751 passed, 12 skipped.
- `pre-commit run` on the changed files: passed.

<details><summary>Repro script (run on master)</summary>

```python
import time, ray
from ray import serve
from ray.serve.api import _run
ray.init(num_cpus=8, include_dashboard=False, log_to_driver=False)

@serve.deployment(ray_actor_options={"num_cpus": 0})
class Ok:
    def __call__(self): return "ok"

@serve.deployment(autoscaling_config={"min_replicas": 1, "max_replicas": 3, "target_ongoing_requests": None}, ray_actor_options={"num_cpus": 0})
class Bad:
    def __call__(self): return "bad"

serve.run(Ok.bind(), name="ok1", route_prefix="/ok1")
_run(Bad.bind(), name="bad", route_prefix="/bad", _blocking=False)
time.sleep(3)
_run(Ok.bind(), name="ok2", route_prefix="/ok2", _blocking=False)
time.sleep(15)
st = serve.status().applications
print({k: str(v.status) for k, v in st.items()})
serve.shutdown(); ray.shutdown()
```

</details>

Signed-off-by: William Guo <[email protected]>
wanadzhar913 and others added 15 commits November 19, 2026 23:30
Two premerge failures from 7af4332 ("Add locality routing options to
DeploymentSchema/Deployment").

1. lint-api-param-coverage requires an Args: entry for every new
   parameter on a @publicapi callable. Adding one to
   Deployment.options() ends that docstring's pydoclint "short
   docstring" exemption, which then demands all 26 parameters plus a
   Returns section -- duplicating the @serve.deployment docs the
   docstring deliberately delegates to. The repo has an empty pydoclint
   baseline and no "# noqa: DOC" suppressions, so neither escape hatch
   is available without adding new lint debt. Drop the two options from
   Deployment.options() instead, matching rolling_update_percentage,
   which is likewise in DeploymentConfig and DeploymentSchema but
   intentionally absent from options().

2. test_get_serve_instance_details_json_serializable compares the whole
   details response against a golden dict that enumerates every
   deployment_config key. _deployment_info_to_schema now reports both
   options, so add them to the golden dicts in test_controller.py and
   test_direct_ingress.py. Both default to True via
   RAY_SERVE_PROXY_PREFER_LOCAL_{NODE,AZ}_ROUTING.

The DeploymentSchema fields and converters are unchanged: config files,
the REST API, and RayService serveConfigV2 can still set both options.

Signed-off-by: wanadzhar913 <[email protected]>
Co-authored-by: Cursor <[email protected]>
AsyncioRouter took prefer_local_node_routing as a constructor argument
but hardcoded self._prefer_local_az_routing to the
RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING env var. Because the request
router is created lazily, it can be constructed before the
DEPLOYMENT_CONFIG long poll fires (for example when
update_deployment_targets arrives first), in which case the AZ flag was
never controllable at init while the node flag was.

Make prefer_local_az_routing a required AsyncioRouter parameter,
sourced from a new InitHandleOptions._prefer_local_az_routing field
that defaults to the env var. create_router forwards it, and
get_proxy_handle passes it explicitly alongside the node flag.

Also drop the user_configured_option_names branching in
update_deployment_config. DeploymentConfig.prefer_local_node_routing
and prefer_local_az_routing already default to their respective env
vars, so both arms of each if/else assigned the same value. Read the
config fields directly, matching how the backoff params in the same
method are handled.

Tests:
- test_router.py: pass the new argument at every router construction
  site; cover a default DeploymentConfig (no user-configured names)
  still applying its field values, and a lazily created request router
  picking up the constructor AZ flag.
- test_handle_options.py: cover the new field's default and override.

Signed-off-by: wanadzhar913 <[email protected]>
…default and the router live in different processes. DeploymentConfig.prefer_local_*_routing defaults to the env var, but that default is evaluated once at import time in the process that builds the config (the driver), while the router runs in a proxy or replica process that imported the env var independently. Without the guard, the config's copy wins, which makes RAY_SERVE_PROXY_PREFER_LOCAL_*_ROUTING a no-op on every node except the one that built the config — that's what broke test_cluster.py::test_proxy_prefers_replicas_on_same_node[False], which sets the env var to 0 after the driver has already imported Serve so the proxy and driver legitimately disagree. The else keeps the intended precedence: explicit deployment config beats the env var, and an unconfigured deployment defers to the env var of the process actually doing the routing.

Signed-off-by: wanadzhar913 <[email protected]>
Two-node cluster with d1->d2, one replica of each per node. Asserts that
prefer_local_node_routing pins replica-to-replica traffic on-node, and
that flipping the flag off via a lightweight config update restores
spread routing.

Signed-off-by: wanadzhar913 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Drop router runtime wiring and related tests from this branch so PR 1
covers deployment config, schema, and protobuf only. Router behavior
lands in a stacked follow-up branch.

Signed-off-by: wanadzhar913 <[email protected]>
Add prefer_local_node_routing and prefer_local_az_routing to Deployment.options(), as requested in review. Previously the flags could be set through @serve.deployment and the config schema, but calling .options(prefer_local_node_routing=...) raised a TypeError.

This reverses the options() part of 1062bad, which removed the flags to satisfy the API param coverage lint.

Tests:
- Add both flags to TestDeploymentOptions.deployment_options. This covers the decorator, .options(), and user_configured_option_names after proto serialization.
- Add test_options_prefer_local_node_routing_false.

Signed-off-by: wanadzhar913 <[email protected]>
…zed over all four (prefer_local_node_routing, prefer_local_az_routing) combinations. - Builds a DeploymentConfig with both flags and user_configured_option_names set. - After to_proto(), asserts HasField on both optional bool fields and that values match (including explicit False). - Round-trips via to_proto_bytes() / from_proto_bytes() and checks flags and user_configured_option_names. test_prefer_local_routing_proto_unset_fields_use_defaults - Starts from a valid proto, ClearFields both locality fields (simulating an older sender). - Deserializes from bytes and asserts values equal RAY_SERVE_PROXY_PREFER_LOCAL_NODE_ROUTING and RAY_SERVE_PROXY_PREFER_LOCAL_AZ_ROUTING, not proto3’s implicit False.

Signed-off-by: wanadzhar913 <[email protected]>
Deploy ray.serve.tests.test_config_files.pid.node through serve deploy
with prefer_local_node_routing=false and prefer_local_az_routing=true,
and check that serve details reports both in deployment_config. Then
redeploy with the values swapped and check that the details update
while the replica PID stays the same.

Giving the two flags different values, and flipping both, catches any
mix-up between the fields. It also confirms that changing them is a
lightweight update that doesn't restart the replica.

Signed-off-by: wanadzhar913 <[email protected]>
Add unit tests that flipping prefer_local_node_routing or
prefer_local_az_routing does not change DeploymentVersion equality or
trigger replica restart/reconfigure, while still broadcasting the updated
deployment config over long poll for routers.

Signed-off-by: wanadzhar913 <[email protected]>
… healthy state to verify there's no regression in the reconciliation loop

Signed-off-by: wanadzhar913 <[email protected]>
…test_options_locality_routing & test_decorator_locality_routing

Signed-off-by: wanadzhar913 <[email protected]>
Add Args entries for prefer_local_node_routing and
prefer_local_az_routing so public API param coverage and pydoclint
match the existing options() parameters. In response to ray-project#66267

Signed-off-by: wanadzhar913 <[email protected]>
ray-project#66513 typed the @serve.deployment overloads with a _DeploymentOptions
TypedDict and added test_typed_options_match_deployment_signature,
which checks that the TypedDict lists every keyword deployment()
takes. This branch added prefer_local_node_routing and
prefer_local_az_routing to deployment() but not to the TypedDict, so
the test fails after merging master. Type checkers would also reject
both options when passed to @serve.deployment(...).

Add both as Default[bool] fields, matching deployment()'s signature.
Also move the two options after max_surge_percent in DeploymentConfig
and Deployment.options() so they follow the same order as deployment().
In response to ray-project#66513

Signed-off-by: wanadzhar913 <[email protected]>
Co-authored-by: Cursor <[email protected]>
Wire prefer_local_node_routing and prefer_local_az_routing from deployment
config into AsyncioRouter and request routers, with env var fallback when
options are not user-configured. Includes unit and cluster e2e tests.

Signed-off-by: wanadzhar913 <[email protected]>
@wanadzhar913
wanadzhar913 force-pushed the bugfix/locality-routing-router-59929 branch from 8033d80 to cd1a616 Compare November 19, 2026 15:42

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

community-contribution Contributed by the community serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants