Skip to content

[Serve] Turn same event loop flags on by default - #62156

Closed
win5923 wants to merge 11 commits into
ray-project:masterfrom
win5923:ray-serve-same-event-loop
Closed

win5923 wants to merge 11 commits into
ray-project:masterfrom
win5923:ray-serve-same-event-loop

Conversation

@win5923

@win5923 win5923 commented Mar 28, 2026 •

Copy link
Copy Markdown
Member

Description

  • Change defaults for RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD and RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP from 1 to 0.
  • Remove redundant RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP=0 overrides in test BUILD.bazel (now the default).
  • Update documentation in asyncio-best-practices, performance, and monitoring guides to reflect the new defaults.

Related issues

Closes #61226

Additional information

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

@win5923
win5923 requested a review from a team as a code owner March 28, 2026 07:41

@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 default behavior of Ray Serve to run user code and the request router in the same event loop as the replica's main/control loop, aiming to improve throughput by reducing cross-loop communication overhead. The changes include updating the default values for RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD and RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP to 0, adjusting documentation across several files, and removing now-redundant environment variable overrides in the test suite. Feedback was provided to clarify documentation regarding which specific event loop the router shares by default to ensure accuracy when other isolation flags are toggled.

@win5923
win5923 force-pushed the ray-serve-same-event-loop branch from f7cc883 to 523a475 Compare March 28, 2026 07:43
Comment thread python/ray/serve/tests/BUILD.bazel Resolved
@win5923 win5923 added the serve Ray Serve Related Issue label Mar 28, 2026
@win5923
win5923 force-pushed the ray-serve-same-event-loop branch from 6259e2b to 8efecb4 Compare March 28, 2026 10:34
@win5923
win5923 requested a review from a team as a code owner March 28, 2026 13:25
Comment thread python/ray/serve/_private/constants.py Resolved
Comment thread python/ray/serve/tests/BUILD.bazel Resolved
@win5923
win5923 force-pushed the ray-serve-same-event-loop branch from abf7c69 to d3cefa1 Compare March 28, 2026 13:33
Comment thread python/ray/serve/tests/BUILD.bazel Resolved
@win5923
win5923 force-pushed the ray-serve-same-event-loop branch 2 times, most recently from 36c9e00 to 60dd38d Compare March 29, 2026 15:37
@win5923
win5923 force-pushed the ray-serve-same-event-loop branch from 60dd38d to 12a8d66 Compare March 29, 2026 18:37
@github-actions

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 Apr 13, 2026
@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Apr 14, 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.

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

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 5ff104e. Configure here.

--test-env=RAY_SERVE_ENABLE_DIRECT_INGRESS=0
--test-env=RAY_SERVE_DIRECT_INGRESS_MIN_DRAINING_PERIOD_S=0.01
--test-env=SERVE_SOCKET_REUSE_PORT_ENABLED=1
--test-env=RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP=1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

HAProxy pip tests missing router separate loop override

Medium Severity

The "HAProxy tests (pip)" CI job runs the same test files (serve_hap_test_names.txt) as the regular "HAProxy tests" job, but the RAY_SERVE_RUN_ROUTER_IN_SEPARATE_LOOP=1 override was only added to the regular variant. With the default now 0, the pip variant will run those HAProxy tests with the router in the same loop, likely causing test failures for the same reasons the regular variant needed the override.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 5ff104e. Configure here.

@abrarsheikh

Copy link
Copy Markdown
Contributor

Hey unfortunately, I will be holding this change off for a little bit longer, looking for some data points from community before we make this default.

@win5923

win5923 commented Apr 25, 2026

Copy link
Copy Markdown
Member Author

Hey unfortunately, I will be holding this change off for a little bit longer, looking for some data points from community before we make this default.

Make sense, I think this is a breaking change.

@win5923 win5923 closed this Jun 22, 2026
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

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

serve Ray Serve Related Issue unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve] Turn same event loop flags on by default

2 participants