Skip to content

[Serve] Add direct ingress support for Ray Serve - #60118

Merged
abrarsheikh merged 30 commits into
ray-project:masterfrom
eicherseiji:direct-ingress-v2
Jan 29, 2026
Merged

abrarsheikh merged 30 commits into
ray-project:masterfrom
eicherseiji:direct-ingress-v2

Conversation

@eicherseiji

@eicherseiji eicherseiji commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR adds direct ingress functionality to Ray Serve, allowing replicas to listen directly on ports for incoming traffic. This enables deployments where each replica is individually addressable, which is useful for Kubernetes ingress controllers and load balancers.

Key changes:

  • Add direct ingress HTTP utility for ASGI receive proxying
  • Add direct ingress gRPC support (unary-unary handlers, health checks)
  • Add replica response generator for disconnect detection
  • Add node port manager for per-node port allocation
  • Add direct ingress support to controller (target groups, port allocation)
  • Add direct ingress support to replica (HTTP/gRPC servers, graceful shutdown)
  • Add direct ingress constants and feature flag (RAY_SERVE_ENABLE_DIRECT_INGRESS)
  • Add integration and unit tests

The feature is disabled by default and can be enabled by setting RAY_SERVE_ENABLE_DIRECT_INGRESS=1.

Test plan

  • Run test_direct_ingress.py integration tests
  • Run test_direct_ingress_standalone.py standalone tests
  • Run test_controller_direct_ingress.py unit tests
  • Benchmarks

Benchmarks

Validated using release image from https://buildkite.com/ray-project/release/builds/76725#019be801-2dc9-45f7-bf1e-3d7ae41ff6d8 and RAY_SERVE_ENABLE_DIRECT_INGRESS=1, direct ingress provides 6x reduction in TTFT and 1.8x improvement in throughput. Max concurrency 32/replica, 256 prompts/replica total. ITL 1024 OTL 256.
httpproxy_vs_direct_ingress

HTTPProxy (baseline) sweep: https://gist.github.com/eicherseiji/630a83a0582aad22fb4655e6464a0038
Direct Ingress (this PR) sweep: https://gist.github.com/eicherseiji/18d326524cbfe48e0353bfa8243bbb28
Toy load balancer used to test Direct Ingress: https://gist.github.com/eicherseiji/cce80555ac2e8d04482483e5f8422509

@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 direct ingress support for Ray Serve, a significant feature enabling replicas to be individually addressable. The changes are extensive, touching the controller, replica logic, and adding new components for port management. The implementation is mostly solid and is accompanied by comprehensive tests. My review focuses on improving maintainability by avoiding private member access, enhancing robustness by adding validation and fixing a race condition, and addressing a critical bug in header parsing. I've also noted a potential improvement for the graceful shutdown logic.

Comment on lines +1734 to +1737
was_error=not healthy,
status_code=str(status_code),
)
return

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.

critical

The logic to extract request_id from headers is not safe. If the SERVE_HTTP_REQUEST_ID_HEADER is missing, headers.get(...) returns None, and calling .decode("utf-8") on None will raise an AttributeError, causing the request to fail. This should be handled gracefully, for example by providing a default value to headers.get().

Suggested change
was_error=not healthy,
status_code=str(status_code),
)
return
request_id = (
headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8"), b"").decode("utf-8")
or generate_request_id()
)

Comment on lines +29 to +30
# TODO(abrar): add a validation here to ensure min_port and max_port dont overlap with
# ray params min_worker_port and max_worker_port.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The TODO on line 29 highlights a potential for port conflicts with Ray worker ports. The direct ingress port range should be validated against the min_worker_port and max_worker_port configured for Ray to prevent hard-to-debug port collision issues. This is a critical correctness concern.

Comment on lines +1760 to +1768
request_timeout_s = self._parse_request_timeout(headers)

request_metadata = RequestMetadata(
request_id=request_id,
internal_request_id=generate_request_id(),
call_method="__call__",
route=self._determine_http_route(scope),
app_name=self._deployment_id.app_name,
# TODO(edoakes): populate the multiplexed model ID.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

There is a race condition in the backpressure logic for direct ingress requests. The check _can_accept_request and the increment of self._num_queued_requests are not atomic. This can lead to more requests being accepted than max_queued_requests under high load, as noted in the code comment.

To fix this, you should introduce a lock to protect the critical section where the number of queued requests is checked and modified.

For example, in Replica.__init__:

self._queued_requests_lock = asyncio.Lock()

Then, in _direct_ingress_asgi, wrap the check and increment:

async with self._queued_requests_lock:
    if not self._can_accept_request(request_metadata):
        # ... drop request
        return
    self._num_queued_requests += 1

And finally, ensure the decrement is also atomic within call_asgi:

async with self._start_request(request_metadata):
    async with self._queued_requests_lock:
        self._num_queued_requests -= 1
    # ... rest of the method

Comment on lines +1422 to +1440
def _get_node_id_to_alive_replica_ids(self) -> Dict[str, Set[str]]:
node_id_to_alive_replica_ids = defaultdict(set)
# TODO(abrar): Expose the right APIs in the DeploymentStateManager
# to get the alive replicas for a deployment.
for ds in self.deployment_state_manager._deployment_states.values():
# here we get all the replicas irrespective of their state
# unlike in the get_running_replica_infos_for_ingress_deployment
# where we only get the replicas that are running, because we dont
# wish to agressively cleanup ports for replicas that are not running
# and are in the process of being updated or are in the process of
# being started.
replicas: List[DeploymentReplica] = ds._replicas.get()
for replica in replicas:
node_id: Optional[str] = replica.actor_node_id
if node_id is None:
continue
replica_unique_id = replica.replica_id.unique_id
node_id_to_alive_replica_ids[node_id].add(replica_unique_id)
return node_id_to_alive_replica_ids

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The method _get_node_id_to_alive_replica_ids accesses private members _deployment_states and _replicas of DeploymentStateManager. This breaks encapsulation and makes the code harder to maintain, as noted in the TODO comment. To improve maintainability, a public API should be exposed in DeploymentStateManager to provide this information instead of accessing private attributes directly.

Comment on lines +1894 to +1898
# if direct ingress is not enabled or the replica is not an ingress replica,
# we can just call the super method to perform the graceful shutdown.
await super().perform_graceful_shutdown()
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The TODO comment highlights a potential issue with the graceful shutdown logic for direct ingress. Relying on a fixed draining period might not be robust if the load balancer (e.g., ALB) continues to send traffic. The suggested improvement in the TODO to use a cooldown period since the last request finished would make the shutdown process more reliable and prevent requests from being dropped during shutdown. It would be good to create a follow-up issue to track this improvement.

@eicherseiji eicherseiji added the go add ONLY when ready to merge, run all tests label Jan 14, 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

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 modulo imports

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.

Integrated parity and OSS, but otherwise 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 modulo gRPC

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

@@ -175,6 +184,15 @@ async def __init__(
self.cluster_node_info_cache = create_cluster_node_info_cache(self.gcs_client)
self.cluster_node_info_cache.update()

self._direct_ingress_enabled = RAY_SERVE_ENABLE_DIRECT_INGRESS

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

@@ -600,6 +620,20 @@ async def run_control_loop_step(
| self.proxy_state_manager.get_alive_proxy_actor_ids()
)

# Direct ingress port management

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.

Test targets are complete with logic ported from parity

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 modulo env variables and stubbed out HAProxy

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 modulo imports and env variables

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 modulo import paths and env variable naming

@@ -249,6 +267,8 @@ async def __init__(
] = []
self._refresh_autoscaling_deployments_cache()

self._last_broadcasted_target_groups: List[TargetGroup] = []

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


This information is used to setup the load balancer.
"""
def _get_proxy_target_groups(self) -> List[TargetGroup]:

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.

Keeping the base class OSS logic by renaming the function. Removing the unused parameters. They were only present to match the signature of the override in parity implementation.

If there are multiple applications with no running replicas, we return
one target group per application with unique route prefix.
"""
proxy_target_groups = self._get_proxy_target_groups()

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.

In parity, this was a call to the base class

]

if not apps:
return proxy_target_groups

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.

Divergence. Skipping HAProxy logic

route_prefix, app_name
)
)

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.

Remainder is identical modulo skipped HAProxy logic and prepended underscore on function names

@@ -262,6 +277,119 @@ def __init__(

self.set_autoscaling_config(autoscaling_config)

if self._is_direct_ingress:

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 force-pushed the direct-ingress-v2 branch 5 times, most recently from c0f4462 to c939736 Compare January 15, 2026 01:03
@@ -1152,9 +1178,123 @@ async def record_routing_stats(self) -> Dict[str, Any]:
raise e from None


async def send_http_response(message, status_code, send):

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

@@ -355,7 +374,14 @@ def should_collect_ongoing_requests(self) -> bool:
│ └──────────────────────────────┘ │
│ │
└────────────────────────────────────────────────────────────────┘

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

@@ -1169,7 +1309,12 @@ async def _on_initialized(self):
def _on_request_cancelled(
self, metadata: RequestMetadata, e: asyncio.CancelledError
):
"""Recursively cancels child requests."""
"""Recursively cancel child requests.

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

@@ -1179,6 +1324,7 @@ def _on_request_cancelled(
task.cancel()

# Cancel child requests that have already been assigned.
# This is for gRPC requests and direct ingress requests.

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

@@ -1187,6 +1333,16 @@ def _on_request_failed(self, request_metadata: RequestMetadata, e: Exception):
if ray.util.pdb._is_ray_debugger_post_mortem_enabled():
ray.util.pdb._post_mortem()

def _can_accept_request(self, 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.

Identical

@@ -380,15 +558,35 @@ def enable_custom_autoscaling_metrics(
def inc_num_ongoing_requests(self, request_metadata: RequestMetadata) -> int:
"""Increment the current total queue length of requests for this replica."""
self._num_ongoing_requests += 1

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

@@ -408,6 +606,72 @@ def record_request_metrics(self, *, route: str, latency_ms: float, was_error: bo
else:
self._request_counter.inc(tags={"route": route})

def record_ingress_request_metrics(

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

@@ -1206,12 +1600,302 @@ def _wrap_request(
multiplexed_model_id=request_metadata.multiplexed_model_id,
grpc_context=request_metadata.grpc_context,
_ray_trace_ctx=ray_trace_ctx,
cancel_on_parent_request_cancel=self._ingress

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

)
)

with self._handle_errors_and_metrics(request_metadata) as status_code_callback:
yield status_code_callback

async def _dataplane_health_check(self) -> Tuple[bool, str]:

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

Comment thread python/ray/serve/_private/replica.py Outdated

return healthy, message

def get_asgi_tracing_context(self, headers: List[Tuple[bytes, bytes]]):

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.

Here to end of file identical

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.

get_asgi_tracing_context needs to be omitted. Since tracing is not implemented in OSS

eicherseiji and others added 9 commits January 15, 2026 10:39
This adds direct ingress functionality to Ray Serve, allowing replicas to
listen directly on ports (HTTP 30000-31000) for incoming traffic. This
enables deployments where each replica is individually addressable,
which is useful for Kubernetes ingress controllers and load balancers.

Key changes:
- Add direct ingress HTTP utility for ASGI receive proxying
- Add replica response generator for disconnect detection
- Add node port manager for per-node port allocation
- Add direct ingress support to controller (target groups, port allocation)
- Add direct ingress support to replica (ASGI server, graceful shutdown)
- Add direct ingress constants and feature flag (RAY_SERVE_ENABLE_DIRECT_INGRESS)
- Add integration and unit tests

The feature is disabled by default and can be enabled by setting
RAY_SERVE_ENABLE_DIRECT_INGRESS=1.

Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>
The unit test sets the env var via monkeypatch fixture, matching rayturbo.

Signed-off-by: Seiji Eicher <[email protected]>
Metrics collection for direct ingress is not critical for the initial port.

Signed-off-by: Seiji Eicher <[email protected]>
Leftover from metrics removal - override just called super() with no additional logic.

Signed-off-by: Seiji Eicher <[email protected]>
Use ray.util.metrics instead of ray.serve.metrics to avoid reserved tag
conflicts (ray.serve.metrics reserves "application", "deployment", etc.).

This adds metrics tracking for direct ingress requests:
- Request counters with route, method, application, status_code tags
- Error counters for both ingress and deployment level
- Latency histograms for request processing time
- Ongoing requests gauge for autoscaling

Signed-off-by: Seiji Eicher <[email protected]>
- Add gRPC server startup alongside HTTP server when gRPC is enabled
- Add _direct_ingress_unary_unary handler for gRPC requests
- Add _direct_ingress_service_handler_factory for gRPC service handlers
- Support Healthz and ListApplications gRPC endpoints
- Handle graceful shutdown for gRPC server task

Signed-off-by: Seiji Eicher <[email protected]>
@@ -1548,6 +1559,9 @@ def __init__(self, **kwargs):
# get node ID
self._node_id = ray.get_runtime_context().get_node_id()
self._http_options: Optional[HTTPOptions] = None
self._grpc_options: Optional[gRPCOptions] = None

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

@@ -1612,10 +1626,15 @@ async def allocate_and_start_server(start_server_fn, protocol):
raise RuntimeError(err_msg)

# Fetch configs
self._http_options = ray.get(
self._controller_handle.get_http_config.remote(),
self._http_options, self._grpc_options = ray.get(

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

@@ -1639,7 +1658,30 @@ async def start_http_server(port):
protocol=RequestProtocol.HTTP,
)

logger.info(f"Started HTTP server on port {self._http_port}")
# Allocate and start gRPC server if enabled

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

await self.shutdown()
if self._direct_ingress_http_server_task:
self._direct_ingress_http_server_task.cancel()
if self._direct_ingress_grpc_server_task:

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

Comment thread python/ray/serve/_private/replica.py Outdated

return tracing_ctx

def get_grpc_tracing_context(self, context: grpc._cython.cygrpc._ServicerContext):

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 modulo set_rpc_span_attributes

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.

get_grpc_tracing_context needs to be removed

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.

Done

@eicherseiji
eicherseiji marked this pull request as ready for review January 16, 2026 00:25
@eicherseiji
eicherseiji requested a review from a team as a code owner January 16, 2026 00:25
request_id = (
headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8")
or generate_request_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 header causes AttributeError when parsing request ID

High Severity

When the x-request-id header is not present in an HTTP request, headers.get(...) returns None, and calling .decode("utf-8") on None raises AttributeError: 'NoneType' object has no attribute 'decode'. The or generate_request_id() fallback never executes because the exception occurs first. This affects all direct ingress HTTP requests that don't include the x-request-id header, which is the common case for most clients.

Fix in Cursor Fix in Web

msg = (
f"Request {request_id} timed out after "
f"{self._http_options.request_timeout_s}s."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Timeout error message displays wrong timeout value

Low Severity

When a request times out, the error message at line 2295 uses self._http_options.request_timeout_s (the default config value), but the actual timeout applied at line 2267 is request_timeout_s, which may have been overridden by the x-request-timeout-seconds header. If a client sets a custom timeout (e.g., 5 seconds) via header, but the default is 30 seconds, the error message will incorrectly say "timed out after 30s" instead of "5s".

Fix in Cursor Fix in Web

@ray-gardener ray-gardener Bot added the serve Ray Serve Related Issue label Jan 16, 2026
- Add serve_di_test_names.txt with 44 tests to run with DI enabled
- Add direct ingress test targets to BUILD.bazel (with _with_grpc variants)
- Add "same loop" CI variant with RAY_SERVE_RUN_USER_CODE_IN_SEPARATE_THREAD=0
- Port test_handle.py from rayturbo (tests _by_reference option)

Signed-off-by: Seiji Eicher <[email protected]>
Add recording of serve_num_http_requests metric in _record_errors_and_metrics
when handling direct ingress HTTP requests. This ensures HTTP request metrics
are properly tracked when direct ingress is enabled.

Signed-off-by: Seiji Eicher <[email protected]>
@eicherseiji
eicherseiji marked this pull request as ready for review January 22, 2026 21:45
request_id = (
headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8")
or generate_request_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.

Request ID extraction crashes when header is missing

High Severity

The request_id extraction calls .decode("utf-8") directly on the result of headers.get(), which returns None when the x-request-id header is not present. This causes an AttributeError: 'NoneType' object has no attribute 'decode' on every HTTP request without the header. Compare with the correct pattern used two lines below for request_disconnect_disabled, which provides a default value b"?0".

Fix in Cursor Fix in Web

)
return port

raise NoAvailablePortError(self._protocol, self._node_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.

Port allocator can assign same port to multiple replicas

Medium Severity

After controller restart, update_port_if_missing adds recovered ports to _allocated_ports but doesn't remove them from _available_ports. When allocate is called for a new replica, it pops from the heap and only checks _blocked_ports, not whether the port is already in _allocated_ports.values(). This can cause the same port to be assigned to multiple replicas, resulting in port conflicts.

Additional Locations (1)

Fix in Cursor Fix in Web

self.queue.put_nowait(msg)

def close_queue(self):
self.queue.close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Method calls nonexistent asyncio.Queue.close() method

Low Severity

The close_queue method calls self.queue.close(), but asyncio.Queue does not have a close() method. If called, this would raise AttributeError: 'Queue' object has no attribute 'close'. The method is currently unused but represents broken code that would fail if invoked.

Fix in Cursor Fix in Web

Remove 9 skip blocks that are no longer needed now that proxy metrics
recording has been ported for direct ingress. Keep only the skip for
test_proxy_metrics_http_status_code_is_error which still fails.

Also remove redundant disable_router_queue_len_throttle fixture since
the env var is already set in BUILD.bazel.

Signed-off-by: Eugene Kim <[email protected]>
Signed-off-by: Seiji Eicher <[email protected]>

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 modulo imports

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.

Skips are identical to parity implementation

was_error=user_exception is not None,
)

# Record ingress metrics for direct ingress HTTP requests

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

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.

Modulo set_http_span_attributes and set_rpc_span_attributes

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 modulo env variables and OSS-specific CI dependency setup

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.

Contents identical to parity modulo proxy/ingress specific items

if not response_started:
msg = (
f"Request {request_id} timed out after "
f"{self._http_options.request_timeout_s}s."

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Timeout error message shows wrong timeout value

Medium Severity

The timeout error message uses self._http_options.request_timeout_s instead of the local request_timeout_s variable. When a client overrides the timeout via the x-request-timeout-seconds header (parsed at line 2181), the actual timeout applied differs from the default HTTP options timeout. The error message will display an incorrect timeout value, confusing users about what timeout actually occurred.

Fix in Cursor Fix in Web

self.queue.put_nowait(msg)

def close_queue(self):
self.queue.close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Dead code calls nonexistent asyncio.Queue method

Low Severity

The close_queue method calls self.queue.close(), but asyncio.Queue does not have a close() method. This would raise AttributeError if invoked. The method is currently unused (no callers found), making it dead code that would fail if ever used.

Fix in Cursor Fix in Web

port,
protocol,
block_port=True,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Port incorrectly blocked on non-port-conflict failures

Medium Severity

The code always passes block_port=True when releasing a port after a server startup failure, regardless of whether the failure was due to port-in-use (is_port_in_use). The is_port_in_use variable is computed at lines 1613-1619 to distinguish port conflicts from other errors, but it's only used for the error message, not for the block_port parameter. This causes ports to be permanently blocked even when failures are unrelated to port conflicts.

Fix in Cursor Fix in Web

Comment thread python/ray/serve/_private/constants.py Outdated
Comment on lines +597 to +600
RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH = int(
# Default max message length in gRPC is 4MB, we keep that default
os.environ.get("RAY_SERVE_REPLICA_GRPC_MAX_MESSAGE_LENGTH", 4 * 1024 * 1024)
)

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.

Is this supposed to be added?

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.

Removed

Comment thread python/ray/serve/_private/replica.py Outdated

return healthy, message

def get_asgi_tracing_context(self, headers: List[Tuple[bytes, bytes]]):

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.

get_asgi_tracing_context needs to be omitted. Since tracing is not implemented in OSS

Comment thread python/ray/serve/_private/replica.py Outdated

return tracing_ctx

def get_grpc_tracing_context(self, context: grpc._cython.cygrpc._ServicerContext):

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.

get_grpc_tracing_context needs to be removed

Comment thread python/ray/serve/_private/replica.py Outdated
from ray.serve.handle import DeploymentHandle
from ray.serve.schema import EncodingType, LoggingConfig, ReplicaRank
from ray.util import metrics as ray_metrics
from ray.util.tracing.tracing_helper import _is_tracing_enabled

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.

i dont think we need this. _is_tracing_enabled is coming from core, which is saperate from serve's tracing

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.

Done

Comment thread python/ray/serve/_private/replica.py Outdated
# TODO(edoakes): populate this.
multiplexed_model_id="",
route=self._deployment_id.app_name,
tracing_context=self.get_grpc_tracing_context(context),

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.

set _is_tracing_enabled to None

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.

Done

request_id = (
headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8")
or generate_request_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.

Request ID extraction crashes when header is missing

High Severity

The request_id extraction in _direct_ingress_asgi calls .decode("utf-8") directly on the result of headers.get(). When the x-request-id header is not present, headers.get() returns None, and calling .decode() on None raises AttributeError: 'NoneType' object has no attribute 'decode'. This will crash every HTTP request that doesn't include the request ID header, which is the common case.

Fix in Cursor Fix in Web

self.queue.put_nowait(msg)

def close_queue(self):
self.queue.close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

close_queue method calls non-existent Queue.close()

Low Severity

The ASGIDIReceiveProxy.close_queue method calls self.queue.close(), but asyncio.Queue lacks a close() method. This unused method would raise an AttributeError if invoked, representing a latent bug.

Fix in Cursor Fix in Web

logger.info(
f"Recovered {self._protocol} port {port} for replica {replica_id} on node {self._node_id}"
)
return port

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Recovered ports not removed from available pool

High Severity

The update_port_if_missing method adds a recovered port to _allocated_ports but does not remove it from _available_ports. This can cause the same port to be allocated to multiple replicas. When a new replica calls allocate(), it may pop and assign a port that was already recovered for an existing replica, causing port conflicts and server startup failures.

Fix in Cursor Fix in Web

msg = (
f"Request {request_id} timed out after "
f"{self._http_options.request_timeout_s}s."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Timeout error message reports wrong timeout value

Low Severity

The timeout error message at line 2274 uses self._http_options.request_timeout_s instead of the actual request_timeout_s value that was used for the timeout (line 2246). When a client sends a custom timeout header, the error message will incorrectly report the default timeout value rather than the actual timeout that was applied, causing confusion during debugging.

Fix in Cursor Fix in Web

) = await allocate_and_start_server(
start_server_fn=start_grpc_server_fn,
protocol=RequestProtocol.GRPC,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

HTTP server not cleaned up when gRPC startup fails

Medium Severity

In _maybe_start_direct_ingress_servers, if the HTTP server starts successfully (lines 1667-1673) but the subsequent gRPC server startup fails after exhausting retries, the HTTP server task continues running and the HTTP port remains allocated. The function raises RuntimeError without canceling self._direct_ingress_http_server_task or releasing the HTTP port, causing a resource leak and orphaned server.

Fix in Cursor Fix in Web

if isinstance(message, Exception):
raise message

return message

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Duplicated ASGI receive proxy implementations

Medium Severity

The ASGIDIReceiveProxy class in direct_ingress_http_util.py duplicates logic from ASGIReceiveProxy, specifically for _get_default_disconnect_message, queue, and __call__. The _get_default_disconnect_message method is also unused within ASGIDIReceiveProxy. This introduces unnecessary code and increases maintenance overhead.

Fix in Cursor Fix in Web

] = []
self._refresh_autoscaling_deployments_cache()

self._last_broadcasted_target_groups: List[TargetGroup] = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unused variable _last_broadcasted_target_groups

Low Severity

The _last_broadcasted_target_groups instance variable is initialized to an empty list but never read or written to anywhere else in the codebase. This appears to be dead code or placeholder for unimplemented functionality.

Fix in Cursor Fix in Web

def get_target_groups(
self,
app_name: Optional[str] = None,
from_proxy_manager: bool = False,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unused parameter from_proxy_manager in get_target_groups

Low Severity

The from_proxy_manager parameter in get_target_groups is never used within the function body. The parameter is accepted but has no effect on the function's behavior, which can mislead callers into thinking it controls something.

Fix in Cursor Fix in Web

@eicherseiji

eicherseiji commented Jan 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Skipping new test added by #60270 that does not apply to DI mode

The test_root_path test validates proxy-dependent behavior where
serve_root_path from http_options is handled by the proxy's route
matching logic. In direct ingress mode, requests bypass the proxy
and go directly to replicas, so this test is not applicable.

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

@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 8 potential issues.

request_id = (
headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")).decode("utf-8")
or generate_request_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.

Null pointer error when request ID header is missing

High Severity

In _direct_ingress_asgi, the code attempts to decode the x-request-id header value without first checking if the header exists. When headers.get(SERVE_HTTP_REQUEST_ID_HEADER.encode("utf-8")) returns None (header not present), calling .decode("utf-8") on None raises an AttributeError. The or generate_request_id() fallback never executes because the exception occurs first. Most HTTP requests won't include this header, causing the direct ingress endpoint to crash.

Fix in Cursor Fix in Web

msg = (
f"Request {request_id} timed out after "
f"{self._http_options.request_timeout_s}s."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Timeout error message shows wrong timeout value

Low Severity

The timeout error message uses self._http_options.request_timeout_s instead of the actual request_timeout_s value that was used for the timeout. If a client sends a custom timeout via the x-request-timeout-seconds header, the error message will incorrectly display the default HTTP options timeout rather than the actual timeout that was applied.

Fix in Cursor Fix in Web

logger.info(
f"Recovered {self._protocol} port {port} for replica {replica_id} on node {self._node_id}"
)
return port

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Recovered ports not removed from available pool causes conflicts

High Severity

The update_port_if_missing method adds recovered ports to _allocated_ports but fails to remove them from _available_ports. After controller restart, the PortAllocator is reinitialized with all ports in _available_ports. When existing replica ports are recovered via update_port_if_missing, the ports remain in the heap. Subsequent calls to allocate() can return these already-allocated ports to new replicas, causing port conflicts where two replicas believe they own the same port.

Fix in Cursor Fix in Web

f"{self._http_options.request_timeout_s}s."
)
await send_http_response(msg, 408, send)
raise asyncio.CancelledError

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Queue counter leak when request cancelled before processing starts

Medium Severity

When an HTTP request times out or disconnects while waiting on the semaphore in _start_request, the _num_queued_requests counter is incremented at line 2190 but never decremented. The decrement at line 2209 only executes after successfully entering _start_request. When request_task.cancel() is called (lines 2259, 2269), the task is cancelled but not awaited, and CancelledError is immediately raised. If the task was blocked on the semaphore, the decrement never runs. Over time, this counter drift causes the replica to reject all requests due to hitting max_queued_requests.

Additional Locations (1)

Fix in Cursor Fix in Web

] = []
self._refresh_autoscaling_deployments_cache()

self._last_broadcasted_target_groups: List[TargetGroup] = []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unused instance variable never read after initialization

Low Severity

The instance variable _last_broadcasted_target_groups is initialized but never read or used anywhere in the codebase. It appears to be scaffolding for potential future caching/comparison logic (similar to _last_broadcasted_running_replica_infos in deployment_state.py), but since it's not actually used, it's dead code that adds confusion.

Fix in Cursor Fix in Web

"code": 1005,
}
else:
return {"type": "http.disconnect"}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Duplicated disconnect message method across two classes

Low Severity

The _get_default_disconnect_message method in ASGIDIReceiveProxy is an exact character-for-character copy of the same method in ASGIReceiveProxy. Both classes also share identical queue properties and nearly identical __call__ methods. This duplication increases maintenance burden and risks divergent bug fixes.

Fix in Cursor Fix in Web

"node_id": node_id,
"node_ip_address": node_ip_address,
}
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Duplicated ingress metrics initialization with proxy code

Low Severity

The methods _init_ingress_request_counter, _init_ingress_request_error_counter, _init_deployment_request_error_counter, _init_ingress_processing_latency_tracker, and _init_ingress_num_ongoing_requests_gauge duplicate the metrics initialization logic from proxy.py. These create identical metric names, descriptions, and tag keys, making maintenance harder.

Fix in Cursor Fix in Web

request: Any,
context: grpc._cython.cygrpc._ServicerContext,
):
raise NotImplementedError("unary_stream not implemented.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Stub method raises NotImplementedError in production path

Medium Severity

The _direct_ingress_unary_stream method is wired into the gRPC handler factory and will be called when streaming gRPC requests arrive, but it only raises NotImplementedError. This incomplete implementation exists in a production code path and could surprise users with unexpected errors.

Fix in Cursor Fix in Web

@eicherseiji
eicherseiji requested a review from aslonnie January 29, 2026 08:00
@abrarsheikh
abrarsheikh merged commit 792c4b8 into ray-project:master Jan 29, 2026
3 checks passed
ans9868 pushed a commit to ans9868/ray that referenced this pull request Feb 18, 2026
## Summary

This PR adds direct ingress functionality to Ray Serve, allowing
replicas to listen directly on ports for incoming traffic. This enables
deployments where each replica is individually addressable, which is
useful for Kubernetes ingress controllers and load balancers.

### Key changes:
- Add direct ingress HTTP utility for ASGI receive proxying
- Add direct ingress gRPC support (unary-unary handlers, health checks)
- Add replica response generator for disconnect detection
- Add node port manager for per-node port allocation
- Add direct ingress support to controller (target groups, port
allocation)
- Add direct ingress support to replica (HTTP/gRPC servers, graceful
shutdown)
- Add direct ingress constants and feature flag
(`RAY_SERVE_ENABLE_DIRECT_INGRESS`)
- Add integration and unit tests

The feature is disabled by default and can be enabled by setting
`RAY_SERVE_ENABLE_DIRECT_INGRESS=1`.

## Test plan
- [x] Run `test_direct_ingress.py` integration tests
- [x] Run `test_direct_ingress_standalone.py` standalone tests
- [x] Run `test_controller_direct_ingress.py` unit tests
- [x] Benchmarks

## Benchmarks

Validated using release image from
https://buildkite.com/ray-project/release/builds/76725#019be801-2dc9-45f7-bf1e-3d7ae41ff6d8
and `RAY_SERVE_ENABLE_DIRECT_INGRESS=1`, direct ingress provides 6x
reduction in TTFT and 1.8x improvement in throughput. Max concurrency
32/replica, 256 prompts/replica total. ITL 1024 OTL 256.
<img width="4171" height="2955" alt="httpproxy_vs_direct_ingress"
src="https://github.com/user-attachments/assets/2fddd7df-ad8a-4422-920a-d692993f846c"
/>

HTTPProxy (baseline) sweep:
https://gist.github.com/eicherseiji/630a83a0582aad22fb4655e6464a0038
Direct Ingress (this PR) sweep:
https://gist.github.com/eicherseiji/18d326524cbfe48e0353bfa8243bbb28
Toy load balancer used to test Direct Ingress:
https://gist.github.com/eicherseiji/cce80555ac2e8d04482483e5f8422509

---------

Signed-off-by: Seiji Eicher <[email protected]>
Signed-off-by: Future-Outlier <[email protected]>
Signed-off-by: Eugene Kim <[email protected]>
Co-authored-by: Han-Ju Chen (Future-Outlier) <[email protected]>
Signed-off-by: Adel Nour <[email protected]>
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]>
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.

4 participants