Repository navigation
[Serve] Add gRPC inter-deployment communication - #59908
Conversation
There was a problem hiding this comment.
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
InterDeploymentServiceis defined in the protobuf, with RPCs for unary and streaming requests, including support for backpressure. - A flexible serialization layer (
RPCSerializer) is added, supportingcloudpickle,pickle,msgpack,orjson, and anoopfor 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
gRPCReplicaWrapperandgRPCReplicaResultare introduced to handle sending requests and receiving responses over gRPC. - The
DeploymentHandle.options()method is extended with_by_reference,_request_serialization, and_response_serializationto 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.
| rpc HandleRequestWithRejection(InterDeploymentRequest) returns (InterDeploymentResponse); | ||
| // Streaming request with rejection support for backpressure. | ||
| rpc HandleRequestWithRejectionStreaming(InterDeploymentRequest) returns (stream InterDeploymentResponse); | ||
| } |
There was a problem hiding this comment.
Proto file modified requires RPC standards review (Bugbot Rules)
Medium Severity
.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
There was a problem hiding this comment.
Identical to parity implementation
There was a problem hiding this comment.
Identical to parity implementation
There was a problem hiding this comment.
Identical to parity implementation
There was a problem hiding this comment.
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]>
27d99b1 to
fda4b8e
Compare
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]>
Signed-off-by: Seiji Eicher <[email protected]>
| 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): |
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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): | |||
There was a problem hiding this comment.
Identical to parity implementation
| @@ -94,6 +112,58 @@ def send_request_python( | |||
| ) | |||
|
|
|||
|
|
|||
| class gRPCReplicaWrapper(ReplicaWrapper): | |||
There was a problem hiding this comment.
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 | |||
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
Additions identical to parity implementation
280d413 to
0ec7116
Compare
Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
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]>
Signed-off-by: Seiji Eicher <[email protected]>
This reverts commit 0147d76. Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
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]>
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 | ||
| ) | ||
| ) |
There was a problem hiding this comment.
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.
| ( | ||
| "grpc.max_receive_message_length", | ||
| RAY_SERVE_GRPC_MAX_MESSAGE_SIZE, | ||
| RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH, |
There was a problem hiding this comment.
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( |
|
|
||
|
|
||
| @pytest.mark.skipif( | ||
| RAY_SERVE_USE_GRPC_BY_DEFAULT, |
| # 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 |
| return await deployment_response | ||
|
|
||
|
|
||
| async def resolve_deployment_response(obj: Any, request_metadata: RequestMetadata): |
There was a problem hiding this comment.
Merged logic from parity resolve_deployment_response
…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]>
…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]>
## 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]>
## 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]>
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
gRPC Server on Replicas: Each replica now starts a gRPC server that can handle requests from other deployments.
gRPC Replica Wrapper: A new
gRPCReplicaWrapperclass handles sending requests via gRPC and processing responses.Handle Options: The
_by_referenceoption on handles controls whether to use Ray actor calls (True) or gRPC transport (False).New Environment Variables:
RAY_SERVE_USE_GRPC_BY_DEFAULT: Master flag to enable gRPC transport by default for all inter-deployment communicationRAY_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
scripts/format.shto lint the changes in this PR.temporary testing hook, I've added it under the API Reference
(Experimental) page.
Test Plan
python/ray/serve/tests/test_grpc_e2e.pypython/ray/serve/tests/test_grpc_replica_wrapper.pypython/ray/serve/tests/unit/test_grpc_replica_result.pyBenchmarks
Script available here
Results show throughput/latency improvements w/ gRPC for message size < ~1MB.
Compared to parity implementation:
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.