Skip to content

[Serve] Computed Retry-After for backpressure rejections - #66798

Open
suppagoddo wants to merge 11 commits into
ray-project:masterfrom
suppagoddo:my-feature
Open

suppagoddo wants to merge 11 commits into
ray-project:masterfrom
suppagoddo:my-feature

Conversation

@suppagoddo

@suppagoddo suppagoddo commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

Implements upstream RFC ray-project/ray#65879: an opt-in BackpressureConfig.retry_after_policy that computes Retry-After for backpressure rejections from load the rejecting component observes locally, instead of a guessed static value. The acceptance criteria are in #65879 (comment).

@serve.deployment(
    max_queued_requests=64,
    backpressure_config=BackpressureConfig(
        status_code=429,
        retry_after_policy="queue_drain_rate",  # "static" (default) | "queue_drain_rate"
        retry_after_s=5,                         # fallback until the estimate is warm
    ),
)

What changed

  • Config and proto: retry_after_policy: Literal["static", "queue_drain_rate"] = "static". The proto adds optional string retry_after_policy = 3 and leaves existing field numbers alone. An unset field from an older controller deserializes to "static".
  • _private/backpressure.py (new): one shared implementation for router and replica.
    • DrainRateEstimator keeps a monotonic drain counter N. The hot path only increments it.
    • Busy clock. A periodic sample (default every 1s) adds the interval to a busy clock B if work was pending or anything drained during it. A fully idle interval adds nothing, so idle time doesn't lower the rate. A stall (work pending, no drains) keeps adding busy time, so the estimate grows.
    • After each busy sample it records a checkpoint (B, N). The window starts at the most recent checkpoint at least 8 drains and at least 10 busy seconds back, or at the oldest checkpoint if none qualifies. Seconds per drain = window busy seconds / max(window drains, 1), and the estimate is queue depth × seconds per drain.
    • History is kept by drains, not by time, so sparse workloads (one drain every few minutes) are still measured. Checkpoints that can no longer start a window are pruned, so memory stays bounded (at most 21 checkpoints at the 1s default), independent of the time between drains.
    • The estimate is used only after a warmup of 3 busy samples.
    • "Pending work" means something different at the two rejection sites, because they count different drain events:
      • Router: queued requests only. The router counter measures assignment throughput. Once the router's queue is empty there is nothing left for it to drain, even if replicas are still running long requests.
      • Replica (direct ingress): queued or running requests. The replica counter measures completions (slot releases), so a running request will still produce a drain event when it finishes.
    • DrainRateTracker runs the sampler on its own MetricsPusher, only while the policy is queue_drain_rate. It doesn't depend on autoscaling.
    • Each sampling lifetime gets its own MetricsPusher, so switching queue_drain_rate → static → queue_drain_rate can't leave an old sampler running alongside the new one. Switching the policy on also clears the busy history.
    • compute_retry_after_decision() produces an immutable RetryAfterDecision. It walks the fallback ladder (computed → retry_after_s → no header), floors computed values at 1s with no upper cap, and draws ±10% jitter exactly once. The jittered value is rounded up to whole seconds, and computed values are floored at 1s again.
  • Router counter: counts requests accepted by a replica: a send without rejection, an accepted send, or an accepted slot reservation. It does not count replica rejections, failed sends, or cancellations while queued. num_requests_sent_to_replicas is an in-flight gauge and is not reused.
  • Replica counter (direct ingress): counts slot releases in _start_request, whether the request succeeded, raised, or was cancelled while running. Requests cancelled while queued and reservations released without running don't count.
  • Observed depth: both rejection sites use the queue depth seen at rejection, which can exceed max_queued_requests at the router.
  • Wire value: the decision's integer post_jitter_s is what goes into BackPressureError.retry_after_s and the direct-ingress header. retry_after_headers only formats it, so the proxy and composition paths can't jitter it a second time.
  • Telemetry: one structured warning per rejection, using extra={SERVE_LOG_EXTRA_FIELDS: ...}.
    • Fields: backpressure_request_id, backpressure_retry_after_policy, backpressure_retry_after_fallback_rung, backpressure_observed_queue_depth, backpressure_drain_rate (drains per busy second over the window), backpressure_busy_seconds, backpressure_drains_in_window, backpressure_seconds_per_drain, backpressure_estimator_warm, backpressure_estimator_num_samples, backpressure_retry_after_pre_jitter_s, backpressure_retry_after_post_jitter_s, backpressure_drain_counter.
    • backpressure_request_id is passed explicitly from each rejection site, because direct ingress rejects before the request's logging context is set up.
    • They're visible as separate fields when Serve logs use JSON encoding (LoggingConfig(encoding="JSON")).
    • The router enriches its existing warning. Direct-ingress rejections (HTTP and gRPC) logged nothing before and now emit this record.
  • Private counter accessors for the acceptance harness. Reads are immediate, with no controller round-trip:
    • Router: RouterMetricsManager._get_drain_counter()
    • Proxy: ProxyActor._get_backpressure_drain_counter_for_testing(route)
    • Replica: ReplicaActor._get_backpressure_drain_counter_for_testing()
  • Tunables: RAY_SERVE_BACKPRESSURE_BUSY_CLOCK_MIN_WINDOW_DRAINS (8), RAY_SERVE_BACKPRESSURE_BUSY_CLOCK_MIN_WINDOW_BUSY_S (10), RAY_SERVE_BACKPRESSURE_DRAIN_RATE_SAMPLE_INTERVAL_S (1), RAY_SERVE_BACKPRESSURE_DRAIN_RATE_WARMUP_SAMPLES (3) and RAY_SERVE_BACKPRESSURE_RETRY_AFTER_JITTER_FRACTION (0.1). The EWMA alpha setting is removed.
  • Docs: the load-shedding section of the best-practices guide and its doc code.

Behavior change for existing users

A static retry_after_s is now jittered by ±10%, as agreed in the RFC thread, to help spread the retries of clients rejected together. It is rounded up and never capped. For example, retry_after_s=7 now yields 7 or 8. Status codes and handle errors are otherwise unchanged.

Known limitations

  • Window lag: after a sudden slowdown or speedup, the estimate follows within the window (at least 8 drains and 10 busy seconds).
  • Local only: each estimate reflects only the component that rejected the request.
  • Not a reservation: the header is a hint, not a guarantee of admission.
  • Router handshake: if a caller is cancelled during the router's accept handshake, a hand-off can go uncounted. This is bounded and rare.
  • Router history survives deployment updates: a router that is reused across a deployment config or code update keeps its busy-clock history. The updated deployment may briefly get estimates based on the previous version until the window moves past it. Direct ingress doesn't have this problem for newly created replicas, which start with a cold estimator.
  • Acceptance benchmark: the scorer and scenario matrix are owned separately by @vinay7373, per the RFC thread. This PR supplies the counters and records that work needs.

Related issue number

Upstream: #65879.

Not a duplicate

The upstream RFC thread assigned this implementation to me (GitHub: @suppagoddo) on 2026-09-22. A search of open PRs for 65879, retry_after_policy, queue_drain_rate, and "Retry-After backpressure" turned up no other PR for this work.

Tests run

The tests ran on macOS arm64 with Python 3.11, the nightly wheel one day behind this base, and the Serve sources linked in via setup-dev.py.

  • Changed and new unit tests: 462 passed, 4 skipped (rerun on 46153ad).
    pytest python/ray/serve/tests/unit/test_backpressure_retry_after.py \
      python/ray/serve/tests/unit/test_router.py \
      python/ray/serve/tests/unit/test_replica_backpressure.py \
      python/ray/serve/tests/unit/test_config.py \
      python/ray/serve/tests/unit/test_schema.py \
      python/ray/serve/tests/unit/test_http_util.py \
      python/ray/serve/tests/unit/test_deployment_version.py \
      python/ray/serve/tests/unit/test_replica_quiesce.py
    
  • Full python/ray/serve/tests/unit/ suite (before the busy-clock commit): 4918 passed, 9 failed. The 9 are HAProxy and direct-ingress target-group tests in test_controller_haproxy.py and test_controller_direct_ingress.py. They fail the same way on the unmodified base in this environment.
    • Excluded: test_deployment_scheduler.py, which needs ray.tests and isn't in the wheel, and test_batching.py, which breaks test_deployment_state.py when run before it. That happens on the base too.
  • Lint: black 22.10.0, ruff 0.8.4 (including the isort rules), and pydoclint 0.9.1 are clean on the changed files.
  • Not yet run locally: the integration tests python/ray/serve/tests/test_backpressure.py and test_direct_ingress.py -k retry_after, because my local environment couldn't start a Ray cluster. They collect successfully, and I'll update this description once I've run them.

AI assistance

This PR was written with AI assistance (Claude Code). I reviewed the changes and am responsible for them.

Checks

  • I've signed off every commit (DCO).
  • I've added tests and docs.
  • Integration tests verified locally (pending, see above).

Older Implementation

Why are these changes needed?

Implements upstream RFC ray-project/ray#65879: an opt-in BackpressureConfig.retry_after_policy that computes Retry-After for backpressure rejections from load the rejecting component observes locally, instead of a guessed static value. The acceptance criteria are in #65879 (comment).

@serve.deployment(
    max_queued_requests=64,
    backpressure_config=BackpressureConfig(
        status_code=429,
        retry_after_policy="queue_drain_rate",  # "static" (default) | "queue_drain_rate"
        retry_after_s=5,                         # fallback until the estimate is warm
    ),
)

What changed

  • Config and proto: retry_after_policy: Literal["static", "queue_drain_rate"] = "static". The proto adds optional string retry_after_policy = 3 and leaves existing field numbers alone. An unset field from an older controller deserializes to "static".
  • _private/backpressure.py (new): one shared implementation for router and replica.
    • DrainRateEstimator keeps a monotonic drain counter. The hot path only increments it.
    • A periodic sample (default every 1s) folds the counter delta into an EWMA (alpha 0.3). The estimate is used only after a warmup of 3 counted intervals.
    • An interval with pending work and zero drains is a valid zero-rate sample. A fully idle interval is skipped, so the rate doesn't decay just because traffic stopped.
    • "Pending work" means something different at the two rejection sites, because they count different drain events:
      • Router: queued requests only. The router counter measures assignment throughput. Once the router's queue is empty there is nothing left for it to drain, even if replicas are still running long requests.
      • Replica (direct ingress): queued or running requests. The replica counter measures completions (slot releases), so a running request will still produce a drain event when it finishes.
    • DrainRateTracker runs the sampler on its own MetricsPusher, only while the policy is queue_drain_rate. It doesn't depend on autoscaling.
    • Each sampling lifetime gets its own MetricsPusher, so switching queue_drain_rate → static → queue_drain_rate can't leave an old sampler running alongside the new one.
    • compute_retry_after_decision() produces an immutable RetryAfterDecision. It walks the fallback ladder (computed → retry_after_s → no header), clamps computed values to [1, 60]s, and draws ±20% jitter exactly once.
  • Router counter: counts requests accepted by a replica: a send without rejection, an accepted send, or an accepted slot reservation. It does not count replica rejections, failed sends, or cancellations while queued. num_requests_sent_to_replicas is an in-flight gauge and is not reused.
  • Replica counter (direct ingress): counts slot releases in _start_request, whether the request succeeded, raised, or was cancelled while running. Requests cancelled while queued and reservations released without running don't count.
  • Observed depth: both rejection sites use the queue depth seen at rejection, which can exceed max_queued_requests at the router.
  • Wire value: the decision's integer post_jitter_s is what goes into BackPressureError.retry_after_s and the direct-ingress header. retry_after_headers only formats it, so the proxy and composition paths can't jitter it a second time.
  • Telemetry: one structured warning per rejection, using extra={SERVE_LOG_EXTRA_FIELDS: ...}.
    • Fields: backpressure_request_id, backpressure_retry_after_policy, backpressure_retry_after_fallback_rung, backpressure_observed_queue_depth, backpressure_drain_rate, backpressure_estimator_warm, backpressure_estimator_num_samples, backpressure_retry_after_pre_jitter_s, backpressure_retry_after_post_jitter_s, backpressure_drain_counter.
    • backpressure_request_id is passed explicitly from each rejection site, because direct ingress rejects before the request's logging context is set up.
    • They're visible as separate fields when Serve logs use JSON encoding (LoggingConfig(encoding="JSON")).
    • The router enriches its existing warning. Direct-ingress rejections (HTTP and gRPC) logged nothing before and now emit this record.
  • Private counter accessors for the acceptance harness. Reads are immediate, with no controller round-trip:
    • Router: RouterMetricsManager._get_drain_counter()
    • Proxy: ProxyActor._get_backpressure_drain_counter_for_testing(route)
    • Replica: ReplicaActor._get_backpressure_drain_counter_for_testing()
  • Tunables: RAY_SERVE_BACKPRESSURE_DRAIN_RATE_EWMA_ALPHA, ..._SAMPLE_INTERVAL_S, ..._WARMUP_SAMPLES, and RAY_SERVE_BACKPRESSURE_RETRY_AFTER_JITTER_FRACTION.
  • Docs: the load-shedding section of the best-practices guide and its doc code.

Behavior change for existing users

A static retry_after_s is now jittered by ±20%, as the RFC specifies, so that clients rejected together don't retry together. For example, retry_after_s=7 now yields 6 to 9. Status codes and handle errors are otherwise unchanged.

Open question for reviewers

Computed values are clamped to [1, 60] both before and after jitter, to keep the "at most 60s" guarantee. As a result, about half of the rejections whose estimate hits the 60s cap get exactly 60, so jitter spreads them less. The alternatives are allowing up to 72s, or capping the estimate at 50s before jitter. Feedback is welcome.

Known limitations

  • EWMA lag: the estimate lags after sudden slowdowns or speedups.
  • Local only: each estimate reflects only the component that rejected the request.
  • Not a reservation: the header is a hint, not a guarantee of admission.
  • Router handshake: if a caller is cancelled during the router's accept handshake, a hand-off can go uncounted. This is bounded and rare.
  • Router EWMA survives deployment updates: a router that is reused across a deployment config or code update keeps the drain rate it learned. The updated deployment may briefly get estimates based on the previous version until the EWMA converges on the new workload. Direct ingress doesn't have this problem for newly created replicas, which start with a cold estimator.
  • Acceptance benchmark: the scorer and scenario matrix are owned separately by @vinay7373, per the RFC thread. This PR supplies the counters and records that work needs.

Related issue number

Upstream: #65879.

Not a duplicate

The upstream RFC thread assigned this implementation to me (GitHub: @suppagoddo) on 2026-09-22. A search of open PRs for 65879, retry_after_policy, queue_drain_rate, and "Retry-After backpressure" turned up no other PR for this work.

Tests run

The tests ran on macOS arm64 with Python 3.11, the nightly wheel one day behind this base, and the Serve sources linked in via setup-dev.py.

  • Changed and new unit tests: 437 passed, 4 skipped.
    pytest python/ray/serve/tests/unit/test_backpressure_retry_after.py \
      python/ray/serve/tests/unit/test_router.py \
      python/ray/serve/tests/unit/test_replica_backpressure.py \
      python/ray/serve/tests/unit/test_config.py \
      python/ray/serve/tests/unit/test_schema.py \
      python/ray/serve/tests/unit/test_http_util.py \
      python/ray/serve/tests/unit/test_deployment_version.py \
      python/ray/serve/tests/unit/test_replica_quiesce.py
    
  • Full python/ray/serve/tests/unit/ suite: 4918 passed, 9 failed. The 9 are HAProxy and direct-ingress target-group tests in test_controller_haproxy.py and test_controller_direct_ingress.py. They fail the same way on the unmodified base in this environment.
    • Excluded: test_deployment_scheduler.py, which needs ray.tests and isn't in the wheel, and test_batching.py, which breaks test_deployment_state.py when run before it. That happens on the base too.
  • Lint: black 22.10.0, ruff 0.8.4 (including the isort rules), and pydoclint 0.9.1 are clean on the changed files.
  • Not yet run locally: the integration tests python/ray/serve/tests/test_backpressure.py and test_direct_ingress.py -k retry_after, because my local environment couldn't start a Ray cluster. They collect successfully, and I'll update this description once I've run them.

AI assistance

This PR was written with AI assistance (Claude Code). I reviewed the changes and am responsible for them.

Checks

  • I've signed off every commit (DCO).
  • I've added tests and docs.
  • Integration tests verified locally (pending, see above).

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@suppagoddo
suppagoddo marked this pull request as ready for review October 6, 2026 23:58
@suppagoddo
suppagoddo requested review from a team as code owners October 6, 2026 23:58
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

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

// How the `Retry-After` value is chosen: "static" or "queue_drain_rate".
// Unset (e.g. from an older controller during a rolling upgrade) falls back
// to "static" on the Python side.
optional string retry_after_policy = 3;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Proto change needs fault-tolerance review

Low Severity

⚠️ This PR modifies one or more .proto files.
Please review the RPC fault-tolerance & idempotency standards guide here:
https://github.com/ray-project/ray/tree/master/doc/source/ray-core/internals/rpc-fault-tolerance.md

Fix in Cursor Fix in Web

Triggered by project rule: Bugbot Rules

Reviewed by Cursor Bugbot for commit eeed736. Configure here.

@ray-gardener ray-gardener Bot added the community-contribution Contributed by the community label Oct 7, 2026
…_rate)

Implements RFC ray-project#65879. Adds `BackpressureConfig.retry_after_policy`
("static" default, or "queue_drain_rate"). The computed policy suggests
ceil(observed_queue_depth / drain_rate), clamped to [1, 60]s, where the
drain rate is an EWMA of the rejecting component's own drain events:
successful hand-offs to replicas at the router, execution-slot releases
at the replica (direct ingress). It falls back to `retry_after_s`, then
to no header, until the estimator is warm.

Retry-After values (static and computed) are jittered by +/-20% once at
the rejection site, and that same value is both logged and sent. Each
rejection emits one structured warning carrying the acceptance-test
fields (policy, fallback rung, observed depth, drain rate, warm flag,
pre/post-jitter value, drain counter). The monotonic drain counters are
readable through private testing accessors.

The proto field is optional, so configs from older controllers default
to "static".

Signed-off-by: uditagrawal <[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.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit daf306b. Configure here.

The proxy reuses its router (and drain-rate estimate) for a deployment ID
across tests, so a queue_drain_rate case could inherit a warm estimator
from the previous case. Give each case its own deployment name.

Signed-off-by: uditagrawal <[email protected]>
…ests

Cover two real-path gaps for queue_drain_rate:
- Direct ingress transitions from the static fallback to a computed
  Retry-After once real completions warm the replica's estimator.
- ProxyActor._get_backpressure_drain_counter_for_testing(route) exposes
  the proxy router's assignment counter over the actor API.

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

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

Overall great PR, thanks for taking this up.

Comment thread python/ray/serve/_private/router.py Resolved
Comment thread python/ray/serve/_private/router.py Resolved
@vinay7373

Copy link
Copy Markdown
Contributor

On your open question "at most 60s" guarantee: I'd keep the current behavior and leave the cap at 60s for now. An estimate at the cap usually means the queue needs longer than 60s, so those clients already come back early and capping at 50 would send them back even earlier. Allowing 72 would raise the limit through the back door.

I do think the 60s limit is worth revisiting, since the SDKs that motivated it have changed:

But that depends on how well the estimate holds up for long requests. The acceptance runs will give us data on both. Until then, let's keep 60s. Nothing needs to change in this PR.

…mple count to rejection records

A warm estimator with a drain rate of 0 has observed pending work that
never drained. That is a real slow-drain observation, so estimate_s now
returns inf and the computed path clamps it to 60s instead of falling
back to the static retry_after_s. Missing, negative and non-finite rates
still fall back.

Each structured rejection record now also carries
backpressure_request_id (threaded explicitly from the router and both
direct-ingress rejection sites, since direct ingress rejects before the
request context exists) and backpressure_estimator_num_samples
(snapshotted with the rest of the decision).

Tests that check the cold fallback no longer depend on rejecting before
the estimator can warm up on blocked work: the rejecting process gets an
unreachable warmup threshold via runtime_env. Adds router, replica and
direct-ingress integration coverage for the warm zero-rate path.

Signed-off-by: uditagrawal <[email protected]>
…ed log fields

Point users to JSON log encoding to see the request ID, queue depth,
drain counter, drain rate, sample count, fallback rung, and pre/post-
jitter Retry-After recorded for each backpressure rejection.

Signed-off-by: uditagrawal <[email protected]>
Switching the policy queue_drain_rate -> static -> queue_drain_rate within
one event-loop turn could leave the first sampler running: start() on the
reused MetricsPusher cleared the stop event before that sampler task had
checked it, so two samplers advanced the estimator.

Each sampling lifetime now gets its own pusher, stopped by setting its
stop event (which is never cleared again), and the registered sampler only
samples while its pusher is still the current one.

Replaces the wall-clock timer test with deterministic tests driven by a
manually released sleep, including a regression test for the restart race.

Signed-off-by: uditagrawal <[email protected]>
The mypy (ray serve) hook can't infer through the `sampling` property that
the pusher is set when stopping, so narrow it explicitly.

Signed-off-by: uditagrawal <[email protected]>
Per the RFC ray-project#65879 discussion, queue_drain_rate now estimates
observed_queue_depth * seconds_per_drain, where seconds_per_drain is busy
seconds / max(drains, 1) over the most recent busy stretch with at least 8
drains and at least 10 busy seconds. Busy time advances only in intervals
with pending work or a drain, so idle time never looks like slow draining
and a stall grows the estimate steadily. The EWMA was dominated by the time
since the last completion when completions were seconds apart.

The estimator keeps cumulative (busy clock, drain counter) checkpoints at
sample boundaries and starts the window at a real checkpoint, matching the
reference implementation, including with irregular sample spacing. History
is kept by drains rather than time, so a drain every 15 minutes is still
measured; checkpoints that can no longer start a window are pruned, keeping
memory to about 21 checkpoints at the default 1 s sample interval.

Also, per the RFC thread: jitter is now +/-10% (default
RAY_SERVE_BACKPRESSURE_RETRY_AFTER_JITTER_FRACTION=0.1), and computed values
keep a 1 s floor but no longer have a 60 s cap. Rejection records add
backpressure_busy_seconds, backpressure_drains_in_window and
backpressure_seconds_per_drain; backpressure_drain_rate is now drains per
busy second over the window.

Removes RAY_SERVE_BACKPRESSURE_DRAIN_RATE_EWMA_ALPHA and adds
RAY_SERVE_BACKPRESSURE_BUSY_CLOCK_MIN_WINDOW_DRAINS (8) and
RAY_SERVE_BACKPRESSURE_BUSY_CLOCK_MIN_WINDOW_BUSY_S (10).

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

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

@suppagoddo Thanks for implementing the busy clock. The implementation matches the design proposed in RFC #65879. All unit tests pass. All acceptance tests passed.

Comment on lines +51 to +53
# Computed values are never below this, before or after jitter. There is no
# upper bound: the busy clock stays proportional to the real wait even for long
# backlogs, so the header tells clients the expected wait.

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.

We should make it clear in docs that this retry hint can grow to large values like for example if there is a hour-long stall then the computed value be 3.8 hours. In future, if users prefer an upper bound then we could add a field to BackpressureConfig for their preferred upper bound. What do you think?

fallback_rung = FALLBACK_RUNG_NONE
elif static_s is not None:
fallback_rung = FALLBACK_RUNG_STATIC
pre_jitter_s = static_s

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.

Worth calling out in the description: the static policy is now jittered too (±10%). In Ray 2.58 and 2.59, retry_after_s is sent exactly as configured, so users of the static policy will see the header vary after upgrading.


The estimate is the queue depth at rejection multiplied by the average time the component has recently spent per drained request while it was busy: measured over its most recent busy period that covers at least 8 drained requests and at least 10 seconds. Time when the component had nothing to do doesn't count, and time spent with work pending but nothing finishing makes the estimate grow. The result is at least 1 second, with no upper limit, and is jittered like the static value. The proxy or `DeploymentHandle` counts queued requests it assigns to replicas; with direct ingress, the replica counts its running requests completing. Each estimate only reflects what the rejecting component observes locally.

Until a few seconds of busy time have been observed, for example right after a replica starts, rejections fall back to `retry_after_s`, or send no `Retry-After` header if it isn't set. The value is a hint, not a reservation: a retry at the suggested time isn't guaranteed to be admitted.

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.

Since there is no upper limit now, one sentence on client behavior would help operators: the OpenAI Python SDK does not retry when Retry-After is above 120 s, older OpenAI and Anthropic SDKs ignore values above 60 s and use their own backoff, and the current Anthropic SDK waits as long as it is told.

"backpressure_retry_after_policy": self.policy,
"backpressure_retry_after_fallback_rung": self.fallback_rung,
"backpressure_observed_queue_depth": self.observed_queue_depth,
"backpressure_drain_rate": self.drain_rate,

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.

The field now means drains per busy second over the window, not the EWMA. The docs list the window fields instead (busy seconds, drains in window, seconds per drain). Either say what drain_rate now means or drop it, so anyone comparing old and new logs is not misled.

@johntaylor-cell johntaylor-cell added serve Ray Serve Related Issue go add ONLY when ready to merge, run all tests labels Nov 3, 2026

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

Pre-existing (base does the same), but these tests hit it. After a spike, the router drained its backlog at ~4 requests/s for up to 15 s while the replica sat idle with 20–150 requests queued.

  1. In _fulfill_pending_requests (request_router.py:1288-1314), a routing task that fulfills another request continues its backoff generator, so it keeps sleeping max_backoff_s (0.5 s); both routing tasks were in backoff throughout the stall.
  2. With max_num_routing_tasks = 2 × replicas, one replica gets ~4 assignments/s until each task's own request reaches the front.
  3. Retry-After undershoots meanwhile: 7–11 s headers for a 12 s drain.


self._last_sample_time = now
self._last_sample_counter = counter
if drains == 0 and not has_pending_work:

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.

Any interval with a drain counts as a full busy second, so light traffic inflates the estimate. After 60 s at 0.5 req/s, a spike got Retry-After 65–81 s while the queue cleared in under 1 s.

  1. Could busy time accrue only while saturated?
  2. Update best-practices.md:141 ("Time when the component had nothing to do doesn't count") to match.
  3. Update the DrainRateEstimator docstring ("Idle time is ignored") to match.

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.

Good catch, and thanks for the numbers. I reproduced it with our reference estimator: after 60 s at 0.5 req/s the clock reads exactly 1.00 s per completion, so a queue of 65 gets 65 s. The cause is the second half of the busy rule. An interval with a completion counts as a full busy second even when the queue was empty, so light traffic teaches "1 s per completion" whatever the service time, and the 10 busy-second minimum keeps those seconds in the window for the first 10 s of a burst.

Your suggestion fixes it, and I would take it in its strict form: an interval enters the estimator only if the component had requests waiting in its queue at the sample. Completions in other intervals are not counted, and warm-up counts only those intervals. Light traffic then teaches nothing, which is right, since it carries no information about the drain rate. A burst after light traffic sends the static fallback for the first three saturated seconds and the computed value after that. In your case that is static, static, static, then 6.5 s for a 6.5 s wait, instead of 65 s. For the replica this means "queued" rather than "queued or running", so a running request with an empty queue no longer makes a second busy.

I replayed the strict rule on all 17 acceptance pairs from the recorded runs. 15 pairs are unchanged. Bursts with idle moves under 1% either way, Long requests on the proxy path goes from 1.91 to 2.16 (still 90% below static) and the 17-pair mean from 0.70 to 0.72.

@suppagoddo, can you make the change? I will rerun the acceptance matrix on the new commit and add a light-traffic scenario (0.5 req/s with fast requests, then a burst) so this case is covered from now on.

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.

Thanks @johntaylor-cell for catching this, and @vinay7373 for confirming the strict sampling rule.

Following are the changes I pushed:

  • An interval now contributes to the busy clock only when requests are queued at sampling time. Running-only replica requests and assignments/completions without queued work no longer train the estimator.
  • I also separated busy-interval drains from the global drain counter so that drains from skipped intervals cannot leak into future estimation windows.
  • Added deterministic regression tests covering the light-traffic-to-burst scenario, skipped-drain leakage, and router/replica queue-only behavior. The relevant unit tests pass locally.

@vinay7373, could you rerun the acceptance matrix and the new light-traffic scenario against this commit?

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]>
@vinay7373

Copy link
Copy Markdown
Contributor

Pre-existing (base does the same), but these tests hit it. After a spike, the router drained its backlog at ~4 requests/s for up to 15 s while the replica sat idle with 20–150 requests queued.

  1. In _fulfill_pending_requests (request_router.py:1288-1314), a routing task that fulfills another request continues its backoff generator, so it keeps sleeping max_backoff_s (0.5 s); both routing tasks were in backoff throughout the stall.
  2. With max_num_routing_tasks = 2 × replicas, one replica gets ~4 assignments/s until each task's own request reaches the front.
  3. Retry-After undershoots meanwhile: 7–11 s headers for a 12 s drain.

Thanks, that explains something we never hit. None of our scenarios needs more than about 2 assignments per second per replica, so the ceiling never bound and the sanity checks passed. It will matter for fast models, which is also the regime of your other comment. Since it is pre-existing and sits in the router's backoff loop, I would keep it out of this PR and open a separate issue for _fulfill_pending_requests keeping its backoff after a hand-off; I can file it with your numbers if you prefer. On the undershoot: the estimator measures what the router actually does, so while the router is throttled the hint follows the throttled rate once the window has seen it. The early hints in your test most likely come from the faster assignments made before the throttle bit. Once the router is fixed the hint follows on its own. The light-traffic scenario I am adding uses fast requests, so it should catch this too.

An interval with a drain used to count as a full busy second even with
an empty queue, so light traffic taught the estimator about 1 s per
drain: after 60 s at 0.5 req/s, a burst of 65 got Retry-After ~65 s
while the queue cleared in under a second.

A sample interval is now busy only if requests are waiting in the
component's queue at the sample (router: waiting for assignment;
replica: waiting for a slot, so running-only no longer counts). A busy
interval adds its time and its own drains; other intervals are skipped
with their drains. Checkpoints use a separate count of busy-interval
drains, so drains in skipped intervals can't leak into a later window.
The global drain counter still counts every drain for ground truth.
Queued work with no drains still advances the clock.

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

Copy link
Copy Markdown
Contributor

Pre-existing (base does the same), but these tests hit it. After a spike, the router drained its backlog at ~4 requests/s for up to 15 s while the replica sat idle with 20–150 requests queued.

  1. In _fulfill_pending_requests (request_router.py:1288-1314), a routing task that fulfills another request continues its backoff generator, so it keeps sleeping max_backoff_s (0.5 s); both routing tasks were in backoff throughout the stall.
  2. With max_num_routing_tasks = 2 × replicas, one replica gets ~4 assignments/s until each task's own request reaches the front.
  3. Retry-After undershoots meanwhile: 7–11 s headers for a 12 s drain.

Thanks, that explains something we never hit. None of our scenarios needs more than about 2 assignments per second per replica, so the ceiling never bound and the sanity checks passed. It will matter for fast models, which is also the regime of your other comment. Since it is pre-existing and sits in the router's backoff loop, I would keep it out of this PR and open a separate issue for _fulfill_pending_requests keeping its backoff after a hand-off; I can file it with your numbers if you prefer. On the undershoot: the estimator measures what the router actually does, so while the router is throttled the hint follows the throttled rate once the window has seen it. The early hints in your test most likely come from the faster assignments made before the throttle bit. Once the router is fixed the hint follows on its own. The light-traffic scenario I am adding uses fast requests, so it should catch this too.

Yes, please file a separate issue for the router plateau issue @vinay7373

@johntaylor-cell

Copy link
Copy Markdown
Contributor

Second pass. The light-traffic fix works. That spike now gets the static fallback (5–6 s) instead of 65–81s, thanks. More comments:

  1. backpressure.py:224: skipping the interval in which the queue empties also drops the drains that emptied it. Direct ingress, 8 × 6 s slots, 8 queued: the next spike got Retry-After 45–53 s for a 6 s wait (0 drains in the window; 46153ad: 5–6 s). Counting those drains (not the time) gave 6–8 s for 6–7 s waits (later bursts 4–6 s; now 6–11 s) and kept the light-traffic fix. best-practices.md:141 would need to match.
  2. router.py:203: num_queued_requests also counts requests that are only being routed, so light steady traffic trains the router at about one arrival interval per drain. Proxy, 160 req/s capacity, after 10 min at 5 req/s: a spike got 20–25 s for a <1 s wait. The planned 60 s, 0.5 req/s scenario won't catch it. Could routing-only requests be skipped? Otherwise "Light traffic that never builds a backlog doesn't count" (best-practices.md:141) is wrong for proxy and handle.
  3. router.py:577: nothing fails without it. test_sampler_lifecycle_follows_config_updates could end with:
        router.update_deployment_config(computed)
        assert tracker.sampling
        await router.shutdown()
        assert not tracker.sampling
  1. replica.py:1967: nothing fails without it; e.g. deploy static (retry_after_s=100), redeploy queue_drain_rate (same replica), stall one request with one queued, and wait for Retry-After < 90.
  2. constants.py:1219: untested; e.g.:
def test_jitter_fraction_of_one_or_more_is_rejected(monkeypatch):
    import importlib
    import ray.serve._private.constants as constants
    monkeypatch.setenv("RAY_SERVE_BACKPRESSURE_RETRY_AFTER_JITTER_FRACTION", "1")
    with pytest.raises(ValueError):
        importlib.reload(constants)
    monkeypatch.delenv("RAY_SERVE_BACKPRESSURE_RETRY_AFTER_JITTER_FRACTION")
    importlib.reload(constants)
  1. test_estimator_failure_falls_back: estimate_s can't raise, so this tests a hypothetical.
  2. router.py:270 and Replica._decide_direct_ingress_backpressure duplicate decide → error → log; could a DrainRateTracker.reject() do it?
  3. Could the duplicated test helpers live once in _private/test_utils.py: the three fake clocks, capture_serve_log_records (inlined again in test_replica_backpressure.py:294), and COLD_ESTIMATOR_RUNTIME_ENV?
  4. The three new direct-ingress tests could share their block-one, queue-one, reject-one setup.
  5. The description still has the old busy rule and the replica's "queued or running requests".

@vinay7373

vinay7373 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

@johntaylor-cell thanks for the second pass. Here are alternate proposals for items 1 and 2 in your list:

  1. Reproduced the backpressure.py:224 issue. Your proposal "count the drains but not the time" fails in light traffic scenario. I replayed it on our recorded runs of the light-then-burst scenario: the completions of the light phase enter the window with no busy time behind them, seconds per drain sinks toward zero and every hint sits at the 1 s floor (loss 4.2 and 2.6 against 0.5 and 0.3 on e2cea2f, 100% early). It looked fine in the 8-slot case only because the mismatch there is small, 8 extra drains against 6 counted seconds. The busy clock's premise is that the time and the drains in the window describe the same period, so an interval should contribute both or neither.

    Solution that works: an interval counts if requests were queued at its start or at its end, that is, at the previous sample or at this one. The interval in which a line clears then counts with its completions, because the previous sample saw the line. Light traffic still never counts, because no sample ever sees a line. In sample():

    busy = has_pending_work or self._prev_pending_work   # queued at either end of the interval
    self._prev_pending_work = has_pending_work
    if not busy:
        return

    with _prev_pending_work reset to False in reset_rate. I verified this by replayed this on all scenarios and they look good. On your 8-slot case it gives 7.0 s for a 6 s wait. For best-practices.md:141: "only seconds in which requests were queued at the start or the end count as busy, along with the requests drained in them".

  2. Confirmed the router.py:203 mechanism in the code: num_queued_requests is incremented around the whole routing attempt, so when a request spends a few milliseconds finding a free slot, a sample that lands in those milliseconds sees a backlog and counts the interval as busy, although the request never waited; those milliseconds were only the time to assign a replica. Under steady light traffic this trains the clock at about one arrival interval per drain.

    Proposal: the router's pending signal should mean "a request is waiting because no replica had a free slot", which the request router already tracks as routing tasks in backoff. Something like

    has_pending_work=lambda: self._active_request_router().num_routing_tasks_in_backoff > 0

    (or a small accessor on RequestRouter), for the proxy router and the handle router alike. A request placed on its first attempt then never counts as a line. The replica side is unaffected, since it counts requests waiting for a slot already. Please update the docs sentence to say the proxy and handle count requests that could not be placed on their first attempt.
    I will add a steady-light-traffic cell, five minutes at a few requests per second on an 8-slot deployment and then a spike, on both paths, and rerun the full matrix once all items are in, so the final commit carries one complete set of results.

I agree with the rest of the items, 3 to 10.

@johntaylor-cell

Copy link
Copy Markdown
Contributor

Thanks @vinay7373

  1. Agreed. Live, the first spike after light traffic still gets the static fallback, and the next direct-ingress spike gets 8–9 s for a 6 s wait (currently 45–53 s). (Mine only added drains of an interval that started with a queue, so light traffic never entered.)
  2. Agreed, but under heavy CPU load it misses backlogs. One spike had 17 s queued with no routing task in backoff, so the router stayed cold. Could the matrix include a loaded cell?
    For the steady-traffic cell: 5 req/s currently takes ~3 min to warm the router, so a few req/s for 5 min may not catch it.

@vinay7373

Copy link
Copy Markdown
Contributor

@johntaylor-cell agree on item 2: backoff alone misses a backlog the router itself causes and the current signal would have measured it, so I don't want to regress that. Proposal: an interval is busy if a request is waiting for a routing task or a routing task is in backoff. Both states exist already:

 has_pending_work=lambda: (
     self._active_request_router().num_routing_tasks_in_backoff > 0
     or len(self._active_request_router()._pending_requests_to_route) > 0
 )

(or one accessor on RequestRouter), for the proxy and handle routers. A request in the milliseconds of being assigned, with nothing behind it, is in neither, so light traffic still teaches nothing. Replica side unchanged.

Steady-traffic cell: I'll run it at about 8 req/s for five minutes on an 8-slot deployment, then a spike, on both paths. I wouldn't add a CPU-loaded cell to this PR, since the combined signal counts a router-bound backlog by construction; happy to run one as a follow-up if wanted.

…og for the busy clock

An interval now counts if requests were queued at its start or its end
(the previous sample or this one), so the interval in which a backlog
clears keeps the drains that cleared it. Time and drains still enter the
window together; other intervals are skipped with their drains.

The router's busy signal is RequestRouter.has_queue_pressure(): a
routing task in backoff or a request waiting for a routing task.
num_queued_requests also counted requests that were only being routed,
so light steady traffic trained the estimator. Cancelled or fulfilled
requests left in the routing deque are popped lazily so they can't keep
an idle router busy.

Also: a shared reject_for_backpressure() for the router and direct
ingress; tests for router shutdown, static-to-computed redeploy and
jitter-fraction validation; shared test helpers.

Signed-off-by: uditagrawal <[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

community-contribution Contributed by the community 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.

3 participants