Skip to content

[Serve] Add gRPC inter-deployment communication - #59908

Merged
abrarsheikh merged 31 commits into
ray-project:masterfrom
eicherseiji:grpc-inter-deployment
Jan 15, 2026
Merged

abrarsheikh merged 31 commits into
ray-project:masterfrom
eicherseiji:grpc-inter-deployment

Conversation

@eicherseiji

@eicherseiji eicherseiji commented Jan 7, 2026 •

Copy link
Copy Markdown
Contributor

Why are these changes needed?

This PR adds gRPC-based inter-deployment communication for Ray Serve, allowing deployments to communicate with each other using gRPC transport instead of Ray actor calls. This can provide performance benefits in certain scenarios.

Key Changes

  1. gRPC Server on Replicas: Each replica now starts a gRPC server that can handle requests from other deployments.

  2. gRPC Replica Wrapper: A new gRPCReplicaWrapper class handles sending requests via gRPC and processing responses.

  3. Handle Options: The _by_reference option on handles controls whether to use Ray actor calls (True) or gRPC transport (False).

  4. New Environment Variables:

    • RAY_SERVE_USE_GRPC_BY_DEFAULT: Master flag to enable gRPC transport by default for all inter-deployment communication
    • RAY_SERVE_PROXY_USE_GRPC: Controls whether the proxy uses gRPC transport (defaults to the master flag value)
    • RAY_SERVE_GRPC_MAX_MESSAGE_SIZE: Configures the maximum gRPC message size (default: 2GB-1)

Related issue number

N/A

Checks

Test Plan

  • python/ray/serve/tests/test_grpc_e2e.py
  • python/ray/serve/tests/test_grpc_replica_wrapper.py
  • python/ray/serve/tests/unit/test_grpc_replica_result.py

Benchmarks

Script available here

Results show throughput/latency improvements w/ gRPC for message size < ~1MB.

benchmark_plot
  ⎿  ==============================================================================
       gRPC vs Plasma Benchmark Results
     ==============================================================================

       Payload  Metric               Plasma         gRPC          Δ     Winner
       ----------------------------------------------------------------------
       1 KB     Latency p50          2.63ms       1.89ms       +28%       gRPC
                Chain p50            4.11ms       3.02ms       +26%       gRPC
                Throughput            160/s        190/s       +16%       gRPC
       ----------------------------------------------------------------------
       10 KB    Latency p50          2.68ms       1.68ms       +37%       gRPC
                Chain p50            3.91ms       2.94ms       +25%       gRPC
                Throughput            167/s        185/s       +10%       gRPC
       ----------------------------------------------------------------------
       100 KB   Latency p50          2.74ms       2.02ms       +26%       gRPC
                Chain p50            4.28ms       3.06ms       +28%       gRPC
                Throughput            157/s        182/s       +13%       gRPC
       ----------------------------------------------------------------------
       500 KB   Latency p50          5.78ms       3.52ms       +39%       gRPC
                Chain p50            5.65ms       4.82ms       +15%       gRPC
                Throughput            114/s        144/s       +21%       gRPC
       ----------------------------------------------------------------------
       1 MB     Latency p50          6.31ms       5.18ms       +18%       gRPC
                Chain p50            5.96ms       6.20ms        -4%     Plasma
                Throughput            130/s        165/s       +21%       gRPC
       ----------------------------------------------------------------------
       2 MB     Latency p50          8.82ms       9.57ms        -9%     Plasma
                Chain p50            7.20ms      10.69ms       -48%     Plasma
                Throughput            123/s        106/s       -16%     Plasma
       ----------------------------------------------------------------------
       5 MB     Latency p50         15.20ms      23.72ms       -56%     Plasma
                Chain p50            8.90ms      23.25ms      -161%     Plasma
                Throughput             78/s         49/s       -58%     Plasma
       ----------------------------------------------------------------------
       10 MB    Latency p50         25.02ms      34.34ms       -37%     Plasma
                Chain p50            9.72ms      34.71ms      -257%     Plasma
                Throughput             38/s         31/s       -24%     Plasma
       ----------------------------------------------------------------------

Compared to parity implementation:

==============================================================================
  gRPC Transport: OSS 3.0.0.dev0 vs Parity 2.53.0
==============================================================================

  Payload  Metric              OSS 3.0.0.dev0  Parity 2.53.0
  ----------------------------------------------------------------------
  1 KB     Latency p50              1.82ms           2.27ms
           Chain p50                2.95ms           2.99ms
           Throughput                268/s            272/s
  ----------------------------------------------------------------------
  10 KB    Latency p50              1.82ms           2.05ms
           Chain p50                2.85ms           2.80ms
           Throughput                246/s            293/s
  ----------------------------------------------------------------------
  100 KB   Latency p50              2.04ms           2.35ms
           Chain p50                3.27ms           3.12ms
           Throughput                262/s            257/s
  ----------------------------------------------------------------------
  500 KB   Latency p50              3.67ms           3.78ms
           Chain p50                5.77ms           4.91ms
           Throughput                186/s            192/s
  ----------------------------------------------------------------------
  1 MB     Latency p50              4.99ms           5.39ms
           Chain p50                5.95ms           6.56ms
           Throughput                177/s            156/s
  ----------------------------------------------------------------------
  2 MB     Latency p50              7.91ms           7.37ms
           Chain p50                8.26ms          12.16ms
           Throughput                117/s            129/s
  ----------------------------------------------------------------------
  5 MB     Latency p50             17.86ms          19.53ms
           Chain p50               22.65ms          23.85ms
           Throughput                 87/s             54/s
  ----------------------------------------------------------------------
  10 MB    Latency p50             23.79ms          27.78ms
           Chain p50               35.67ms          31.06ms
           Throughput                 48/s             27/s
  ----------------------------------------------------------------------

  Cluster: 2 worker nodes (48 CPU, 4 GPU, 192GB RAM, 54.5GB object store each)
  3-trial average

Note: OSS 3.0.0.dev0 includes a token auth optimization (#59500) that reduces per-RPC overhead by caching auth tokens and avoiding object construction on each call. This likely explains the improved latency and throughput at larger payload sizes.

@eicherseiji
eicherseiji requested a review from a team as a code owner January 7, 2026 01:54

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a significant new feature to Ray Serve: inter-deployment communication via gRPC. This provides an alternative to the default Ray actor calls, which can be beneficial for performance and for certain network environments. The feature is enabled by a new _by_reference=False option on deployment handles.

The changes are comprehensive, touching multiple layers of the Serve stack:

  • A new InterDeploymentService is defined in the protobuf, with RPCs for unary and streaming requests, including support for backpressure.
  • A flexible serialization layer (RPCSerializer) is added, supporting cloudpickle, pickle, msgpack, orjson, and a noop for raw bytes. This allows users to choose the best serialization method for their use case.
  • Replicas now run a gRPC server to handle these incoming requests. The logic is nicely encapsulated in a decorator (_wrap_inter_deployment_grpc_call).
  • On the client side, a new gRPCReplicaWrapper and gRPCReplicaResult are introduced to handle sending requests and receiving responses over gRPC.
  • The DeploymentHandle.options() method is extended with _by_reference, _request_serialization, and _response_serialization to control this new communication channel.
  • New tests are added to validate the gRPC transport, including different serialization methods and streaming.

Overall, this is a well-designed and well-implemented feature. The code is clear and the changes are well-contained. I have one suggestion for refactoring to reduce code duplication.

Comment thread python/ray/serve/_private/replica.py Resolved
rpc HandleRequestWithRejection(InterDeploymentRequest) returns (InterDeploymentResponse);
// Streaming request with rejection support for backpressure.
rpc HandleRequestWithRejectionStreaming(InterDeploymentRequest) returns (stream InterDeploymentResponse);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Proto file modified requires RPC standards review (Bugbot Rules)

Medium Severity

⚠️ This PR modifies one or more .proto files.
Please review the RPC fault-tolerance & idempotency standards guide here:
https://github.com/ray-project/ray/tree/master/doc/source/ray-core/internals/rpc-fault-tolerance.rst

Fix in Cursor Fix in Web

Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
@eicherseiji
eicherseiji marked this pull request as draft January 7, 2026 02:01
@eicherseiji eicherseiji changed the title [Serve] Add gRPC inter-deployment communication [Serve][WIP][Do not merge] Add gRPC inter-deployment communication Jan 7, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

Add support for deployments to communicate via gRPC instead of Ray actor
calls. This is enabled by setting `_by_reference=False` on a deployment
handle:

```python
handle = serve.get_deployment_handle("Downstream", "app")
grpc_handle = handle.options(_by_reference=False)
result = await grpc_handle.remote(data)
```

Changes:
- Add InterDeploymentService protobuf with HandleRequest, HandleRequestStreaming
  HandleRequestWithRejection, HandleRequestWithRejectionStreaming RPCs
- Add _by_reference, _request_serialization, _response_serialization handle options
- Add RPCSerializer supporting cloudpickle, pickle, msgpack, orjson, noop
- Add gRPCReplicaWrapper for client-side gRPC transport
- Add gRPCReplicaResult for handling gRPC responses
- Add gRPC server to Replica implementing InterDeploymentServiceServicer
- Add grpc_port field to RunningReplicaInfo

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]>
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
@eicherseiji
eicherseiji force-pushed the grpc-inter-deployment branch 2 times, most recently from 27d99b1 to fda4b8e Compare January 7, 2026 21:49
from ray.serve.handle import DeploymentHandle
from ray.serve.schema import EncodingType, LoggingConfig, ReplicaRank

logger = logging.getLogger(SERVE_LOGGER_NAME)


def _wrap_grpc_call(f):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

@@ -1195,6 +1306,121 @@ def _wrap_request(
with self._handle_errors_and_metrics(request_metadata) as status_code_callback:
yield status_code_callback

@_wrap_grpc_call

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Following code block identical to parity implementation

@@ -261,3 +280,303 @@ def to_object_ref_gen(self) -> ray.ObjectRefGenerator:
), "to_object_ref_gen can only be called on a streaming ReplicaActorResult."

return self._obj_ref_gen


class gRPCReplicaResult(ReplicaResult):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

Comment thread python/ray/serve/_private/replica.py Resolved
@@ -94,6 +112,58 @@ def send_request_python(
)


class gRPCReplicaWrapper(ReplicaWrapper):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

@@ -62,7 +65,9 @@ def copy_and_update(self, **kwargs) -> "DynamicHandleOptionsBase":

@dataclass(frozen=True)
class DynamicHandleOptions(DynamicHandleOptionsBase):
_by_reference: bool = True
_by_reference: bool = not RAY_SERVE_USE_GRPC_BY_DEFAULT

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical to parity implementation

_by_reference=handle_options._by_reference,
_on_separate_loop=init_options._run_router_in_separate_loop,
request_serialization=handle_options.request_serialization,
response_serialization=handle_options.response_serialization,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Additions identical to parity implementation

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Identical

@eicherseiji eicherseiji added the go add ONLY when ready to merge, run all tests label Jan 7, 2026
@eicherseiji eicherseiji changed the title [Serve][WIP][Do not merge] Add gRPC inter-deployment communication [Serve] Add gRPC inter-deployment communication Jan 7, 2026
@eicherseiji
eicherseiji force-pushed the grpc-inter-deployment branch 2 times, most recently from 280d413 to 0ec7116 Compare January 7, 2026 23:04
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/constants.py Resolved
This reverts commit f58be92.

Signed-off-by: Seiji Eicher <[email protected]>
Ports ANYSCALE_RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH from rayturbo.
Default is 4MB (gRPC default) for replica-to-replica communication,
separate from RAY_SERVE_GRPC_MAX_MESSAGE_SIZE (4GB) used for proxy.

Signed-off-by: Seiji Eicher <[email protected]>
This reverts commit 0147d76.

Signed-off-by: Seiji Eicher <[email protected]>
Comment thread python/ray/serve/_private/replica.py Resolved
Signed-off-by: Seiji Eicher <[email protected]>
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
When using gRPC for inter-deployment communication, ObjectRefs passed
as arguments need to be resolved to their values before serialization.
This mirrors Ray's behavior where actor calls auto-dereference ObjectRefs.

Signed-off-by: Seiji Eicher <[email protected]>
Comment thread .buildkite/serve.rayci.yml Resolved
The asyncio Python gRPC implementation has circular references that
cause gc.garbage to grow, failing the test. Add a whitelist callback
to filter out known gRPC metadata objects that are small and safe to
be collected by the slower GC cycle.

Signed-off-by: Seiji Eicher <[email protected]>
When RAY_SERVE_USE_GRPC_BY_DEFAULT=1, the default for _by_reference
becomes False. Tests calling _to_object_ref_sync() fail because they
need _by_reference=True. Skip these tests in gRPC mode, matching
rayturbo behavior.

Signed-off-by: Seiji Eicher <[email protected]>
lambda _: ray.serve.context._remove_in_flight_request(
request_context._internal_request_id, self._response_id
)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Missing cancel flag check for in-flight request tracking

Medium Severity

The gRPCReplicaResult unconditionally tracks in-flight requests, while the existing ActorReplicaResult (lines 110-121) only tracks them when request_context.cancel_on_parent_request_cancel is True. This inconsistency means gRPC-based requests don't respect the cancel_on_parent_request_cancel setting, potentially causing unnecessary overhead and behavioral differences in request cancellation propagation between the two transport mechanisms.

Fix in Cursor Fix in Web

(
"grpc.max_receive_message_length",
RAY_SERVE_GRPC_MAX_MESSAGE_SIZE,
RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed: RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH is used in parity, not the existing RAY_SERVE_GRPC_MAX_MESSAGE_SIZE.

h.remote().result()


@pytest.mark.skipif(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Also in parity



@pytest.mark.skipif(
RAY_SERVE_USE_GRPC_BY_DEFAULT,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Also in parity

# https://github.com/ray-project/ray/issues/12395
def test_replica_memory_growth(serve_instance):
# https://github.com/ray-project/ray/issues/12395
# NOTE(zcin): this test checks that there are no circular references

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Also in parity

return await deployment_response


async def resolve_deployment_response(obj: Any, request_metadata: RequestMetadata):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Merged logic from parity resolve_deployment_response

@abrarsheikh
abrarsheikh merged commit 80d3715 into ray-project:master Jan 15, 2026
abrarsheikh pushed a commit that referenced this pull request Mar 28, 2026
…ve abstract base class (#60198)

## Why are these changes needed?

This refactors the Replica class hierarchy to remove `ReplicaBase` in
favor of `Replica` for unified gRPC and direct ingress handling.
Reference PRs:
- #60914
- #59908
- #60118

## Related issue number

N/A

## Checks

- [x] I've signed off every commit (by using the -s flag)
- [x] I've run `scripts/format.sh` to lint the changes in this PR
- [ ] I've included any doc changes needed for
https://docs.ray.io/en/master/
- [ ] I've added any new APIs to the API reference
- [x] I've made sure the tests are passing
- [ ] Testing Strategy
  - [x] Unit tests
  - [ ] Release tests
  - [ ] This PR is not tested :(

## Changes

---------

Signed-off-by: Seiji Eicher <[email protected]>
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
…ve abstract base class (ray-project#60198)

## Why are these changes needed?

This refactors the Replica class hierarchy to remove `ReplicaBase` in
favor of `Replica` for unified gRPC and direct ingress handling.
Reference PRs:
- ray-project#60914
- ray-project#59908
- ray-project#60118

## Related issue number

N/A

## Checks

- [x] I've signed off every commit (by using the -s flag)
- [x] I've run `scripts/format.sh` to lint the changes in this PR
- [ ] I've included any doc changes needed for
https://docs.ray.io/en/master/
- [ ] I've added any new APIs to the API reference
- [x] I've made sure the tests are passing
- [ ] Testing Strategy
  - [x] Unit tests
  - [ ] Release tests
  - [ ] This PR is not tested :(

## Changes

---------

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants