Skip to content

[serve] Take the max_concurrent_batches permit before forming a batch - #67877

Merged
abrarsheikh merged 2 commits into
ray-project:masterfrom
wguo7:fix/serve-batch-slot-before-batch
Nov 6, 2026
Merged

abrarsheikh merged 2 commits into
ray-project:masterfrom
wguo7:fix/serve-batch-slot-before-batch

Conversation

@wguo7

@wguo7 wguo7 commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

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). 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.
Repro script
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")

_process_batches formed a batch and then waited for a semaphore permit in
the batch task. While every permit was in use, the loop kept closing a
batch each batch_wait_timeout_s, so requests arriving at a busy replica ran
as many small batches one after another. Take the permit before
wait_for_batch() and release it when the batch task completes, so those
requests stay queued and form one batch.

Count batch_wait_timeout_s from the first request's arrival, so a request
that waited for a permit does not wait for the timeout again.

Signed-off-by: William Guo <[email protected]>
@wguo7
wguo7 requested a review from a team as a code owner November 5, 2026 21:19

@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 updates Ray Serve's batching mechanism to acquire the concurrency semaphore before forming a batch, rather than during sub-batch processing. This allows requests arriving while all permits are in use to join a single batch, and ensures that batch timeouts account for the time requests spend waiting for a permit. A review comment correctly identifies a potential semaphore leak if a synchronous exception occurs during batch splitting or task creation, and suggests wrapping the entire block in a try-except block to safely release the permit.

Comment on lines +513 to 532
await self.semaphore.acquire()
try:
batch, _ = await self.wait_for_batch()
except BaseException:
self.semaphore.release()
raise

# Split batch by multiplexed_model_id to ensure requests for different
# models are processed in separate batches. This is necessary when using
# model multiplexing with batching, as a single batch containing requests
# for different models would not work correctly.
sub_batches = self._split_batch_by_model_id(batch)

# Process all sub-batches together under a single semaphore permit.
# Process all sub-batches together under the permit taken above.
# This ensures sub-batches from the same original batch run concurrently
# rather than being serialized by the semaphore.
# rather than being serialized by the semaphore. The permit is released
# in _handle_completed_task.
promise = self._process_sub_batches(func, sub_batches)
task = asyncio.create_task(promise)
self.tasks.add(task)

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

If a synchronous exception is raised during batch splitting or task creation (e.g., in _split_batch_by_model_id or _process_sub_batches), the semaphore permit acquired at line 513 will be leaked because the try...except BaseException block only wraps wait_for_batch(). Wrapping the entire sequence of operations from wait_for_batch up to adding the task to self.tasks ensures that the semaphore is safely released if any unexpected exception occurs before the task's done callback is registered.

Suggested change
await self.semaphore.acquire()
try:
batch, _ = await self.wait_for_batch()
except BaseException:
self.semaphore.release()
raise
# Split batch by multiplexed_model_id to ensure requests for different
# models are processed in separate batches. This is necessary when using
# model multiplexing with batching, as a single batch containing requests
# for different models would not work correctly.
sub_batches = self._split_batch_by_model_id(batch)
# Process all sub-batches together under a single semaphore permit.
# Process all sub-batches together under the permit taken above.
# This ensures sub-batches from the same original batch run concurrently
# rather than being serialized by the semaphore.
# rather than being serialized by the semaphore. The permit is released
# in _handle_completed_task.
promise = self._process_sub_batches(func, sub_batches)
task = asyncio.create_task(promise)
self.tasks.add(task)
await self.semaphore.acquire()
try:
batch, _ = await self.wait_for_batch()
# Split batch by multiplexed_model_id to ensure requests for different
# models are processed in separate batches. This is necessary when using
# model multiplexing with batching, as a single batch containing requests
# for different models would not work correctly.
sub_batches = self._split_batch_by_model_id(batch)
# Process all sub-batches together under the permit taken above.
# This ensures sub-batches from the same original batch run concurrently
# rather than being serialized by the semaphore. The permit is released
# in _handle_completed_task.
promise = self._process_sub_batches(func, sub_batches)
task = asyncio.create_task(promise)
self.tasks.add(task)
except BaseException:
self.semaphore.release()
raise

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 in 2ddc36c. The try block now covers wait_for_batch(), the split by model ID, building the coroutine and asyncio.create_task(). If any of them raises, the except BaseException releases the permit and re-raises. Each batch gets one task, which runs all of its sub-batches under the one permit. Once create_task() returns, that task owns the permit, and its done callback _handle_completed_task releases it. The callback is registered a few lines later, outside the try, with no await in between, so the permit is released once on either path.

@abrarsheikh abrarsheikh 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.

lg2m, good fix

@abrarsheikh abrarsheikh added the go add ONLY when ready to merge, run all tests label Nov 5, 2026
@abrarsheikh
abrarsheikh enabled auto-merge (squash) November 5, 2026 23:20
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Nov 6, 2026
@abrarsheikh
abrarsheikh merged commit ab7deff into ray-project:master Nov 6, 2026
7 of 8 checks passed
johntaylor-cell added a commit to johntaylor-cell/ray that referenced this pull request Nov 6, 2026
The test used a 1 ms wait_for as a proxy for "t1's batch has formed". On
Windows the asyncio clock ticks every 15.6 ms, so that timer fires on the
next loop iteration. Since ray-project#67877 frees the batch permit in a done
callback, the loop is a few iterations behind and t2 joins t1's batch.
Wait for t1's batch to start instead.

Signed-off-by: john.taylor <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
abrarsheikh pushed a commit that referenced this pull request Nov 6, 2026
)

The test used a 1 ms wait_for as a proxy for "t1's batch has formed". On
Windows the asyncio clock ticks every 15.6 ms, so that timer fires on
the next loop iteration. Since #67877 frees the batch permit in a done
callback, the loop is a few iterations behind and t2 joins t1's batch.
Wait for t1's batch to start instead.

Signed-off-by: john.taylor <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests serve Ray Serve Related Issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants