Repository navigation
[Serve] Optimize replica routing request data structures - #60139
Conversation
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request significantly optimizes the replica routing mechanism in Ray Serve by refactoring data structures and lookup logic. The changes introduce dictionary-based indices (_pending_requests_by_id, _pending_requests_by_model_id) for O(1) lookups of pending requests, replacing previous O(N) iterations over deques. Lazy cleanup of completed futures is implemented to prevent memory leaks, and a cached list of replicas (_replicas_list) is maintained to avoid redundant list conversions. These improvements enhance the efficiency of request matching, fulfillment, and replica selection, leading to better performance, especially in high-throughput or multiplexed model scenarios. The code is well-commented, explaining the rationale behind the optimizations.
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
harshit-anyscale
left a comment
There was a problem hiding this comment.
great improvements, nice work!
left some comments, else LGTM
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
Signed-off-by: abrar <[email protected]>
## Why are these changes needed? The `test_router_queue_len_metric` test was flaky because the router queue length gauge has a 100ms throttle (`RAY_SERVE_ROUTER_QUEUE_LEN_GAUGE_THROTTLE_S`) that can skip updates when they happen too quickly. When replica initialization sets the gauge to 0 and a request immediately updates it to 1, the second update may be throttled, causing the test to see 0 instead of 1. ## Related issue number Fixes flaky test introduced in #59233 after #60139 added throttling. --------- Signed-off-by: Seiji Eicher <[email protected]>
…68085) ## Description Ray Serve request routers never free finished multiplexed requests from `_pending_requests_by_model_id`, so each one keeps its `args`/`kwargs` alive. `_remove_pending_request_from_indices` only cleans `_pending_requests_by_id`. The model ID index relies on lazy cleanup that only `FIFOMixin` runs, and only when a later request for the same model ID is fulfilled. Before this fix: - `FIFOMixin` routers, including the default `PowerOfTwoChoicesRequestRouter`, kept the last request of every model ID, so memory grew with the number of distinct model IDs. - Routers without `FIFOMixin` (`ConsistentHashRouter`, `KVAwareRouter`, `PrefixCacheAffinityRouter`, custom routers) kept every multiplexed request, so memory grew with traffic. With Serve LLM's KV-aware or prefix-aware routing, this happens on every LoRA request. - Cancelling a request didn't clean the model ID index in any router. **Fix:** every fulfilled or cancelled request already calls `_remove_pending_request_from_indices` once its future is done. That method now pops done entries from the front of the request's model ID deque, and drops the key when the deque is empty. The cost stays amortized O(1), and routing behavior doesn't change. ## Related issues - Related to #60139, which introduced the lazy cleanup. - Related to #67095, which extends the same index to lists of model IDs and will need the same cleanup per ID. ## Additional information Standalone repro (script below). Run it on master vs. this branch. Entries left in `_pending_requests_by_model_id` after 200 finished requests over 50 model IDs, 1 MiB args each: | Router | Fulfilled (master → PR) | Cancelled (master → PR) | |---|---|---| | `PowerOfTwoChoicesRequestRouter` | 50 → 0 | 200 → 0 | | `ConsistentHashRouter` | 200 → 0 | 200 → 0 | <details> <summary><code>repro_router_leak.py</code></summary> ```python """Count finished multiplexed requests left in `_pending_requests_by_model_id`. Run with the Ray you want to check, e.g. on master vs. this PR's branch: python repro_router_leak.py """ import asyncio from ray.serve._private.common import ( DeploymentHandleSource, DeploymentID, RequestMetadata, ) from ray.serve._private.request_router import PendingRequest from ray.serve._private.request_router.pow_2_router import ( PowerOfTwoChoicesRequestRouter, ) from ray.serve._private.test_utils import FakeRunningReplica from ray.serve._private.utils import generate_request_id from ray.serve.experimental.consistent_hash_router import ConsistentHashRouter NUM_REQUESTS = 200 NUM_MODEL_IDS = 50 PAYLOAD_BYTES = 1024 * 1024 async def run(router_cls, cancel: bool): model_ids = [f"model-{i}" for i in range(NUM_MODEL_IDS)] router = router_cls( deployment_id=DeploymentID(name="repro"), handle_source=DeploymentHandleSource.REPLICA, self_actor_id="repro-actor", self_actor_handle=None, use_replica_queue_len_cache=False, ) replica = FakeRunningReplica("r1", model_ids=set(model_ids)) replica.set_queue_len_response(0) router.update_replicas([replica]) for i in range(NUM_REQUESTS): request = PendingRequest( args=[b"x" * PAYLOAD_BYTES], kwargs={}, metadata=RequestMetadata( request_id=generate_request_id(), internal_request_id=generate_request_id(), multiplexed_model_id=model_ids[i % NUM_MODEL_IDS], ), ) task = asyncio.create_task(router._choose_replica_for_request(request)) if cancel: await asyncio.sleep(0) task.cancel() await asyncio.gather(task, return_exceptions=True) for task in list(router._routing_tasks): task.cancel() await asyncio.gather(*router._routing_tasks, return_exceptions=True) entries = [pr for dq in router._pending_requests_by_model_id.values() for pr in dq] assert all(pr.future.done() for pr in entries) return len(entries), len(entries) * PAYLOAD_BYTES / 2**20 async def main(): print( f"{NUM_REQUESTS} finished requests over {NUM_MODEL_IDS} model IDs, " f"{PAYLOAD_BYTES // 2**20} MiB args each. Entries left in the index:" ) for router_cls in (PowerOfTwoChoicesRequestRouter, ConsistentHashRouter): for cancel in (False, True): entries, mib = await run(router_cls, cancel) ending = "cancelled" if cancel else "fulfilled" print(f" {router_cls.__name__:<32}{ending:<11}{entries:>4} ({mib:.0f} MiB)") if __name__ == "__main__": asyncio.run(main()) ``` </details> --------- Signed-off-by: GNITOAHC <[email protected]>
O(1) Pending Request Lookups
_pending_requests_by_idand_pending_requests_by_model_id) for fast lookupsCached Replica List
_replicas_listcache to avoid O(n) dict-to-list conversion on every routing iterationupdate_replicas()oron_replica_actor_died()Lazy Cleanup Strategy
_pending_requests_by_model_idduring lookups using O(1)popleft()Optimized Retry Insertion
_insert_pending_request_sorted()helperSimplified
pow_2_routerself._replicas[chosen_id]instead of building temporary maprandom.sample→ Direct Selectioncommon.py)request_router.py,constants.py)flamegraph of the router after all the optimization
