Skip to content

[Serve] Enable HAProxy by default on Linux - #66432

Closed
eicherseiji wants to merge 9 commits into
ray-project:masterfrom
eicherseiji:seiji/serve-default-swaps
Closed

eicherseiji wants to merge 9 commits into
ray-project:masterfrom
eicherseiji:seiji/serve-default-swaps

Conversation

@eicherseiji

@eicherseiji eicherseiji commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Description

Enable HAProxy by default on Linux. macOS and Windows continue to use the Python HTTP/gRPC proxy by default because HAProxy mode is Linux-only. RAY_SERVE_ENABLE_HA_PROXY=0 remains available as the Linux opt-out.

Environment variable master on Linux After this PR on Linux
RAY_SERVE_ENABLE_HA_PROXY OFF ON

The HAProxy documentation now calls out the Linux-only support boundary and the unchanged macOS and Windows behavior.

HAProxy subprocesses use Ray's Linux parent-death mechanism so an abrupt manager-worker shutdown, including ray stop --force, cannot leave listeners bound after the Ray cluster exits. Serve test targets that repeatedly replace applications also use a short direct-ingress draining period so production deregistration delays do not consume their Bazel timeouts.

The fake multi-node autoscaling tests now run as explicit HAProxy and Python-proxy variants under both default and pack scheduling. Their logical Ray nodes share one host, so the tests use head-only proxy placement. The HAProxy variant therefore owns one listener while replicas still span the simulated worker nodes.

Code-defined deployments already accept any JSON-serializable user_config. DeploymentSchema now matches that API so HAProxy target-group refreshes can inspect deployments with non-dictionary configs without disrupting the controller loop.

Compatibility fallback

This PR adds one narrow compatibility check before the Serve controller starts: when both HTTPOptions.ssl_keyfile and HTTPOptions.ssl_certfile are configured, Serve selects the Python proxy instead of HAProxy. The fallback preserves other controller runtime-environment variables and an explicitly configured HTTP host; when the host was implicit, it restores the normal Python-proxy bind host. Plain HTTP applications still use HAProxy by default.

This is deliberately a temporary, removable layer rather than a permanent public compatibility matrix. It has no new user-facing mode or configuration API. Once HAProxy can terminate configured Serve TLS, the helper, its unit tests, and the documentation exception can be deleted together. custom_ingress_request_router is experimental and is not a default-on blocker here.

Model multiplexing dependency

Review and merge #66585 before this PR. It restores Serve's warm-model affinity for generic @serve.multiplexed ingress by adding a private ingress request router. The default-on commit stack includes it below this PR; after #66585 merges, GitHub will remove that lower commit from this PR's diff automatically.

Generic model multiplexing does not require reading the request body: its routing key is the serve_multiplexed_model_id header. Every request for an application with an ingress request router consults that router, independent of HTTP method. The router receives all end-to-end request headers; HAProxy filters only hop-by-hop and internal framing fields and streams the original request directly to the selected replica.

The private model-mux router uses the header with Serve's existing model-aware selection policy. OpenAI-compatible multi-model routing is different because its model name is in the JSON body and that path must inspect enough of the body to extract model.

A header hash entirely inside HAProxy would avoid the private router, but it would not preserve Serve's current semantics: it does not know which replicas have a model loaded, cannot place a cold model on the replica with the fewest loaded models, and cannot react correctly to LRU eviction or scaling. Publishing model state into HAProxy would require a separate dynamic-map/control-plane mechanism to avoid configuration reloads. #66585 reuses Serve's existing model-location propagation instead.

Related PRs

Stack and review order:

  1. #66585 Preserve model affinity for multiplexed HAProxy ingress
  2. This PR: enable HAProxy by default with the TLS compatibility fallback

These other default changes are independent and can merge in any order:

Tests

  • Added unit coverage for TLS fallback, controller environment preservation, explicit host preservation, and the unchanged plain-HTTP path.
  • Removed the HAProxy skips from the existing HTTPS and secure-WebSocket integration suites so CI exercises the real fallback with HAProxy enabled by default.
  • python/ray/serve/tests/unit/test_schema.py: 121 passed, including non-dictionary user_config conversion
  • python/ray/serve/tests/test_deploy.py::test_reconfigure_with_exception: 1 passed with HAProxy enabled; the controller loop remained healthy with user_config="hi"
  • Four previously failing deployment update, deletion, and autoscaling cases from test_deploy_app.py: 4 passed in 54.52s
  • Full HAProxy test_max_replicas_per_node.py target: 4 passed in 118.89s; the reproduced v2 redeployment case also passed in all four proxy/scheduling variants: HAProxy default (42.20s), Python proxy default (39.20s), HAProxy pack (30.19s), and Python proxy pack (39.18s)
  • doc/source/serve/doc_code/custom_request_router_app.py: completed all four examples under the Python proxy, exercising the deployment request router configured directly on the HTTP ingress
  • python/ray/llm/tests/batch/gpu/processor/test_serve_deployment_proc.py: 7 passed in 359.27s with Python 3.12.12, vLLM 0.29.0, and Torch 2.13.0+cu130
  • Five focused graceful and dependency-ordered shutdown cases: 5 passed across two runs
  • python/ray/serve/tests/test_haproxy_api.py::test_failed_spawn_retires_log_files: 1 passed
  • python/ray/serve/tests/test_runtime_env.py python/ray/serve/tests/test_runtime_env_2.py: 5 passed in 250.43s across repeated external Ray cluster restarts; no HAProxy processes or listeners remained afterward
  • python/ray/serve/tests/test_api.py python/ray/serve/tests/test_api_2.py python/ray/serve/tests/test_model_composition.py: 72 passed, 2 skipped in 290.08s with the same direct-ingress drain setting used by their Bazel targets
  • Focused pre-commit on the TLS compatibility changes and documentation passed, including Ruff, Black, mypy, Pyrefly, docs style, and import-order checks.
  • Focused pytest/Bazel execution for the new stack was attempted locally, but the available compiled Ray extension predates this checkout and cannot import the current source tree. CI execution is required before this draft is marked ready.

Duplicate search

I searched open Ray PRs for RAY_SERVE_ENABLE_HA_PROXY default changes and found no duplicate. For multiplexing, the merged #65678 and #65679 propagate model IDs and add multiplex support to RoundRobinRouter, but neither makes generic HAProxy ingress consult Serve's model-aware router.

AI assistance

AI assistance was used for implementation and testing. The generated changes and test results require submitter review before the PR is marked ready.

@eicherseiji
eicherseiji force-pushed the seiji/serve-default-swaps branch 2 times, most recently from e73b2d4 to 35f7e2a Compare September 23, 2026 21:57
@eicherseiji eicherseiji changed the title [Serve] Flip production-ready defaults [Serve] Enable HAProxy by default on Linux Sep 23, 2026
@eicherseiji
eicherseiji force-pushed the seiji/serve-default-swaps branch 2 times, most recently from 7a5d47b to ae47c1b Compare September 24, 2026 01:03
@eicherseiji eicherseiji added the go add ONLY when ready to merge, run all tests label Sep 24, 2026
@eicherseiji
eicherseiji force-pushed the seiji/serve-default-swaps branch 4 times, most recently from 3010b78 to ff7953a Compare September 24, 2026 18:46
eicherseiji added a commit that referenced this pull request Sep 29, 2026
## Description

Run synchronous deployment methods in a thread pool by default so
blocking synchronous I/O does not block the replica event loop.
`RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0` retains the legacy behavior for
deployments whose shared state is not thread-safe.

| Environment variable | `master` | After this PR |
| --- | --- | --- |
| `RAY_SERVE_RUN_SYNC_IN_THREADPOOL` | OFF | ON |

The opt-in warning has been emitted since
[#48897](#48897) merged on
November 26, 2024—667 days (about 22 months) before this default swap.
This provided an extended migration period for users to make synchronous
deployment code thread-safe or convert it to `async def`.

The documentation now describes thread safety requirements and the
opt-out. This default was previously enabled in
[#61229](#61229) and reverted in
[#61369](#61369).

## Related PRs

These default changes are independent and can merge in any order:

- [#66432 Enable HAProxy by default on
Linux](#66432)
- [#66434 Select request body forwarding by
router](#66434)
- [#66435 Apply Serve LLM replica performance
defaults](#66435)

## Tests

- `RAY_USE_UVLOOP=0 python -m pytest -q
python/ray/serve/tests/test_replica_sync_methods.py`: 9 passed. The
executor-introspection cases target the standard asyncio loop used by
this Bazel test.
- Updated the thread-pool test target description
- Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs
style, and import-order checks

## Duplicate search

I searched open Ray PRs for this environment variable and found no
active duplicate.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

Signed-off-by: Seiji Eicher <[email protected]>
@eicherseiji
eicherseiji force-pushed the seiji/serve-default-swaps branch from dafc0ed to 53bff1c Compare September 29, 2026 23:44
@eicherseiji
eicherseiji force-pushed the seiji/serve-default-swaps branch from 53bff1c to 39734a7 Compare September 30, 2026 00:22
@eicherseiji

Copy link
Copy Markdown
Contributor Author

Superseded by native stack #66591. The HAProxy default-on and TLS compatibility changes are now isolated in #66590.

eicherseiji added a commit that referenced this pull request Sep 30, 2026
## Description

Apply the performance-oriented replica defaults only to the default Ray
Serve LLM path. General Serve defaults remain unchanged.

| Serve LLM setting | `master` | After this PR |
| --- | --- | --- |
| OpenAI ingress model-handle transport | `ray.remote` | gRPC |
| `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` | ON | OFF |
| `RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` | ON | OFF |

The same-event-loop defaults are injected into `OpenAiIngress`, the
vLLM-backed `LLMServer`, and the direct LLM routers. Explicit
`runtime_env.env_vars` values take precedence.

Serve LLM's `OpenAiIngress` configures its model deployment handles with
`_by_reference=False`, selecting the gRPC transport directly at the
point where those handles are created. This avoids changing generic
Serve handle construction and does not add a Serve LLM opt-out.

gRPC transport was introduced in
[#59908](#59908). The
same-event-loop defaults were previously proposed globally in
[#62156](#62156); this PR limits
them to Serve LLM.

## Related PRs

These default changes are independent and can merge in any order:

- [#66432 Enable HAProxy by default on
Linux](#66432)
- [#66434 Select request body forwarding by
router](#66434)
- [#66436 Run sync deployment methods in a thread
pool](#66436)

## Tests

- The live GPU reproducer below completed a real OpenAI-compatible
request and observed only the consolidated `main` loop on both
production replicas
- Focused unit tests for LLMServer runtime env defaults and overrides,
OpenAI ingress gRPC handles, and router runtime env propagation: 5
passed in 4.22s
- The commit hooks passed Ruff, Black, pydoclint, docs style, import
order, and the other applicable repository checks

## Local performance benchmark

The short-request workload is intentionally framework-heavy while
retaining a real vLLM engine. Lower latency is better; higher throughput
is better.

```mermaid
---
config:
  themeCSS: |
    .plot path { stroke-width: 5px !important; stroke-linecap: round; }
    .legend .markers path { stroke-width: 10px !important; stroke-linecap: round; stroke-dasharray: 0 100; }
  themeVariables:
    xyChart:
      plotColorPalette: "#0072B2, #CC79A7, #009E73, #D55E00"
---
xychart-beta
    title "Effect of consolidating replica event loops"
    x-axis "Maximum concurrency" [64, 128, 256]
    y-axis "Requests per second" 0 --> 400
    line "This PR: shared main loop" [264.0, 355.9, 368.8]
    line "Separate user-code thread only" [246.4, 325.8, 318.6]
    line "Separate router loop only" [255.4, 318.4, 305.7]
    line "Current default: both separate" [244.1, 302.3, 272.9]
```

Compared with the previous loop defaults, the new defaults increased
throughput by 8%, 18%, and 35% at concurrency 64, 128, and 256,
respectively. Both individual settings contributed; their relative
impact varied with concurrency. The concurrency-256 values are the mean
of two runs; the other points are one run each.

The chart uses thick series lines and a dot legend with a
color-blind-friendly palette in this order: blue, purple, green, and
vermilion.

| Chart series | `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` |
`RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` |
| --- | ---: | ---: |
| This PR: shared main loop | `0` | `0` |
| Separate user-code thread only | `1` | `0` |
| Separate router loop only | `0` | `1` |
| Current default: both separate | `1` | `1` |

### Benchmark setup

| Item | Configuration |
| --- | --- |
| Hardware | NVIDIA A10G (23 GiB) |
| Software | Python 3.12, vLLM 0.29.0, Torch 2.13, HAProxy 2.8.25 |
| Model | `Qwen/Qwen3-0.6B` on one vLLM-backed `LLMServer` replica |
| Serve topology | One `OpenAiIngress` replica and one `LLMServer`
replica; HAProxy was enabled with `RAY_SERVE_ENABLE_HA_PROXY=1` and
received requests on port 8000; ingress-to-model handles used gRPC in
both cases |
| Workload | `vllm bench serve`, OpenAI completions endpoint, random
input 32 tokens and output 8 tokens with `--random-range-ratio 0.5`,
`--ignore-eos`, and `--temperature 0` |
| Load | Infinite offered request rate at maximum concurrency 64, 128,
and 256 |
| Samples | 256 warmup requests, then 2,048 measured requests per point;
deterministic seed `20260928`; 32,768 measured requests and zero
failures across all four configurations |
| Environment application | Each environment-variable combination was
applied to both `OpenAiIngress` and `LLMServer` before their replicas
started |

As a control, an engine-heavy workload (1,024-token random input,
128-token random output, concurrency 64) delivered approximately 12
requests/s under either setting. This indicates that the difference
above is in framework overhead and becomes hidden when model execution
dominates.

## Duplicate search

I searched open Ray PRs for each environment variable and found no
duplicate of this Serve LLM-scoped change.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

## Live GPU reproducer

The reproducer uses the Python 3.12 `ray[llm]` wheel built from this
branch's merge base, then symlinks only `ray/llm` to the checkout.
Serve, generated protobufs, and compiled extensions remain from the
matching wheel.

```bash
uv venv --python 3.12 /tmp/ray-66435-live-venv
uv pip install --python /tmp/ray-66435-live-venv/bin/python \
  "https://s3-us-west-2.amazonaws.com/ray-wheels/master/98d8084dbf690739ef2921c25918cd49aa1db556/ray-3.0.0.dev0-cp312-cp312-manylinux2014_x86_64.whl[llm]"

SITE=/tmp/ray-66435-live-venv/lib/python3.12/site-packages/ray
mv "$SITE/llm" "$SITE/llm-wheel"
ln -s "$PWD/python/ray/llm" "$SITE/llm"

RAY_USAGE_STATS_ENABLED=0 /tmp/ray-66435-live-venv/bin/python - <<'PY'
import json
import time

import openai
from prometheus_client.parser import text_string_to_metric_families
import requests

import ray
from ray import serve
from ray.serve.llm import LLMConfig, LLMServingArgs, ModelLoadingConfig, build_openai_app


MODEL = "Qwen/Qwen3-0.6B"
METRICS_URL = "http://127.0.0.1:9999/metrics"
METRIC = "ray_serve_event_loop_monitoring_iterations_total"


def replica_event_loops():
    response = requests.get(METRICS_URL, timeout=5)
    response.raise_for_status()
    samples = [
        sample
        for family in text_string_to_metric_families(response.text)
        for sample in family.samples
        if sample.name == METRIC
        and sample.labels.get("component") == "replica"
        and sample.labels.get("application") == "default"
    ]
    actor_to_deployment = {
        sample.labels["actor_id"]: sample.labels["deployment"]
        for sample in samples
        if sample.labels.get("loop_type") == "main"
        and (
            sample.labels["deployment"] == "OpenAiIngress"
            or sample.labels["deployment"].startswith("LLMServer:")
        )
    }
    return {
        deployment: sorted(
            {
                sample.labels["loop_type"]
                for sample in samples
                if sample.labels["actor_id"] == actor_id
            }
        )
        for actor_id, deployment in actor_to_deployment.items()
    }


try:
    ray.init(
        num_cpus=8,
        num_gpus=1,
        include_dashboard=False,
        _metrics_export_port=9999,
        _system_config={"metrics_report_interval_ms": 1000},
    )
    config = LLMConfig(
        model_loading_config=ModelLoadingConfig(model_id=MODEL, model_source=MODEL),
        engine_kwargs={
            "max_model_len": 1024,
            "gpu_memory_utilization": 0.5,
            "enforce_eager": True,
        },
        deployment_config={"num_replicas": 1},
    )
    serve.run(build_openai_app(LLMServingArgs(llm_configs=[config])))

    client = openai.OpenAI(
        base_url="http://127.0.0.1:8000/v1", api_key="test", timeout=60
    )
    completion = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "user", "content": "Reply with: loop test passed"}],
        max_tokens=8,
        temperature=0,
    )
    print("COMPLETION", completion.choices[0].message.content)

    deadline = time.time() + 90
    while time.time() < deadline:
        loops = replica_event_loops()
        if len(loops) == 2:
            break
        time.sleep(1)
    else:
        raise RuntimeError("Timed out waiting for replica event-loop metrics")

    # Check three later scrapes so a separate loop cannot be hidden by a
    # just-created metric that has not reached the exporter yet.
    for _ in range(3):
        time.sleep(2)
        loops = replica_event_loops()
        assert len(loops) == 2
        assert all(loop_types == ["main"] for loop_types in loops.values())

    print("REPLICA_EVENT_LOOPS", json.dumps(loops, sort_keys=True))
finally:
    serve.shutdown()
    ray.shutdown()
PY
```

The script builds the unmodified `build_openai_app` application, starts
its real `OpenAiIngress` and vLLM-backed `LLMServer` deployments, sends
an OpenAI-compatible completion request, and reads Serve's event-loop
heartbeat metrics for those replica actors.

Relevant output:

```text
Deployment Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

Ingress Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

HTTP Request: POST http://127.0.0.1:8000/v1/chat/completions "HTTP/1.1 200 OK"
COMPLETION <think>
Okay, the user wants me
REPLICA_EVENT_LOOPS {"LLMServer:Qwen--Qwen3-0_6B": ["main"], "OpenAiIngress": ["main"]}
```

The completion request initializes the ingress model handle before
metrics are checked. A separate user-code loop or handle-router loop
would emit `user_code` or `router` for the same replica actor. Both
production replicas emit only `main`, showing that the environment
settings take effect and consolidate those loops onto the replica event
loop.

---------

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

Run synchronous deployment methods in a thread pool by default so
blocking synchronous I/O does not block the replica event loop.
`RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0` retains the legacy behavior for
deployments whose shared state is not thread-safe.

| Environment variable | `master` | After this PR |
| --- | --- | --- |
| `RAY_SERVE_RUN_SYNC_IN_THREADPOOL` | OFF | ON |

The opt-in warning has been emitted since
[ray-project#48897](ray-project#48897) merged on
November 26, 2024—667 days (about 22 months) before this default swap.
This provided an extended migration period for users to make synchronous
deployment code thread-safe or convert it to `async def`.

The documentation now describes thread safety requirements and the
opt-out. This default was previously enabled in
[ray-project#61229](ray-project#61229) and reverted in
[ray-project#61369](ray-project#61369).

## Related PRs

These default changes are independent and can merge in any order:

- [ray-project#66432 Enable HAProxy by default on
Linux](ray-project#66432)
- [ray-project#66434 Select request body forwarding by
router](ray-project#66434)
- [ray-project#66435 Apply Serve LLM replica performance
defaults](ray-project#66435)

## Tests

- `RAY_USE_UVLOOP=0 python -m pytest -q
python/ray/serve/tests/test_replica_sync_methods.py`: 9 passed. The
executor-introspection cases target the standard asyncio loop used by
this Bazel test.
- Updated the thread-pool test target description
- Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs
style, and import-order checks

## Duplicate search

I searched open Ray PRs for this environment variable and found no
active duplicate.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

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

Apply the performance-oriented replica defaults only to the default Ray
Serve LLM path. General Serve defaults remain unchanged.

| Serve LLM setting | `master` | After this PR |
| --- | --- | --- |
| OpenAI ingress model-handle transport | `ray.remote` | gRPC |
| `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` | ON | OFF |
| `RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` | ON | OFF |

The same-event-loop defaults are injected into `OpenAiIngress`, the
vLLM-backed `LLMServer`, and the direct LLM routers. Explicit
`runtime_env.env_vars` values take precedence.

Serve LLM's `OpenAiIngress` configures its model deployment handles with
`_by_reference=False`, selecting the gRPC transport directly at the
point where those handles are created. This avoids changing generic
Serve handle construction and does not add a Serve LLM opt-out.

gRPC transport was introduced in
[ray-project#59908](ray-project#59908). The
same-event-loop defaults were previously proposed globally in
[ray-project#62156](ray-project#62156); this PR limits
them to Serve LLM.

## Related PRs

These default changes are independent and can merge in any order:

- [ray-project#66432 Enable HAProxy by default on
Linux](ray-project#66432)
- [ray-project#66434 Select request body forwarding by
router](ray-project#66434)
- [ray-project#66436 Run sync deployment methods in a thread
pool](ray-project#66436)

## Tests

- The live GPU reproducer below completed a real OpenAI-compatible
request and observed only the consolidated `main` loop on both
production replicas
- Focused unit tests for LLMServer runtime env defaults and overrides,
OpenAI ingress gRPC handles, and router runtime env propagation: 5
passed in 4.22s
- The commit hooks passed Ruff, Black, pydoclint, docs style, import
order, and the other applicable repository checks

## Local performance benchmark

The short-request workload is intentionally framework-heavy while
retaining a real vLLM engine. Lower latency is better; higher throughput
is better.

```mermaid
---
config:
  themeCSS: |
    .plot path { stroke-width: 5px !important; stroke-linecap: round; }
    .legend .markers path { stroke-width: 10px !important; stroke-linecap: round; stroke-dasharray: 0 100; }
  themeVariables:
    xyChart:
      plotColorPalette: "#0072B2, #CC79A7, #009E73, #D55E00"
---
xychart-beta
    title "Effect of consolidating replica event loops"
    x-axis "Maximum concurrency" [64, 128, 256]
    y-axis "Requests per second" 0 --> 400
    line "This PR: shared main loop" [264.0, 355.9, 368.8]
    line "Separate user-code thread only" [246.4, 325.8, 318.6]
    line "Separate router loop only" [255.4, 318.4, 305.7]
    line "Current default: both separate" [244.1, 302.3, 272.9]
```

Compared with the previous loop defaults, the new defaults increased
throughput by 8%, 18%, and 35% at concurrency 64, 128, and 256,
respectively. Both individual settings contributed; their relative
impact varied with concurrency. The concurrency-256 values are the mean
of two runs; the other points are one run each.

The chart uses thick series lines and a dot legend with a
color-blind-friendly palette in this order: blue, purple, green, and
vermilion.

| Chart series | `RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD` |
`RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP` |
| --- | ---: | ---: |
| This PR: shared main loop | `0` | `0` |
| Separate user-code thread only | `1` | `0` |
| Separate router loop only | `0` | `1` |
| Current default: both separate | `1` | `1` |

### Benchmark setup

| Item | Configuration |
| --- | --- |
| Hardware | NVIDIA A10G (23 GiB) |
| Software | Python 3.12, vLLM 0.29.0, Torch 2.13, HAProxy 2.8.25 |
| Model | `Qwen/Qwen3-0.6B` on one vLLM-backed `LLMServer` replica |
| Serve topology | One `OpenAiIngress` replica and one `LLMServer`
replica; HAProxy was enabled with `RAY_SERVE_ENABLE_HA_PROXY=1` and
received requests on port 8000; ingress-to-model handles used gRPC in
both cases |
| Workload | `vllm bench serve`, OpenAI completions endpoint, random
input 32 tokens and output 8 tokens with `--random-range-ratio 0.5`,
`--ignore-eos`, and `--temperature 0` |
| Load | Infinite offered request rate at maximum concurrency 64, 128,
and 256 |
| Samples | 256 warmup requests, then 2,048 measured requests per point;
deterministic seed `20260928`; 32,768 measured requests and zero
failures across all four configurations |
| Environment application | Each environment-variable combination was
applied to both `OpenAiIngress` and `LLMServer` before their replicas
started |

As a control, an engine-heavy workload (1,024-token random input,
128-token random output, concurrency 64) delivered approximately 12
requests/s under either setting. This indicates that the difference
above is in framework overhead and becomes hidden when model execution
dominates.

## Duplicate search

I searched open Ray PRs for each environment variable and found no
duplicate of this Serve LLM-scoped change.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

## Live GPU reproducer

The reproducer uses the Python 3.12 `ray[llm]` wheel built from this
branch's merge base, then symlinks only `ray/llm` to the checkout.
Serve, generated protobufs, and compiled extensions remain from the
matching wheel.

```bash
uv venv --python 3.12 /tmp/ray-66435-live-venv
uv pip install --python /tmp/ray-66435-live-venv/bin/python \
  "https://s3-us-west-2.amazonaws.com/ray-wheels/master/98d8084dbf690739ef2921c25918cd49aa1db556/ray-3.0.0.dev0-cp312-cp312-manylinux2014_x86_64.whl[llm]"

SITE=/tmp/ray-66435-live-venv/lib/python3.12/site-packages/ray
mv "$SITE/llm" "$SITE/llm-wheel"
ln -s "$PWD/python/ray/llm" "$SITE/llm"

RAY_USAGE_STATS_ENABLED=0 /tmp/ray-66435-live-venv/bin/python - <<'PY'
import json
import time

import openai
from prometheus_client.parser import text_string_to_metric_families
import requests

import ray
from ray import serve
from ray.serve.llm import LLMConfig, LLMServingArgs, ModelLoadingConfig, build_openai_app


MODEL = "Qwen/Qwen3-0.6B"
METRICS_URL = "http://127.0.0.1:9999/metrics"
METRIC = "ray_serve_event_loop_monitoring_iterations_total"


def replica_event_loops():
    response = requests.get(METRICS_URL, timeout=5)
    response.raise_for_status()
    samples = [
        sample
        for family in text_string_to_metric_families(response.text)
        for sample in family.samples
        if sample.name == METRIC
        and sample.labels.get("component") == "replica"
        and sample.labels.get("application") == "default"
    ]
    actor_to_deployment = {
        sample.labels["actor_id"]: sample.labels["deployment"]
        for sample in samples
        if sample.labels.get("loop_type") == "main"
        and (
            sample.labels["deployment"] == "OpenAiIngress"
            or sample.labels["deployment"].startswith("LLMServer:")
        )
    }
    return {
        deployment: sorted(
            {
                sample.labels["loop_type"]
                for sample in samples
                if sample.labels["actor_id"] == actor_id
            }
        )
        for actor_id, deployment in actor_to_deployment.items()
    }


try:
    ray.init(
        num_cpus=8,
        num_gpus=1,
        include_dashboard=False,
        _metrics_export_port=9999,
        _system_config={"metrics_report_interval_ms": 1000},
    )
    config = LLMConfig(
        model_loading_config=ModelLoadingConfig(model_id=MODEL, model_source=MODEL),
        engine_kwargs={
            "max_model_len": 1024,
            "gpu_memory_utilization": 0.5,
            "enforce_eager": True,
        },
        deployment_config={"num_replicas": 1},
    )
    serve.run(build_openai_app(LLMServingArgs(llm_configs=[config])))

    client = openai.OpenAI(
        base_url="http://127.0.0.1:8000/v1", api_key="test", timeout=60
    )
    completion = client.chat.completions.create(
        model=MODEL,
        messages=[{"role": "user", "content": "Reply with: loop test passed"}],
        max_tokens=8,
        temperature=0,
    )
    print("COMPLETION", completion.choices[0].message.content)

    deadline = time.time() + 90
    while time.time() < deadline:
        loops = replica_event_loops()
        if len(loops) == 2:
            break
        time.sleep(1)
    else:
        raise RuntimeError("Timed out waiting for replica event-loop metrics")

    # Check three later scrapes so a separate loop cannot be hidden by a
    # just-created metric that has not reached the exporter yet.
    for _ in range(3):
        time.sleep(2)
        loops = replica_event_loops()
        assert len(loops) == 2
        assert all(loop_types == ["main"] for loop_types in loops.values())

    print("REPLICA_EVENT_LOOPS", json.dumps(loops, sort_keys=True))
finally:
    serve.shutdown()
    ray.shutdown()
PY
```

The script builds the unmodified `build_openai_app` application, starts
its real `OpenAiIngress` and vLLM-backed `LLMServer` deployments, sends
an OpenAI-compatible completion request, and reads Serve's event-loop
heartbeat metrics for those replica actors.

Relevant output:

```text
Deployment Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

Ingress Options:
ray_actor_options.runtime_env.env_vars:
  RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP: '0'
  RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD: '0'

HTTP Request: POST http://127.0.0.1:8000/v1/chat/completions "HTTP/1.1 200 OK"
COMPLETION <think>
Okay, the user wants me
REPLICA_EVENT_LOOPS {"LLMServer:Qwen--Qwen3-0_6B": ["main"], "OpenAiIngress": ["main"]}
```

The completion request initializes the ingress model handle before
metrics are checked. A separate user-code loop or handle-router loop
would emit `user_code` or `router` for the same replica actor. Both
production replicas emit only `main`, showing that the environment
settings take effect and consolidate those loops onto the replica event
loop.

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant