Skip to content

[serve] Add request_routing_timeout_s to bound replica assignment - #66512

Open
codechrl wants to merge 11 commits into
ray-project:masterfrom
codechrl:serve-request-routing-timeout-v2
Open

codechrl wants to merge 11 commits into
ray-project:masterfrom
codechrl:serve-request-routing-timeout-v2

Conversation

@codechrl

@codechrl codechrl commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

_choose_replica_for_request awaits the pending request's future with no bound. A request waits with no error while every replica is at capacity. It also waits while the deployment has no replicas, for example when a scaled-to-zero deployment can't schedule a new replica. HTTPOptions.request_timeout_s applies to the HTTP proxy only and also counts processing time. A DeploymentHandle caller can bound assignment only per call, by wrapping _to_object_ref() in asyncio.wait_for and cancelling the response on timeout. _to_object_ref() returns on assignment since #65243.

This adds request_routing_timeout_s to RequestRouterConfig. It follows the same path as the backoff fields: serve.proto, then AsyncioRouter. The default None keeps the current behavior.

The timeout lives in AsyncioRouter as one deadline per request. It starts on the first routing attempt, after the arguments resolve, and retries after a replica rejects the request don't restart it. It covers assign_request, choose_replica with and without reservation, and CapacityQueueRouter. Time spent in reserve_slot or probing counts toward the deadline but isn't interrupted.

  • On expiry the request's future is cancelled and RequestRoutingTimeoutError, a TimeoutError subclass, is raised. The HTTP proxy returns 408 and the gRPC proxy DEADLINE_EXCEEDED, both with the error's own message.
  • handle.py re-raises the error, so Python 3.11+ no longer rewrites it to Timed out resolving to ObjectRef..
  • Timeout cleanup is amortized: the done prefix of both pending queues is popped right away, and the queues are compacted only once timeouts could fill half of them, so cleanup cost doesn't grow with queue length. Routing skips done entries.
  • On Python 3.10 an asyncio.TimeoutError raised by the request router itself propagates; only an expired routing deadline becomes RequestRoutingTimeoutError.
  • ConsistentHashRouter shares the base router's routing-task helpers and registers its routing task per request, so a timed-out request stops it.
  • __eq__ and __hash__ include the field. broadcast_deployment_config_if_changed compares configs with ==, so a timeout-only change would otherwise never reach the routers.
  • The proto field is optional, so an unset value doesn't come back as 0.0.
  • HAProxy ingress queues outside the Python router, so the timeout doesn't bound it. performance.md says so.

Related issues

Closes #40995

Additional information

Not a duplicate: no open or closed PR references #40995. #64399 (open) adds max_request_retries for #61017. It bounds the retry loops that run after a replica rejects a request. It doesn't bound the wait inside _choose_replica_for_request. Both PRs add field 9 to RequestRouterConfig in serve.proto, so whichever merges second needs to renumber.

Tests:

  • test_router.py: TestRequestRoutingTimeout covers the single deadline across retries, the done-prefix pop and the half-queue compaction, routing skipping timed-out entries, _reserve=False, a router's own TimeoutError/asyncio.TimeoutError propagating, and the routing task stopping with every replica at capacity.
  • test_consistent_hash_router.py: a timed-out request stops its routing task, and with one replica, cancelled routing tasks are replaced so a queued third request is still routed.
  • test_http_util.py and test_grpc_util.py: 408 and DEADLINE_EXCEEDED use the error's message, including when wrapped in RayTaskError.
  • test_config.py: proto round trip for None and 1.5, and equality.

Each new test fails with its source hunk reverted. Ran with this branch's python/ray/serve merged with current master on the nightly wheel, Python 3.11: 410 passed, 6 skipped, 1 failed. The failing test_config proto round trip is because the wheel's generated serve_pb2 lacks the new field. The 3.10 branch of _wait_for_routing was checked on CPython 3.9 and 3.10 with a standalone script. Not run: the suite on Python 3.10 and 3.12+, a live CapacityQueueRouter, HAProxy.

Disclaimer: this PR was prepared with the assistance of an AI agent (Claude Code). All code and test changes were reviewed by the author before submission.

_choose_replica_for_request awaits the pending request's future with no
bound. A request waits with no error while every replica is at
capacity. It also waits while the deployment has no replicas, for
example when a scaled-to-zero deployment can't schedule a new replica.
HTTPOptions.request_timeout_s applies to the HTTP proxy only and also
counts processing time.

Add request_routing_timeout_s to RequestRouterConfig. When set, a
request that isn't assigned a replica within the timeout raises
TimeoutError. The timeout does not cover the time the replica takes to
handle the request. The default of None keeps the current behavior.

RequestRouterConfig equality includes the new field, so a timeout-only
config change is broadcast to routers.

Closes ray-project#40995

Signed-off-by: codechrl <[email protected]>

@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 a new configuration option, request_routing_timeout_s, allowing users to set a timeout for assigning requests to replicas in Ray Serve. Key changes include updates to RequestRouterConfig, the protobuf definition, documentation, and the request routing logic to handle and raise a timeout error when the limit is exceeded. The review feedback highlights a potential memory leak in the queue cleanup logic due to head-of-line blocking and suggests filtering the queues in-place. Additionally, it recommends raising asyncio.TimeoutError instead of the built-in TimeoutError to ensure backward compatibility with Python versions prior to 3.11, along with corresponding updates to the unit tests.

Comment on lines +1435 to +1438
raise TimeoutError(
f"Failed to route request to a replica of {self._deployment_id} "
f"within {self.request_routing_timeout_s}s."
) from None

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

In Python versions prior to 3.11, asyncio.TimeoutError and the built-in TimeoutError are distinct exception classes (with different inheritance hierarchies). Since this is an asynchronous API and callers typically expect asyncio.TimeoutError when awaiting async operations, raising asyncio.TimeoutError is more idiomatic and ensures backward compatibility for callers catching asyncio.TimeoutError on Python 3.8 - 3.10.

Suggested change
raise TimeoutError(
f"Failed to route request to a replica of {self._deployment_id} "
f"within {self.request_routing_timeout_s}s."
) from None
raise asyncio.TimeoutError(
f"Failed to route request to a replica of {self._deployment_id} "
f"within {self.request_routing_timeout_s}s."
) from None

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.

Builtin TimeoutError is intentional. The HTTP/gRPC proxies map isinstance(exc, TimeoutError) to 408/DEADLINE_EXCEEDED (http_util.py, grpc_util.py), and handle.py re-raises asyncio.TimeoutError as the builtin for the same reason. On 3.10, asyncio.TimeoutError isn't a subclass of the builtin, so switching would turn the 408 into a 500.

loop = get_or_create_event_loop()

task = loop.create_task(s._choose_replica_for_request(fake_pending_request()))
with pytest.raises(TimeoutError, match="Failed to route request to a replica"):

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

Update the test to expect asyncio.TimeoutError to match the exception raised by the request router.

Suggested change
with pytest.raises(TimeoutError, match="Failed to route request to a replica"):
with pytest.raises(asyncio.TimeoutError, match="Failed to route request to a replica"):

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.

The router raises the builtin TimeoutError on purpose (see the thread on request_router.py), so the test stays as is.

s.update_replicas([r1])

task = loop.create_task(s._choose_replica_for_request(fake_pending_request()))
with pytest.raises(TimeoutError, match="Failed to route request to a replica"):

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

Update the test to expect asyncio.TimeoutError to match the exception raised by the request router.

Suggested change
with pytest.raises(TimeoutError, match="Failed to route request to a replica"):
with pytest.raises(asyncio.TimeoutError, match="Failed to route request to a replica"):

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.

Same as above: the builtin TimeoutError is intentional, so the test stays as is.

@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/config.py Resolved
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue docs An issue or change related to documentation community-contribution Contributed by the community labels Sep 27, 2026

@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
The lazy cleanup only pops a done prefix, so a request that timed out
behind a still-pending one stayed queued. Remove it by identity on
timeout, cancel its future explicitly, and leave the optional
request_routing_timeout_s proto field unset when it is None, matching
retry_after_s.

Signed-off-by: codechrl <[email protected]>
@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 13, 2026
@johntaylor-cell johntaylor-cell added go add ONLY when ready to merge, run all tests and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Oct 22, 2026
@johntaylor-cell

johntaylor-cell commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

@codechrl Please fix the premerge test failure. Please rebase. And I found a few things from testing this:

  1. A timeout below the handle's metric sampling interval (6s by default) can keep a scaled-to-zero deployment at zero, because the request times out before it is ever reported.
  2. With ConsistentHashRouter, a timed-out request's routing task keeps running after the queue stops counting it, so requests for other sessions can time out while their replicas are idle.
  3. Routing timeouts are misreported: the proxy's 408 cites its own request_timeout_s, and on Python 3.11+ .result() says "Timed out resolving to ObjectRef." A dedicated exception would fix both.
  4. Retries restart the timer, so the total wait has no bound. Could this use one deadline per request?
  5. choose_replica(_reserve=False), HAProxy ingress and CapacityQueueRouter ignore the setting.

Move the timeout into AsyncioRouter so retries, choose_replica with
_reserve=False and CapacityQueueRouter share a single deadline.
Raise RequestRoutingTimeoutError (a TimeoutError subclass) and map it
to 408 and DEADLINE_EXCEEDED with its own message. Register the
ConsistentHashRouter routing task per request so a timed-out request
stops it, and record the queued request before the scale-from-zero
metrics push.

Signed-off-by: codechrl <[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 and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 515da64. Configure here.

@johntaylor-cell

Copy link
Copy Markdown
Contributor

@codechrl Please address bot comment and the premerge test failure

A rejected request is re-inserted into the pending queues while its earlier
entry can still be queued, so removal by identity must not stop at the first
match. Otherwise one copy keeps num_pending_requests inflated.

Signed-off-by: codechrl <[email protected]>
@johntaylor-cell

Copy link
Copy Markdown
Contributor

@codechrl premerge still fails the serve mypy hook: router.py:1064-1089 use the routing result without handling None. pre-commit run mypy --files python/ray/serve/_private/router.py reproduces it locally.

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]>
@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 Nov 13, 2026
…ting-timeout-v2

Signed-off-by: codechrl <[email protected]>

# Conflicts:
#	python/ray/serve/_private/router.py
#	python/ray/serve/tests/unit/test_http_util.py
_wait_for_routing returned Any, so replica stayed Optional[RunningReplica]
after routing and the serve mypy hook flagged every use of it in
_route_and_send_request_once. Make it generic over the awaited value.

Signed-off-by: codechrl <[email protected]>
@johntaylor-cell

Copy link
Copy Markdown
Contributor

Thanks @codechrl, mypy and premerge pass now. A few remaining items:

  1. request_router.py:909: every timeout scans both dequeues, so under overload cleanup grows with rate²: 0.5 ms CPU per timeout at 5k queued, over 1 s of CPU per second at 1000 req/s with a 10 s timeout. Popping the done prefix and compacting only once timeouts could fill half the queue stays under 20 µs. A request behind a pending one would then stay until compaction, which the two test_drops_* tests don't allow.
  2. router.py:1543: on 3.10 this also turns the request router's own asyncio.TimeoutError into a routing timeout. It should re-raise unless the deadline expired. Parametrize test_request_router_timeout_error_propagates over TimeoutError and asyncio.TimeoutError to cover it.
  3. consistent_hash_router.py:369-372 is untested: its unit tests all pass without it. Suggested test: one replica, cancel the two requests being routed while a third waits, free the replica, and assert the third gets routed.
  4. consistent_hash_router.py:307-311, 353-361, 371-372 duplicate the base _fulfill_pending_requests. Could both loops share RequestRouter helpers?

In the description, the scaled-to-zero bullet (on master via ray-project/ray#67087) and the test_pow_2_request_router.py entry are stale. Thanks

@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 Nov 17, 2026
…ting-timeout-v2

# Conflicts:
#	python/ray/serve/tests/unit/test_grpc_util.py
…tError on 3.10

- Pop the done prefix of the pending queues on each timeout and compact
  them only once timeouts could fill half the queue.
- On Python < 3.11, re-raise an asyncio.TimeoutError raised by the request
  router itself; only an expired deadline becomes RequestRoutingTimeoutError.
- Share routing-task bookkeeping between RequestRouter and
  ConsistentHashRouter, and test the consistent-hash routing-task restart.

Signed-off-by: codechrl <[email protected]>
@codechrl

Copy link
Copy Markdown
Contributor Author

Thanks. Pushed:

  1. A timeout now pops the done prefix of both queues and compacts only once timeouts could fill half the queue; routing skips done entries. Tests cover the prefix pop, the threshold and the skip.
  2. Before 3.11 the step runs as a task; an asyncio.TimeoutError re-raises unless wait_for cancelled the task. test_request_router_timeout_error_propagates is parametrized over both classes.
  3. Added test_cancelled_routing_tasks_are_replaced_for_queued_request (fails without the restart).
  4. Both loops share _register_routing_task / _unregister_routing_task / _finish_routing_task and _drop_done_pending_requests.

Merged master, description updated.

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 docs An issue or change related to documentation go add ONLY when ready to merge, run all tests 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.

[Serve] Add a timeout parameter for scheduling ray tasks to replicas

2 participants