Skip to content

[serve][llm] Fall back to available replicas when ingress routers fail - #66339

Merged
jeffreywang88 merged 12 commits into
masterfrom
ingress-router-failure-fallback
Oct 1, 2026
Merged

jeffreywang88 merged 12 commits into
masterfrom
ingress-router-failure-fallback

Conversation

@jeffreywang88

@jeffreywang88 jeffreywang88 commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

HAProxy returns errors when an ingress router fails, even if serving replicas remain healthy. This interrupts requests during router failures or restarts.

Solution

Serve

Always enable fallback whenever an ingress request router is configured. If the router cannot select a usable replica, HAProxy can select an available serving replica using random(1). For a pin-miss, HAProxy first uses the head Serve proxy when it is healthy.

Selection Order

For an ingress router failure,

  • Master: Try each ingress router → return 503. The head Serve proxy is not tried.
  • This PR: Try each ingress router → choose a healthy LLMServer replica from local HAProxy’s list with random(1) → use the head Serve proxy only if no local replica is healthy → fail if neither can serve the request.

A pin-miss has a different order because a router did respond, but selected a replica absent from local HAProxy’s list:

  • Master: Try the head Serve proxy if configured → if HAProxy marks it down, select a local replica using the backend’s balancing policy (default leastconn). Without a configured head proxy, return 503.
  • This PR: Try the head Serve proxy if configured → if it is unavailable, randomly select a healthy local replica. With no head proxy configured, select a healthy local replica directly.

Serve LLM specifics

Fallback applies to all direct-streaming routing policies. Requests served through fallback may not follow KV-aware or session routing. Fallback metrics and warnings are emitted when RAY_SERVE_INGRESS_REQUEST_ROUTER_METRICS_ENABLED=1.

Validation

  • HAProxy tests cover router failures, recovery, random(1) configuration, and YAML deployment.
  • Metrics tests cover fallback reasons and warning rate limiting.
  • A direct-streaming test kills an ingress-router replica and verifies that streaming and non-streaming requests continue to succeed.

Metrics validation

Validation and metrics repro

Validated with real HAProxy:

  • Router failures return HTTP 503 without the fallback change and succeed with it.
  • Killing an ingress-router replica preserves streaming and non-streaming requests; routing resumes through its replacement.
  • Leastconn selects an idle replica while another replica has an active request.
  • Five successful fallback requests increased the exported fallback counter.

Repro

Save as fallback_metrics.py and run with this branch installed. The ingress router returns 503, while the serving replica returns "ok".

import os
import time

os.environ["RAY_SERVE_ENABLE_HA_PROXY"] = "1"
os.environ["RAY_SERVE_INGRESS_REQUEST_ROUTER_METRICS_ENABLED"] = "1"

import ray
import requests
from fastapi import FastAPI, Response
from ray import serve

router_app = FastAPI()


@serve.deployment(request_router_config={"ingress_router_fallback": True})
class Ingress:
    async def __call__(self):
        return "ok"


@serve.deployment
@serve.ingress(router_app)
class FailingRouter:
    @router_app.post("/internal/route")
    async def route(self):
        return Response(status_code=503)


ray.init(
    address="local",
    num_cpus=2,
    include_dashboard=False,
    _metrics_export_port=18080,
    _system_config={"metrics_report_interval_ms": 100},
)
try:
    serve.run(
        Ingress.bind()._with_ingress_request_router(FailingRouter.bind()),
        name="fallback-demo",
    )

    # Wait for HAProxy to discover the router and export a fallback sample.
    for _ in range(60):
        response = requests.post("http://localhost:8000/", timeout=10)
        assert response.status_code == 200, response.text
        assert response.text == "ok"

        metrics = requests.get("http://localhost:18080/metrics", timeout=10).text
        samples = [
            line for line in metrics.splitlines()
            if line.startswith("ray_serve_haproxy_ingress_router_fallbacks_total{")
            and 'application="fallback-demo"' in line
            and 'reason="router_non_200"' in line
            and float(line.rsplit(" ", 1)[1]) > 0
        ]
        if samples:
            print("\n".join(samples))
            break
        time.sleep(1)
    else:
        raise RuntimeError("Fallback metric did not appear")

    input("Ready for queries below. Press Enter to shut down this repro.")
finally:
    serve.shutdown()
    ray.shutdown()
python fallback_metrics.py

Query the exported counter

In another terminal:

curl -fsS localhost:18080/metrics |
  grep '^ray_serve_haproxy_ingress_router_fallbacks_total'

The sample should include application="fallback-demo" and reason="router_non_200".

Send five more requests:

for i in 1 2 3 4 5; do
  curl -fsS -X POST localhost:8000/ -w ' HTTP %{http_code}\n'
done

All five should return ok HTTP 200. After metrics export catches up, querying the counter again should show an increase of five.

PromQL

Once Prometheus scrapes the Ray metrics endpoint on port 18080:

sum by (application, reason) (
  ray_serve_haproxy_ingress_router_fallbacks_total{application="fallback-demo"}
)

Related issues

Link related issues: "Fixes #1234", "Closes #1234", or "Related to #1234".

Additional information

Optional: Add implementation details, API changes, usage examples, screenshots, etc.

@jeffreywang88
jeffreywang88 requested review from a team as code owners September 20, 2026 22:30
@jeffreywang88 jeffreywang88 added the go add ONLY when ready to merge, run all tests label Sep 20, 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 ingress router failure fallback support for direct-streaming applications in Ray Serve, allowing HAProxy to route requests to available serving replicas when the ingress router is unavailable or fails. The changes include updates to configuration schemas, HAProxy templates, Lua routing scripts, metrics collection, and tests. The review feedback identifies three important issues: a potential AttributeError in the controller when request_router_config is None, a Pydantic v1/v2 compatibility issue in the builder when using model_copy, and a potential Ray re-initialization error in the HAProxy API tests.

Comment thread python/ray/serve/_private/controller.py 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.

Stale Bugbot comment from a previous run.

Comment thread src/ray/protobuf/serve.proto Resolved
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue llm labels Sep 21, 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 python/ray/serve/config.py Resolved
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>
@@ -190,6 +194,8 @@ local function _route_via_ingress_request_router(txn, app, pool, replica_map)
txn:set_var("txn.ingress_request_router_failed", "router_unreachable")

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] A router that is alive but stuck now costs every request the full router timeout before this fallback kicks in.

call_router sets sock:settimeout(ROUTER_REQUEST_TIMEOUT_S), 5s by default. Nothing carries over between requests except _rr_cursor. If the co-located LLMRouter's event loop stalls while it still accepts connections, every POST waits 5s in receive("*a") before moving on. With the default of one router per node it then falls back here, so every request on that node gains 5s of TTFT. With two routers, half the requests still try the stuck one first.

Before this PR the same stall surfaced as 503s. With fallback on and router metrics off by default, it's a silent brownout. LLMRouter also doesn't define check_health, so Serve has no fast signal to replace a slow but live router.

A per-thread breaker next to _rr_cursor would cover it: after N consecutive router_unreachable results, skip the router for T seconds and let one request through as a probe. The other option is to put the routers in an HAProxy backend with option httpchk GET /health (LLMRouter already serves /health) and skip DOWN ones from Lua.

Assisted by Claude Code

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.

If I'm understanding correctly, this is about the wait time between attempts to send a request to each ingress request router replica.

Suppose there are three ingress request router replicas X, Y, and Z:

  • If X accepts the connection but never completes its response, HAProxy waits for its socket timeout (5 seconds by default), then tries Y.
  • If Y also gives no response, it tries Z.

This loop and timeout are the same on master and this PR. What this PR changes is the result after all router attempts fail: master returns 503; this PR can serve the request from a healthy LLMServer replica.

The comment is mainly about repeating that wait on later requests. HAProxy does not remember that X stalled; when a later request starts at X, it can pay the same timeout again. With just one router replica, every request would suffer the wait. That said, given that this behavior isn't directly related to the fallback logic for all ingress router failure, I think it's out-of-scope for this PR. I'll track this with a GH issue.

@jeffreywang88
jeffreywang88 requested a review from a team as a code owner September 24, 2026 18:49
@jeffreywang88
jeffreywang88 force-pushed the ingress-router-failure-fallback branch from 045d821 to 21a63a1 Compare September 24, 2026 18:59

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stale Bugbot comment from a previous run.

@jeffreywang88
jeffreywang88 force-pushed the ingress-router-failure-fallback branch from 21a63a1 to 8a77989 Compare September 24, 2026 20:43
@jeffreywang88
jeffreywang88 force-pushed the ingress-router-failure-fallback branch from 8a77989 to c33acec Compare September 24, 2026 20:57

@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/controller.py 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.

Stale Bugbot comment from a previous run.

Comment thread src/ray/protobuf/serve.proto Resolved
Signed-off-by: Jeffrey Wang <[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.

Stale Bugbot comment from a previous run.

Comment thread python/ray/serve/_private/controller.py Resolved
Signed-off-by: Jeffrey Wang <[email protected]>
@jeffreywang88 jeffreywang88 changed the title [serve][llm] Fall back to leastconn upon ingress routers failures [serve][llm] Fall back to available replicas when ingress routers fail Sep 25, 2026
Signed-off-by: Jeffrey Wang <[email protected]>
Signed-off-by: Jeffrey Wang <[email protected]>

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

LGTM

…ure-fallback

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 31d8440. Configure here.

@jeffreywang88
jeffreywang88 merged commit f3e1ef4 into master Oct 1, 2026
6 checks passed
@jeffreywang88
jeffreywang88 deleted the ingress-router-failure-fallback branch October 1, 2026 19:38
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
ray-project#66339)

## Problem

HAProxy returns errors when an ingress router fails, even if serving
replicas remain healthy. This interrupts requests during router failures
or restarts.

## Solution

### Serve

**Always enable** fallback whenever an ingress request router is
configured. If the router cannot select a usable replica, HAProxy can
select an available serving replica using `random(1)`. For a pin-miss,
HAProxy first uses the head Serve proxy when it is healthy.

#### Selection Order
For an ingress router failure,

- **Master:** Try each ingress router → return 503. The head Serve proxy
is not tried.
- **This PR:** Try each ingress router → choose a healthy LLMServer
replica from local HAProxy’s list with `random(1)` → use the head Serve
proxy only if no local replica is healthy → fail if neither can serve
the request.

A pin-miss has a different order because a router did respond, but
selected a replica absent from local HAProxy’s list:

- **Master:** Try the head Serve proxy if configured → if HAProxy marks
it down, select a local replica using the backend’s balancing policy
(default `leastconn`). Without a configured head proxy, return 503.
- **This PR:** Try the head Serve proxy if configured → if it is
unavailable, randomly select a healthy local replica. With no head proxy
configured, select a healthy local replica directly.

### Serve LLM specifics

Fallback applies to all direct-streaming routing policies. Requests
served through fallback may not follow KV-aware or session routing.
Fallback metrics and warnings are emitted when
`RAY_SERVE_INGRESS_REQUEST_ROUTER_METRICS_ENABLED=1`.

## Validation

- HAProxy tests cover router failures, recovery, `random(1)`
configuration, and YAML deployment.
- Metrics tests cover fallback reasons and warning rate limiting.
- A direct-streaming test kills an ingress-router replica and verifies
that streaming and non-streaming requests continue to succeed.

### Metrics validation
<details>
<summary>Validation and metrics repro</summary>

Validated with real HAProxy:

- Router failures return HTTP 503 without the fallback change and
succeed with it.
- Killing an ingress-router replica preserves streaming and
non-streaming requests; routing resumes through its replacement.
- Leastconn selects an idle replica while another replica has an active
request.
- Five successful fallback requests increased the exported fallback
counter.

### Repro

Save as `fallback_metrics.py` and run with this branch installed. The
ingress router returns 503, while the serving replica returns `"ok"`.

```python
import os
import time

os.environ["RAY_SERVE_ENABLE_HA_PROXY"] = "1"
os.environ["RAY_SERVE_INGRESS_REQUEST_ROUTER_METRICS_ENABLED"] = "1"

import ray
import requests
from fastapi import FastAPI, Response
from ray import serve

router_app = FastAPI()


@serve.deployment(request_router_config={"ingress_router_fallback": True})
class Ingress:
    async def __call__(self):
        return "ok"


@serve.deployment
@serve.ingress(router_app)
class FailingRouter:
    @router_app.post("/internal/route")
    async def route(self):
        return Response(status_code=503)


ray.init(
    address="local",
    num_cpus=2,
    include_dashboard=False,
    _metrics_export_port=18080,
    _system_config={"metrics_report_interval_ms": 100},
)
try:
    serve.run(
        Ingress.bind()._with_ingress_request_router(FailingRouter.bind()),
        name="fallback-demo",
    )

    # Wait for HAProxy to discover the router and export a fallback sample.
    for _ in range(60):
        response = requests.post("http://localhost:8000/", timeout=10)
        assert response.status_code == 200, response.text
        assert response.text == "ok"

        metrics = requests.get("http://localhost:18080/metrics", timeout=10).text
        samples = [
            line for line in metrics.splitlines()
            if line.startswith("ray_serve_haproxy_ingress_router_fallbacks_total{")
            and 'application="fallback-demo"' in line
            and 'reason="router_non_200"' in line
            and float(line.rsplit(" ", 1)[1]) > 0
        ]
        if samples:
            print("\n".join(samples))
            break
        time.sleep(1)
    else:
        raise RuntimeError("Fallback metric did not appear")

    input("Ready for queries below. Press Enter to shut down this repro.")
finally:
    serve.shutdown()
    ray.shutdown()
```

```bash
python fallback_metrics.py
```

### Query the exported counter

In another terminal:

```bash
curl -fsS localhost:18080/metrics |
  grep '^ray_serve_haproxy_ingress_router_fallbacks_total'
```

The sample should include `application="fallback-demo"` and
`reason="router_non_200"`.

Send five more requests:

```bash
for i in 1 2 3 4 5; do
  curl -fsS -X POST localhost:8000/ -w ' HTTP %{http_code}\n'
done
```

All five should return `ok HTTP 200`. After metrics export catches up,
querying the counter again should show an increase of five.

### PromQL

Once Prometheus scrapes the Ray metrics endpoint on port `18080`:

```promql
sum by (application, reason) (
  ray_serve_haproxy_ingress_router_fallbacks_total{application="fallback-demo"}
)
```

</details>

## Related issues
> Link related issues: "Fixes ray-project#1234", "Closes ray-project#1234", or "Related to
ray-project#1234".

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

---------

Signed-off-by: Jeffrey Wang <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
sai-miduthuri pushed a commit that referenced this pull request Oct 16, 2026
…rcent` for start-before-stop rolling updates (#66267) (#67094)

Cherry-pick of #66267 (master commit
9491664) onto `releases/2.60.0`.

## Why

The first three PRs of the in-place-updates series (#66252, #66290,
#66266) are already on `releases/2.60.0`. This picks the fourth, which
adds `max_surge_percent` for start-before-stop rolling updates, so
2.60.0 ships the complete series.

## Cherry-pick details

`git cherry-pick -x` conflicted in one file,
`python/ray/serve/tests/unit/test_deployment_state.py`. The conflict was
positional only: on master, #66243 (push-based replica health) had
appended `TestPushedHealthEndToEnd` and related tests to the end of that
file, and #66267 inserts `TestMaxSurge` right before them. This branch
doesn't have #66243, so git couldn't anchor the hunk and offered the
#66243 tests as part of the incoming side. Resolved by inserting only
the PR's `TestMaxSurge` block (plus its `defaultdict` import) before the
`__main__` guard. The added and removed lines in each of the 17 files
are identical to the master commit's diff.

After the pick, 11 of the 17 files are byte-identical to master at
9491664. The other 6 differ only by master commits that aren't on
this branch and that #66267 doesn't depend on:

- `_private/deployment_state.py`, `tests/unit/test_deployment_state.py`:
#66243.
- `schema.py`, `tests/BUILD.bazel`, `tests/test_controller.py`,
`tests/test_direct_ingress.py`: #66339 and #66940.

No commit on `releases/2.60.0` after the branch cut touched any of these
files.

Not a duplicate: no PR against `releases/2.60.0` references #66267.

## Testing

Run on this branch with the Serve protobuf regenerated from the branch's
`serve.proto` (the pick adds the `max_surge_percent` field).

```
python -m pytest python/ray/serve/tests/unit/test_deployment_state.py python/ray/serve/tests/unit/test_config.py python/ray/serve/tests/unit/test_deployment_class.py python/ray/serve/tests/unit/test_schema.py
3530 passed, 12 skipped
```

```
python -m pytest python/ray/serve/tests/test_deploy_app_3.py python/ray/serve/tests/test_deploy_app_2.py -k surge
13 passed, 41 deselected in 282s
```

`pre-commit run --files <changed files>` passed.

AI assistance was used to prepare this cherry-pick.

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

Signed-off-by: Qisheng He <[email protected]>
Signed-off-by: qishengxhe <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ray fails to serialize self-reference objects

3 participants