Skip to content

[Serve][3/5] Route HAProxy requests to deployment-specific replicas - #66258

Closed
celinaky wants to merge 31 commits into
celina/direct-http-target-groupsfrom
celina/direct-http-haproxy-routing
Closed

celinaky wants to merge 31 commits into
celina/direct-http-target-groupsfrom
celina/direct-http-haproxy-routing

Conversation

@celinaky

@celinaky celinaky commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Why this is needed

The previous PR publishes _direct_http replicas by deployment. This PR lets HAProxy route to those deployments: the router selects both a deployment and replica, and HAProxy pins the request accordingly.

Router contract

For eligible POST requests, HAProxy calls:

POST /internal/route
Content-Type: application/json

{ ...original request body... }

The router returns:

{
  "deployment": "LLMServer:model-a",
  "replica_id": "<actor name>"
}

Request-body forwarding remains controlled by RAY_SERVE_INGRESS_REQUEST_ROUTER_FORWARD_BODY.

Router errors, timeouts, unknown deployments, and direct-deployment replica misses fail closed with 503. An ingress replica miss may recover through the preexisting fallback Serve proxy.

HAProxy routing changes

The frontend now dispatches using the deployment backend selected by Lua.

For every _direct_http deployment:

use_backend <direct-backend> \
    if is_<app-backend> \
       { var(txn.selected_deployment_backend) -m str "<direct-backend>" }

Ingress selections continue to use the existing companion backend, identified through the same variable:

use_backend <app-backend>-via-ingress-request-router \
    if is_<app-backend> \
       { var(txn.selected_deployment_backend) -m str "<app-backend>-via-ingress-request-router" }

Each _direct_http deployment gets a separate backend containing only that deployment’s replicas:

backend <direct-backend>
    use-server <server> \
        if { var(txn.selected_replica_server) -m str "<server>" }

    server <server> <host>:<port>

These backends own their health checks. The existing ingress companion backend continues to mirror health from the application backend.

Lua changes

The replica lookup changes from:

application → replica_id → server

to:

application → deployment → {
backend,
replica_id → server
}

For example:

REPLICA_TARGETS["<app>"]["LLMServer:model-a"] = {
    b = "<direct-backend>",
    r = {
        ["<replica-id>"] = "<server-name>",
    },
}

Lua now reads both fields returned by /internal/route:

{
  "deployment": "LLMServer:model-a",
  "replica_id": "<actor name>"
}

It resolves the deployment first and sets txn.selected_deployment_backend. It then resolves the replica within that deployment and sets txn.selected_replica_server.

Config shape

DirectTargetConfig(
    deployment_name=...,
    name=...,
    servers=[...],
)

BackendConfig(
    ...,
    direct_target_configs=[DirectTargetConfig(...), ...],
)

Test plan

  • Unit coverage for backend generation, Lua lookup rendering, routing failures, readiness, and statistics
  • git diff --check
  • Repo commit hooks and linters on commit
  • Targeted HAProxy config/integration tests

To Do

  • Was not able to review the test files, they make up the bulk of the lines changed.

Example usage

This PR adds DirectTargetConfig and BackendConfig.direct_target_configs. It also extends the ingress-router response with deployment, so HAProxy resolves the (deployment, replica_id) pair to an isolated backend and server:

from ray.serve._private.haproxy import (
    BackendConfig,
    DirectTargetConfig,
    ServerConfig,
)

backend = BackendConfig(
    name="llm",
    path_prefix="/",
    direct_target_configs=[
        DirectTargetConfig(
            deployment_name="LLMServer:model-a",
            name="llm-direct-0",
            servers=[
                ServerConfig(
                    name="model-a-replica",
                    host="10.0.0.2",
                    port=30010,
                    replica_id="replica-a",
                )
            ],
        )
    ],
)

# Returned by POST /internal/route.
route_decision = {
    "host": "10.0.0.2",
    "port": 30010,
    "deployment": "LLMServer:model-a",
    "replica_id": "replica-a",
}

deployment = backend.get_deployment_targets()[route_decision["deployment"]]
assert deployment.backend_name == "llm-direct-0"
assert deployment.replicas[route_decision["replica_id"]] == "model-a-replica"

Each direct deployment gets its own backend, so retries cannot cross model boundaries.

@celinaky
celinaky added this pull request to stack #66257 September 17, 2026 23:40
@celinaky
celinaky force-pushed the celina/direct-http-haproxy-routing branch from 84f1da9 to 77ffd00 Compare September 18, 2026 22:07
celinaky and others added 28 commits September 19, 2026 04:53
Signed-off-by: Celina Yang <[email protected]>
… router

HAProxyManager.serving() added every direct_http_targets backend to the set it
waits to see UP, but the template rendered direct backend stanzas only when the
app has an ingress request router. A desired backend HAProxy never reports never
becomes ready, so any _direct_http app without a router (e.g. the _direct_http
integration tests) wedged the node's proxy with "Proxies not available".

A direct backend is reachable only through the router's dispatch variable, so
without a router there is nothing to render. Make the three sites agree:
_create_backend_config builds direct_target_configs only when the app has router
servers; serving() takes its desired set from _desired_backend_servers(), which
applies the same gate; the backend stanza guard is per-backend like the
frontend's use_backend guard. Pinned by
test_direct_backends_require_an_ingress_request_router.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
…t, including ingress. Temp removing pin-miss recovery for ingress, should follow up on how to keep that in the future

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]>
…end_config() as a single source of truth.

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]>
…ext PR. Clean up inline comments.

Signed-off-by: Celina Yang <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
@celinaky
celinaky force-pushed the celina/direct-http-haproxy-routing branch from 41b3217 to d6b0818 Compare September 19, 2026 05:13
- Merge the two 'nothing for the router to select' tests into one
  parametrized test and the ingress-selection e2e into the direct-http e2e.
- Drop assertions that restate template/Lua source text or duplicate a
  neighbouring test (recoverability config text, per-row count checks,
  health ACLs, own-endpoint short-circuit asserted twice).
- Reduce the serving()/direct-backend test to its one invariant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Celina Yang <[email protected]>
@eicherseiji eicherseiji added the go add ONLY when ready to merge, run all tests label Sep 22, 2026
eicherseiji added a commit that referenced this pull request Sep 22, 2026
## Why

The current 256 KiB cap truncates the router copy of large LLM requests,
causing body-aware routing to lose information. Several recent routing
changes depend on this body:

- [#64224](#64224),
[#64328](#64328), and
[#65095](#65095) use it for
KV-aware routing.
- [#65680](#65680) uses it for
LoRA model selection.
- [#66258](#66258) and
[#66315](#66315) use it for
deployment-aware, multi-model direct streaming.
- [#63183](#63183) introduced the
body-forwarding gate shared by these paths.

This PR raises the default buffer to 8 MiB and lowers the default
`maxconn` to 4,096. The sizing and behavior were verified with a real
HAProxy 2.8.25 test and against the bundled HAProxy source code. Both
settings retain their existing environment-variable overrides.

| Consideration | Result |
|---|---|
| Request size | A one-million-token English request is commonly
estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves
2.28 MiB (~40%) headroom. |
| Latency | Requests below 256 KiB do not wait longer. Requests from 256
KiB to 8 MiB now wait for the complete body before routing. |
| Memory | Buffers are allocated dynamically. A live stream can use
roughly 16 MiB across request and response buffers. Lowering `maxconn`
from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB
to 64 GiB. |

## Changes

- Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB
to 8 MiB.
- Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096.
- Test a 6,000,014-byte, million-token-sized request end to end.
- Derive rendered-config assertions from their constants so environment
overrides remain testable.
- Update the KV-aware routing guide.

## Tests

- Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly
passed.
- HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using
bundled HAProxy 2.8.25.

This does not duplicate the related PRs: they introduce or consume
body-aware routing, while this PR increases the shared buffer default
and tests a million-token-sized body.

AI assistance was used to implement and validate this change; the
submitter reviewed every changed line.

---------

Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
@eicherseiji

Copy link
Copy Markdown
Contributor

cursor review

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

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 2fb2bfe. Configure here.

@eicherseiji

Copy link
Copy Markdown
Contributor

/gemini review

@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 updates the LLMRouter and HAProxy configuration to support routing to non-ingress direct-HTTP deployments. It introduces isolated HAProxy backends for each direct-HTTP deployment to prevent cross-model request pollution during retries, and updates the Lua routing logic to extract both deployment and replica ID from the router's response. Feedback includes a recommendation to truncate the deployment name portion before appending the unique digest in _generate_direct_backend_name to prevent name collisions if the name is extremely long, and a suggestion to explicitly collect bc.name from self.backend_configs.values() for robustness.

Comment on lines +2183 to +2187
# Hash the raw name because distinct names can sanitize to the same value.
digest = hashlib.sha1(deployment_name.encode()).hexdigest()[:12]
return self.get_safe_name(
f"{app_backend_name}-direct-{deployment_name}-{digest}"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

If deployment_name is extremely long, the generated backend name might exceed HAProxy's name limits or get truncated by get_safe_name. If truncation occurs at the end, the unique digest suffix will be lost, potentially leading to duplicate backend name collisions for different deployments that share a long prefix. Truncating the deployment name portion to a safe length before appending the digest ensures uniqueness is always preserved.

        digest = hashlib.sha1(deployment_name.encode()).hexdigest()[:12]\n        max_dep_len = max(10, 63 - len(app_backend_name) - len(\"-direct--\") - len(digest))\n        safe_dep_name = deployment_name[:max_dep_len]\n        return self.get_safe_name(\n            f\"{app_backend_name}-direct-{safe_dep_name}-{digest}\"\n        )


def _configured_backend_names(self) -> Set[str]:
"""Every backend name this config renders, including direct-HTTP backends."""
names = set(self.backend_configs)

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

Using set(self.backend_configs) relies on the dictionary keys matching the actual rendered backend names (bc.name). To make this more robust and less prone to future refactoring bugs, it is safer to explicitly collect the name attribute from the BackendConfig objects.

Suggested change
names = set(self.backend_configs)
names = {bc.name for bc in self.backend_configs.values() if bc.name}

owenowenisme pushed a commit to owenowenisme/ray that referenced this pull request Sep 23, 2026
…t#66360)

## Why

The current 256 KiB cap truncates the router copy of large LLM requests,
causing body-aware routing to lose information. Several recent routing
changes depend on this body:

- [ray-project#64224](ray-project#64224),
[ray-project#64328](ray-project#64328), and
[ray-project#65095](ray-project#65095) use it for
KV-aware routing.
- [ray-project#65680](ray-project#65680) uses it for
LoRA model selection.
- [ray-project#66258](ray-project#66258) and
[ray-project#66315](ray-project#66315) use it for
deployment-aware, multi-model direct streaming.
- [ray-project#63183](ray-project#63183) introduced the
body-forwarding gate shared by these paths.

This PR raises the default buffer to 8 MiB and lowers the default
`maxconn` to 4,096. The sizing and behavior were verified with a real
HAProxy 2.8.25 test and against the bundled HAProxy source code. Both
settings retain their existing environment-variable overrides.

| Consideration | Result |
|---|---|
| Request size | A one-million-token English request is commonly
estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves
2.28 MiB (~40%) headroom. |
| Latency | Requests below 256 KiB do not wait longer. Requests from 256
KiB to 8 MiB now wait for the complete body before routing. |
| Memory | Buffers are allocated dynamically. A live stream can use
roughly 16 MiB across request and response buffers. Lowering `maxconn`
from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB
to 64 GiB. |

## Changes

- Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB
to 8 MiB.
- Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096.
- Test a 6,000,014-byte, million-token-sized request end to end.
- Derive rendered-config assertions from their constants so environment
overrides remain testable.
- Update the KV-aware routing guide.

## Tests

- Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly
passed.
- HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using
bundled HAProxy 2.8.25.

This does not duplicate the related PRs: they introduce or consume
body-aware routing, while this PR increases the shared buffer default
and tests a million-token-sized body.

AI assistance was used to implement and validate this change; the
submitter reviewed every changed line.

---------

Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
…t#66360)

## Why

The current 256 KiB cap truncates the router copy of large LLM requests,
causing body-aware routing to lose information. Several recent routing
changes depend on this body:

- [ray-project#64224](ray-project#64224),
[ray-project#64328](ray-project#64328), and
[ray-project#65095](ray-project#65095) use it for
KV-aware routing.
- [ray-project#65680](ray-project#65680) uses it for
LoRA model selection.
- [ray-project#66258](ray-project#66258) and
[ray-project#66315](ray-project#66315) use it for
deployment-aware, multi-model direct streaming.
- [ray-project#63183](ray-project#63183) introduced the
body-forwarding gate shared by these paths.

This PR raises the default buffer to 8 MiB and lowers the default
`maxconn` to 4,096. The sizing and behavior were verified with a real
HAProxy 2.8.25 test and against the bundled HAProxy source code. Both
settings retain their existing environment-variable overrides.

| Consideration | Result |
|---|---|
| Request size | A one-million-token English request is commonly
estimated at roughly 4 MB. The test request is 5.72 MiB, so 8 MiB leaves
2.28 MiB (~40%) headroom. |
| Latency | Requests below 256 KiB do not wait longer. Requests from 256
KiB to 8 MiB now wait for the complete body before routing. |
| Memory | Buffers are allocated dynamically. A live stream can use
roughly 16 MiB across request and response buffers. Lowering `maxconn`
from 20,000 to 4,096 reduces the theoretical buffer ceiling from 320 GiB
to 64 GiB. |

## Changes

- Raise `RAY_SERVE_HAPROXY_INGRESS_REQUEST_ROUTER_BUFSIZE` from 256 KiB
to 8 MiB.
- Lower `RAY_SERVE_HAPROXY_MAXCONN` from 20,000 to 4,096.
- Test a 6,000,014-byte, million-token-sized request end to end.
- Derive rendered-config assertions from their constants so environment
overrides remain testable.
- Update the KV-aware routing guide.

## Tests

- Pre-commit hooks, Python compilation, Serve mypy, and Serve pyrefly
passed.
- HAProxy end-to-end test passed: 1 passed, 37 deselected in 2.85s using
bundled HAProxy 2.8.25.

This does not duplicate the related PRs: they introduce or consume
body-aware routing, while this PR increases the shared buffer default
and tests a million-token-sized body.

AI assistance was used to implement and validate this change; the
submitter reviewed every changed line.

---------

Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
@github-actions

github-actions Bot commented Oct 7, 2026

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 7, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically closed because there has been no more activity in the 14 days
since being marked stale.

Please feel free to reopen or open a new pull request if you'd still like this to be addressed.

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

Thanks again for your contribution!

@github-actions github-actions Bot closed this Oct 22, 2026
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 stale The issue is stale. It will be closed within 7 days unless there are further conversation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants