Repository navigation
[Serve][2/5] Dispatch router decisions and direct responses in HAProxy - #66507
Conversation
f478204 to
6becfba
Compare
Add an internal, application-wide role, `Application._as_router_application()`, for applications whose ingress chooses which replica of which other application serves a request. HAProxy will consume the role in a follow-up; this change only carries it from the application to the target group. The role marks the application's existing ingress. No router deployment is added. It flows through BuiltApplication, DeploymentArgs and DeploymentInfo (new `router_application` proto fields), ApplicationState, and the HTTP TargetGroup (`is_router_application`). gRPC target groups never carry it. The marker is read from the target state rather than running replicas, so a router application scaled to zero keeps it. Otherwise HAProxy would stop treating the application as a router and return its routing decisions to clients as responses. Validation: - requires HAProxy; - cannot be combined with `_with_ingress_request_router()`: both choose the replica for requests to the application; - requires a route prefix, checked for `serve.run` in the client and for config deploys after route-prefix overrides. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Celina Yang <[email protected]>
…oups Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Celina Yang <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Celina Yang <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
…HAProxy
When a request's longest-prefix match is a router application, HAProxy holds
it and sends a copy (method, path, query, body, content type, request ID,
session header) to one of the router's ingress replicas. A 200
{"application", "replica_id"} is validated against controller-provided
ingress targets; HAProxy then replaces the router's route prefix with the
target application's and pins the original request to that replica:
/v1/chat/completions -> /v1/model-a/v1/chat/completions
/v1/models -> /v1/control/v1/models
Router non-2xx responses are returned to the client. Everything else that
does not select a live replica returns 503 with X-Serve-Reason:
router_unavailable, router_unreachable, router_timeout, malformed_decision,
unknown_application, unknown_replica_id, replica_unavailable. A routed
request never runs the target application's ingress request router, and a
stale decision is not retried through it. Host/port in the decision are
ignored. With the router scaled to zero, HAProxy asks the fallback proxy.
Direct requests to non-router applications are unchanged.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
json.dumps renders non-ASCII as \uXXXX, which Lua 5.4 rejects, so an application or deployment name with such characters made HAProxy fail to load router_application.lua. Emit \ddd byte escapes instead, and cover it with a haproxy -c test. Also clarify the tune.bufsize comment and drop an unused test variable. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
6becfba to
531a2b4
Compare
…-1-serve-role Signed-off-by: Celina Yang <[email protected]>
…2-haproxy-dispatch Signed-off-by: Celina Yang <[email protected]>
Replace Application._as_router_application() with a private class decorator. Being a router application depends on what the class returns, so the marker lives on the class (like @serve.multiplexed) and build_app reads it from the ingress. The wire format is unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Signed-off-by: Celina Yang <[email protected]>
…2-haproxy-dispatch Signed-off-by: Celina Yang <[email protected]>
Keep original method metadata scoped to router applications and combine overlapping HAProxy scenarios. Signed-off-by: Seiji Eicher <[email protected]>
Dechunk marked direct responses and router errors inside reply_with while keeping routing decisions on the existing non-streaming JSON path. Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]> # Conflicts: # python/ray/serve/_private/build_app.py # python/ray/serve/tests/unit/test_application_state.py
…2-haproxy-dispatch Signed-off-by: Seiji Eicher <[email protected]> # Conflicts: # python/ray/serve/_private/haproxy.py # python/ray/serve/_private/haproxy_templates.py # python/ray/serve/_private/ingress_request_router.lua.tmpl
| continue | ||
| servers = sorted(backend.servers, key=lambda s: (s.host, s.port)) | ||
| colocated = [s for s in servers if s.host == local_host] | ||
| pool = colocated or servers |
There was a problem hiding this comment.
Consider this situation:
- Node A runs HAProxy and router replica R1.
- Node B runs router replica R2.
- Both routers can select healthy model replicas.
HAProxy on A prefers local R1 and excludes R2 from its candidate list. If R1 crashes, requests through A return 503, even though R2 could handle them. This lasts until the controller updates HAProxy’s configuration. Router replica refers to a replica of the ingress deployment inside a router application.
Can we evaluate keeping remote router replicas as fallback candidates?
There was a problem hiding this comment.
Good catch. I’m keeping colocated replicas as the primary round-robin pool and will only try remote replicas after all local connection attempts fail. The first version flattened both sets, which could periodically select a remote replica first, so I’m correcting that before resolving this thread.
| if not sock:connect(server.host, server.port) then | ||
| return nil, "router_unreachable" | ||
| end | ||
| local req = "POST /internal/route HTTP/1.0\r\n" |
There was a problem hiding this comment.
There are some rough edges regarding route_prefix. Consider this example:
- You deploy the router with
route_prefix="/llm". - A client sends
POST /llm/v1/chat/completions. - HAProxy recognizes the router application and asks its ingress replica for a routing decision.
- That internal request goes to
/internal/route. - The replica expects requests under
/llm, so it returns 404 before the router’s handler runs.
The control request should use /llm/internal/route; FastAPI then sees /internal/route after accounting for the application prefix. Let's add some tests with specified route_prefix.
There was a problem hiding this comment.
Fixed in 8587cfd. The control request now uses <route_prefix>/internal/route, while ingress request routers retain /internal/route. I also changed the real Serve E2E to deploy the router under /llm and verified requests reach POST /llm/internal/route.
| assert f"::{model}#Backend#" in body["replica_id"] | ||
| served[f"req-{i}"] = body["replica_id"] | ||
| # Round-robin over two replicas per model: all four replicas served. | ||
| assert len(set(served.values())) == 4 |
There was a problem hiding this comment.
handle.choose_replica(_reserve=False) uses the default power-of-two router, whose candidate order is randomized, not round-robin. Four requests per model can legitimately miss one replica, so correct dispatch fails the test.
There was a problem hiding this comment.
Fixed in 8587cfd. I removed the assertion that all four replicas must be selected. The test still verifies that every request reaches the exact replica returned by the router decision.
| async def test_scaled_to_zero_router(with_fallback): | ||
| """With no router replicas HAProxy asks the fallback proxy, else 503s.""" | ||
| async with _router_cluster( | ||
| router_scaled_to_zero=True, router_fallback=with_fallback |
There was a problem hiding this comment.
Could we exercise scale-from-zero with a real serve proxy? Here the fallback points straight at FakeRouter, so the test doesn't cover proxy route matching or waking a router deployment with no replicas.
There was a problem hiding this comment.
Agreed. The current test verifies the generated HAProxy behavior but bypasses the real Serve proxy. The scale-from-zero E2E in PR4 #67087 covers a target model application, not the router deployment itself. I’ll add real proxy coverage for waking a router application from zero before resolving this thread.
Signed-off-by: Seiji Eicher <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
❌ 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 8587cfd. Configure here.
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]> # Conflicts: # python/ray/serve/api.py
## Why this is needed
Multi-model direct streaming deploys each model as an independent Serve
application. This PR adds a lightweight shared OpenAI router application
that maps the model ID in each request to one of those applications,
then asks the request router for the target application to select a
replica. HAProxy sends the original request directly to that replica,
preserving the direct streaming data path.
## Usage
```python
from ray.llm._internal.serve.core.ingress.builder import build_openai_router_app
build_openai_router_app(
{
"model_applications": {
"qwen-0.5b": "llm-model-qwen",
"llama-8b": "llm-model-llama",
},
"llm_configs": [
{"model_loading_config": {"model_id": "qwen-0.5b"}},
{"model_loading_config": {"model_id": "llama-8b"}},
],
}
)
```
The builder is private, requires HAProxy and LLM direct streaming, and
accepts the same dictionary through declarative YAML. It requires
exactly one `LLMConfig` for every model-to-application mapping. Updating
this router does not replace or delete the independently deployed model
applications.
## Design
`RouterApplication` implements the private `POST /internal/route`
protocol introduced in #66507. It reads the model from JSON or form
data, resolves and caches the target application handle, and passes the
routing payload and session ID to the request router for that
application. The response contains the target application name and full
replica ID for HAProxy to validate and dispatch.
Native model routes are delegated without maintaining a duplicate
allowlist. The router itself owns only the global model endpoints: `GET`
and `HEAD /v1/models` and `/v1/models/{model}`. These endpoints do not
wake scale-to-zero model applications. They enforce each target model
API key policy, expose only authorized or public models, and return
vLLM-compatible errors. CORS preflight is handled before model
extraction.
Handle lookup runs in background tasks and retries transient Serve and
Ray failures. Lookup and replica selection remain bounded by the HAProxy
decision deadline. Client errors, unavailable applications, and
router-owned responses use the marked response path from #66507.
This layer uses a fast non-reserving pick and therefore requires an
available target replica. #67087 adds bounded reserving selection for
scale-to-zero targets, and #67218 preserves `KVAwareRouter` behavior in
the shared router process.
## Test plan
- `test_router_application.py` covers model parsing, authentication,
handle lookup, selection, session affinity, errors, and timeouts.
- `test_builder_openai_router_app.py` covers builder validation,
declarative arguments, and router-role propagation.
- `test_openai_router_app_direct_streaming.py` covers the end-to-end
multi-application path and native OpenAI routes.
- Pinned Black 22.10.0 and pre-commit checks on changed files.
Signed-off-by: Seiji Eicher <[email protected]>
Co-authored-by: Seiji Eicher <[email protected]>

Why this is needed
PR #66506 marks router applications and publishes that role to HAProxy. This PR implements the private HAProxy protocol that lets a router application choose a replica in another Serve application while preserving the direct model-to-client streaming path.
Summary
For a request whose longest-prefix match is a router application, HAProxy:
POST /internal/routecontrol request to a router replica. The control request carries the original method, prefix-stripped path and query, selected headers including Authorization, request ID, session ID, and buffered body.A routing decision has this private shape:
{"application": "llm-model-qwen", "replica_id": "SERVE_REPLICA::..."}A router-owned response contains
X-Serve-Router-Direct-Response: 1. HAProxy strips that private marker and hop-by-hop headers while preserving end-to-end headers, status, and body. Chunked router responses are decoded before forwarding or parsing. Unmarked non-2xx responses are returned as errors.Decision parsing supports escaped JSON strings and rejects unknown applications, unknown replicas, malformed decisions, unavailable replicas, and router failures with a fail-closed
503. Ordinary applications and the existing ingress request router path retain their previous behavior.Test plan
RAY_SERVE_ENABLE_HA_PROXY=1 python -m pytest -q python/ray/serve/tests/test_haproxy_router_application.py