Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds support for dynamically reconfiguring the max_concurrent_batches parameter in Ray Serve's batching decorator. It replaces the static asyncio.Semaphore with a dynamic concurrency slot mechanism using asyncio.Condition and adds corresponding setter/getter methods along with unit tests and documentation updates. The review feedback suggests two key improvements: first, immediately notifying the concurrency condition when the limit is increased by scheduling an asynchronous task to avoid unnecessary delays; second, raising a ValueError instead of a TypeError when validating invalid values (less than 1) to maintain semantic correctness and consistency.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
Reviewed by Cursor Bugbot for commit f204ef7. Configure here.
abrarsheikh
left a comment
There was a problem hiding this comment.
what is the usecase for this?
|
|
||
| assert func._get_max_concurrent_batches() == 1 | ||
| tasks = [loop.create_task(func(i)) for i in range(4)] | ||
| await asyncio.sleep(0.2) |
There was a problem hiding this comment.
let's avoid using sleep in tests, it makes the test flaky. Try to make the tests deterministic by using synchronization patter, see other serve tests for example
| self._warn_if_max_batch_size_exceeds_max_ongoing_requests() | ||
| # Wake waiters so a raised limit takes effect now. reconfigure may run on a worker | ||
| # thread (RAY_SERVE_RUN_SYNC_IN_THREADPOOL), so schedule on the loop thread-safely. | ||
| asyncio.run_coroutine_threadsafe(self._notify_concurrency_waiters(), self._loop) |
There was a problem hiding this comment.
nit: worth adding a check here to see if the loop is running?
might come handy if shutdown is called before set_max_concurrent_batches
|
Thanks @abrarsheikh for the review - all comments adressed. The use case is that |
| task.add_done_callback(self._handle_completed_task) | ||
|
|
||
| @asynccontextmanager | ||
| async def _concurrency_slot(self): |
There was a problem hiding this comment.
i dont have strong reason to doubt that this is less performant than semaphore. But for sake of completeness could you run a micro benchmark to compare the perf of the two implementations? I prefer a black box perf benchmark aka test serve deployment with @serve.batch.
There was a problem hiding this comment.
Ran a black-box @serve.batch benchmark (concurrent load, changed only batching.py) - throughput and p50/p99 are within noise. It seems that the Condition path is marginally slower on the uncontended path and slightly faster on the contended (both far below any real per-request cost - so imo there's no measurable impact)
There was a problem hiding this comment.
share the results along with explanation of the XP setup
There was a problem hiding this comment.
Setup
local single node (10 vCPU), Ray 2.54.1. Only batching.py differsbetween the two runs asyncio.Semaphore on main vs the Condition + counter from this PR
Black box
real @serve.batch deployment driven via a DeploymentHandle under concurrent load, max_batch_size=1, max_concurrent_batches=64. OLD and NEW run back-to-back, 6 rounds × 2 trials:
- Semaphore (from main): 569 +/- 15 req/s
- Condition (PR): 582 +/- 30 req/s (+0.7%, within noise, p50/99 latecy too)
... BUT I've played a little bit more with those tests after your last comments, and there is one flag to raise - fairness. asyncio.Semaphore is FIFO-fair (grants slots in FIFO order since this fix) - it no longer lets a fresh acquirer "barge" ahead of queued waiters. The Condition + wait_for(predicate) + notify gate has no such ordering (a freshly arriving batch can take a freed slot before a just-notified waiter re-acquires the lock). In an isolated stress test (64 callers, max_concurrent_batches=4, tight loop) that starves the unlucky waiters: max wait ~530 ms vs Semaphore's ~40 ms. It didn't surface in the real @serve.batch black box tests
Note
If we want to close "fairness" gap, together with runtime tunability, then anyio.CapacityLimiter looks like solution. It's FIFO-fair and runtime-resizable (total_tokens, up/down) and already a Serve's dependency, wdyt? happy to prototype and test that.
There will be slight batch overhead for CapacityLimiter:
- CapacityLimiter ~16 µs/batch overhead
- Semaphore ~0.6 µs
- Condition ~2.4 µs
import anyio
# instead of asyncio.Semaphore(...) / the Condition+counter:
self._limiter = anyio.CapacityLimiter(max_concurrent_batches)
# the gate - instead of `async with self._concurrency_slot():`
async with self._limiter:
... # run the batch
# runtime-tunable - instead of set_max_concurrent_batches() + notify_all:
self._limiter.total_tokens = new_max_concurrent_batches # up or down, stays FIFO-fairThere was a problem hiding this comment.
sounds good could you try that please
There was a problem hiding this comment.
done (and rebased) - switched the gate to anyio.CapacityLimiter
Changed
asyncio.Semaphore->anyio.CapacityLimiter: FIFO-fair and resizable in both directions, the setter is now justtotal_tokens(applied on the loop thread - reconfigure may run on a worker thread under
RAY_SERVE_RUN_SYNC_IN_THREADPOOL). Net diff smaller than the Condition version- added tests: lowering the limit (in-flight batches drain, no preemption) + non-int rejection
- floored
anyio>=4.2in the serve extras (so far an undeclared transitive dep via starlette): anyio 4.2.0 fixedtotal_tokensfailing to wake waiting tasks - on older versions batch admission hangs after a
limit change. CI lockfiles already pin 4.13, llm extras already floor at 4.5
Black box (same setup as before, OLD and NEW back-to-back, 6 rounds × 2 runs)
max_batch_size=1, max_concurrent_batches=64: Semaphore 526 +/- 32 vs CapacityLimiter 524 +/- 33 req/s (within noise, p50/p99 too)max_batch_size=8, max_concurrent_batches=2, ~5ms work: 585 +/- 51 vs 593 +/- 52 req/s (within noise)
Isolated, the gate itself is ~16 µs/batch vs ~0.6 µs for the Semaphore - amortized over the whole batch and against ms-scale batch work
|
This pull request has been automatically marked as stale because it has not had You can always ask for help on our discussion forum or Ray's public slack channel. If you'd like to keep this open, just leave any comment, and the stale label will be removed. |
de67441 to
4251b6b
Compare
|
@arturez this now has merge conflicts with master; could you rebase? @YashwanthRanjanSingaravel you approved #66321 in |
Lets max_concurrent_batches be updated at runtime like max_batch_size and batch_wait_timeout_s. The concurrency gate becomes anyio.CapacityLimiter: FIFO-fair and resizable in both directions. Closes ray-project#64036. Notes: - Floors anyio at 4.2 in the serve extras and requirements.txt (previously an undeclared transitive dep via starlette): anyio 4.2.0 fixed the total_tokens setter failing to wake waiting tasks, and enabled CapacityLimiter construction outside an event loop thread; on older anyio, batch admission hangs after a limit change. CI lockfiles already pin 4.13; the llm extra already floors anyio at 4.5. - max_concurrent_batches < 1 now raises ValueError (was TypeError), matching max_batch_size validation. Signed-off-by: Artur Baćmaga <[email protected]>
4251b6b to
3024122
Compare
|
Hey @johntaylor-cell @YashwanthRanjanSingaravel rebased onto master (the only conflict was related to |
…#67877) ## Description `@serve.batch` forms a batch first and takes a `max_concurrent_batches` permit afterwards. `_process_batches` calls `wait_for_batch()`, then starts a task that waits on the semaphore in `_process_sub_batches` ([`batching.py` L498-L532](https://github.com/ray-project/ray/blob/17e1131/python/ray/serve/batching.py#L498-L532)). While every permit is in use, the loop keeps closing a batch each time `batch_wait_timeout_s` passes, and each of those batches then waits for a permit holding only the requests that arrived in that window. Requests that arrive while the replica is busy are therefore run in many small batches, one after another, instead of together. With `max_batch_size=10`, `batch_wait_timeout_s=0.01`, `max_concurrent_batches=1` and a batch function that takes 0.5 s, one request followed by 10 requests 30 ms apart (script below): | | batch sizes | time for all 11 requests | |---|---|---| | master 17e1131 | `[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]` | 5.53 s | | this PR | `[1, 10]` | 1.02 s | This PR takes the permit in `_process_batches` before calling `wait_for_batch()`, and releases it in `_handle_completed_task`. Requests that arrive while every permit is in use stay in the queue, and the next batch is formed from all of them when a permit is free. `_process_sub_batches` still runs all sub-batches of one batch under one permit. Taking the permit first would make one case slower if nothing else changed: `wait_for_batch()` starts the `batch_wait_timeout_s` timer when it takes the first request from the queue, so a request that waited for a permit would then wait for the timeout again. With `batch_wait_timeout_s=1.0` and a batch function that takes 0.5 s, a lone request arriving 0.2 s into the first batch's run finished 1.81 s after it arrived, against 1.50 s on master. To keep master's timing, each request now records when it was queued (`_SingleRequest.enqueue_time`), and the timeout counts from the first request's arrival. With that change the same request finishes in 1.50 s, as on master, and a request that already waited longer than the timeout goes out with whatever else is queued as soon as a permit is free. The batch wait time metric still measures from when the batch starts forming, as before. If `wait_for_batch()` or starting the batch task raises, or the loop is cancelled while it waits, the permit is released before the exception propagates. A batch task that fails or is cancelled releases its permit in its done callback, because asyncio runs done callbacks for cancelled tasks too, including a task cancelled before it starts. While the queue is empty, the loop now holds one permit as it waits for the first request. That permit becomes the next batch's permit, so no more than `max_concurrent_batches` batches run at once, as before. Holding it while idle delays nothing, because a batch cannot start without a permit. ## Related issues None found. Two open PRs change the same loop: #64040 replaces the semaphore with an `anyio.CapacityLimiter` to add a setter, and #64595 rewrites `_process_batches` for multiplexed queues and acquires the semaphore after `wait_for_batch()`. This PR conflicts with both. With #64595's semaphore shared across queues, a loop that holds a permit while its queue is empty would block the other queues, so that PR would need the acquire placed differently. I can rebase onto either one if it lands first. ## Additional information Tests added to `python/ray/serve/tests/unit/test_batching.py`: - `test_requests_arriving_while_batches_run_form_one_batch`: one request starts a batch that holds the only permit, and 5 more requests arrive 50 ms apart (longer than `batch_wait_timeout_s`). The batch sizes must be `[1, 5]`. On master they are `[1, 1, 1, 1, 1, 1]`. - `test_batch_timeout_counts_time_waiting_for_a_permit`: a request that waited 1.2 s for a permit, with `batch_wait_timeout_s=1.0`, starts less than 0.5 s after the permit is released. It passes on master, and fails if the permit is taken first without the timer change, where the batch starts 1.0 s after the release. The 0.5 s limit leaves room for slow CI machines. Commands, run locally on macOS arm64 with the nightly wheel and `setup-dev.py`: - `pytest python/ray/serve/tests/unit/test_batching.py`: 93 passed. On master 17e1131: 92 passed, and `test_requests_arriving_while_batches_run_form_one_batch` fails. - `pytest python/ray/serve/tests/unit` (without `test_http_util.py`, which does not import in my setup): 273 tests fail on this branch and 274 on master. They are the same tests except for the new one, which fails only on master. Most of them are in `test_deployment_state.py`. - I could not run `python/ray/serve/tests/test_batching.py`. Its first test hangs in my setup on master as well (stopped after 4 minutes), so I am relying on CI for it. - `pre-commit run` on the changed files: passed. <details><summary>Repro script</summary> ```python import asyncio, time from typing import List from ray import serve import ray.serve.context from ray.serve._private.common import DeploymentID, ReplicaID from ray.serve._private.config import DeploymentConfig ray.serve.context._set_internal_replica_context( replica_id=ReplicaID(unique_id="t", deployment_id=DeploymentID(name="t")), servable_object=None, _deployment_config=DeploymentConfig(max_ongoing_requests=100), rank=0, world_size=1) sizes = [] @serve.batch(max_batch_size=10, batch_wait_timeout_s=0.01, max_concurrent_batches=1) async def f(xs: List[int]): sizes.append(len(xs)) await asyncio.sleep(0.5) return xs async def main(): tasks = [asyncio.create_task(f(0))] await asyncio.sleep(0.05) # batch 1 is now executing (0.5 s) for i in range(1, 11): # 10 requests arrive while it runs tasks.append(asyncio.create_task(f(i))) await asyncio.sleep(0.03) await asyncio.gather(*tasks) print("batch sizes:", sizes) t0 = time.perf_counter() asyncio.run(main()) print(f"all 11 requests done in {time.perf_counter() - t0:.2f} s") ``` </details> --------- Signed-off-by: William Guo <[email protected]>

Why are these changes needed?
@serve.batchlets you updatemax_batch_sizeandbatch_wait_timeout_sat runtime (typically fromreconfigure/user_config), but notmax_concurrent_batches— it was baked into a fixedasyncio.Semaphoreat queue construction, which can't be resized.This swaps that semaphore for a counter gated by an
asyncio.Conditionthat reads the livemax_concurrent_batcheson each admission, and addsset_max_concurrent_batches(and a getter) wired through_LazyBatchQueueWrapperand the decorator, mirroring the existing two setters. Raising the limit admits queued batches as in-flight ones complete; lowering it takes effect as they drain (in-flight batches are never cancelled). The setter rejects values< 1, which would otherwise leave the gate admitting nothing.Related issue number
Closes #64036
Checks
test_batching.py(limit enforced, runtime update, invalid-value rejection)dyn-req-batch.md,batching_guide.py)