Skip to content

[Serve] Let multiplexed models fill batches independently - #64595

Open
angryturtlebro wants to merge 9 commits into
ray-project:masterfrom
angryturtlebro:fix-serve-multiplexed-batching
Open

angryturtlebro wants to merge 9 commits into
ray-project:masterfrom
angryturtlebro:fix-serve-multiplexed-batching

Conversation

@angryturtlebro

@angryturtlebro angryturtlebro commented Jul 8, 2026 •

Copy link
Copy Markdown

Description

This is a follow-up to #59334 for the batching + multiplexing behavior reported in #56633.

#59334 prevents requests for different multiplexed model IDs from being processed in the same user batch, but requests still enter a shared batch queue before being split by model ID. When multiple models receive traffic concurrently, that shared queue can fill with requests for different models, so each model receives only a partial sub-batch.

This PR gives each multiplexed model ID its own batch queue, so each model fills its own batch up to max_batch_size or until its own batch_wait_timeout_s. Requests without a model ID use a default queue, as before.

Related issues

Related to #56633
Follow-up to #59334

Additional information

How it works

  • _LazyBatchQueueWrapper keeps one _BatchQueue per model ID. Each queue has its own semaphore, so max_concurrent_batches applies to each model ID.
  • As on master since [serve] Take the max_concurrent_batches permit before forming a batch #67877, each queue takes a permit before it forms a batch, and the permit is released when the batch task finishes. Requests that arrive while every permit is in use wait in the queue and go into the next batch.
  • A model queue is removed once it has no queued, batching, or running requests. The default queue is never removed.
  • The wrapper and its queues share one _BatchConfig, so set_max_batch_size and set_batch_wait_timeout_s update existing queues, new queues, and a queue being created at the same time. A batch that's already forming keeps the size and timeout it started with.
  • The wrapper creates the metric objects once and shares them across its queues. Metric names and labels are unchanged (there's no model-ID label). serve_batch_queue_length reports the requests still queued across all the wrapper's queues, excluding requests already dequeued into a batch.
  • The wrapper logs the max_ongoing_requests warning, when it applies, on its first queue and on set_max_batch_size calls. A recreated model queue doesn't log it again.

Behavior changes

  • max_concurrent_batches now applies to each model ID. Previously, the sub-batches split from one mixed batch shared a single permit. Now the total across models can exceed max_concurrent_batches, even at the default of 1. I updated the batch() docstring and both docs pages to say so.
  • serve_batch_wait_time_ms is recorded once per model batch instead of once per shared batch.
  • serve_batch_queue_length is also recorded after a batch forms, and on enqueue while the queue waits for a permit. On master it is only recorded while a batch is filling, so it goes stale during that wait. In a microbenchmark with metrics on, this adds about 2 µs of CPU per request for back-to-back sequential requests and for 100-model bursts, and about 0.4 µs for 8-model bursts. Runs with a batch wait or gaps between requests were too noisy to show it.
  • _get_curr_iteration_start_times and _get_handling_task_stack aggregate across queues, and _is_batching_task_alive requires every queue's task to be alive.

Trade-offs and limitations

  • With sparse traffic, a model's queue may be removed and recreated between requests. Benchmarks of that cost and of batch sizes are in this comment.

Related work

  • [Serve] Add set_max_concurrent_batches setter to @serve.batch #64040 adds a set_max_concurrent_batches setter and replaces the batch queue semaphore with a capacity limiter. With this PR each model queue has its own semaphore, so the setter would store the new value in the shared _BatchConfig for new queues and update the limit of every existing queue on the event loop. This will need reconciliation if both PRs merge.
  • I searched open and closed PRs and issues for batching and multiplexing. [Serve] Make batching work with multiplexing #59334 (merged) is the change this follows up on; I found no other PR that adds per-model batch queues.

Testing

Run locally on macOS (Python 3.10, nightly wheel with setup-dev.py):

python -m pytest --import-mode=importlib python/ray/serve/tests/unit/test_batching.py        # 110 passed
python -m pytest --import-mode=importlib python/ray/serve/tests/test_batching.py             # 23 passed
python -m pytest --import-mode=importlib python/ray/serve/tests/test_multiplex.py            # 20 passed
python -m pytest --import-mode=importlib python/ray/serve/tests/test_handle_cancellation.py  # 10 passed
python -m pytest --import-mode=importlib python/ray/serve/tests/test_http_cancellation.py    # 6 passed
python -m pytest --import-mode=importlib python/ray/serve/tests/unit/test_build_app.py -k multiplex  # 5 passed
python -m pytest --import-mode=importlib python/ray/serve/tests/test_metrics_3.py -k batching     # 1 passed
pre-commit run --files python/ray/serve/batching.py python/ray/serve/tests/unit/test_batching.py python/ray/serve/tests/test_multiplex.py  # passed

The new unit tests cover per-model batching and concurrency, idle cleanup including after cancelled requests, queue recreation, shared metrics and the queue-length gauge, the setters, the warning, and the debug helpers. test_batch_setter_during_queue_construction_is_kept simulates a setter call during queue creation without starting a thread. test_multiplexed_with_batching_fills_batches_per_model_id in test_multiplex.py sends interleaved requests and checks one full batch of 3 per model; it fails with master's batching.py.

AI assistance

This PR was developed with AI assistance (Claude Code, with OpenAI Codex as a second reviewer). I reviewed every changed line and ran the tests above locally.

@angryturtlebro
angryturtlebro requested a review from a team as a code owner July 8, 2026 07:14

@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 refactors Ray Serve's batching mechanism for multiplexed models by replacing the single-queue sub-batching approach with separate, per-model queues managed dynamically within _LazyBatchQueueWrapper. Idle model-specific queues are automatically cleaned up to conserve resources. A critical race condition was identified in the is_idle() check, where a queue could be prematurely shut down and cancel a background task while it is actively accumulating a batch in wait_for_batch(). A fix is suggested to track the currently accumulating batch and include it in the idle check.

Comment thread python/ray/serve/batching.py Resolved
Route multiplexed Serve requests through per-model batch queues so each model can fill its own batch instead of sharing one queue with other model IDs.

Preserve the global max_concurrent_batches limit across model queues, and add regression coverage for full per-model batches, concurrency limits, and idle queue cleanup.

Signed-off-by: angryturtlebro <[email protected]>
@angryturtlebro
angryturtlebro force-pushed the fix-serve-multiplexed-batching branch from e3f60e2 to fdedbe0 Compare July 8, 2026 07:19

@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 using default effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit fdedbe0. Configure here.

Comment thread python/ray/serve/batching.py Resolved
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue community-contribution Contributed by the community labels Jul 8, 2026
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had
any activity for 14 days. It will be closed in another 14 days if no further activity occurs.
Thank you for your contributions.

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.

@github-actions github-actions Bot added the stale The issue is stale. It will be closed within 7 days unless there are further conversation label Jul 23, 2026
@angryturtlebro

Copy link
Copy Markdown
Author

Would still like this looked at

@github-actions github-actions Bot added unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it. and removed stale The issue is stale. It will be closed within 7 days unless there are further conversation labels Jul 24, 2026
abrarsheikh pushed a commit that referenced this pull request Oct 13, 2026
## Description

When a single-input batched handler uses `batch_size_fn`, passing its
input by keyword leaves no positional argument for `_compute_batch_size`
to read. The resulting `IndexError` escapes batch assembly. A local
Serve deployment reproduces positional success, keyword timeout, then
another positional timeout because the batching task has stopped.

Read the first payload value from the existing flattened argument
representation, after `self` has already been removed. This preserves
successful positional calls and supports a single explicitly supplied
input passed by keyword, including keyword-only parameters. Existing
multi-input positional calls remain supported. Multi-input keyword calls
and variadic keyword (`**kwargs`) handlers are rejected before queueing
because their flattened keyword order is not stable across a batch, and
omitting a defaulted input is rejected because there is no explicit
value to size. These errors affect only the caller and do not stop the
batching worker. General callback-error isolation remains outside this
change.

The tests exercise functions and bound methods, coroutine and streaming
handlers, mixed positional/keyword arrivals in both orders, keyword-only
signatures, oversized keyword input recovery, omitted defaults,
second-keyword-first ordering, variadic keyword signatures, positional
multi-input compatibility, and worker survival after invalid requests.
The batching guide describes the supported call forms.

## Related work and attribution

This addresses the finding already raised in [the review of
#59059](#59059 (comment));
it is not a new discovery. Searches for custom sizing and keyword/kwargs
fixes found no matching open PR. #66141 fixes callback-error isolation
and explicitly excludes keyword compatibility. #64595 restructures
per-model queues but leaves this payload extraction unchanged; it
touches the same file and may require rebasing.

## Validation

macOS arm64, Python 3.12.14, official Ray `3.0.0.dev0` wheel at
`39882c660a6d7b579e39d724ce85d9074d6180fb`, with the branch's current
Python Serve sources linked into the environment. Because the branch
includes newer master changes, the source and wheel revisions are not
exact; the focused suite required a runner-local shim for a newer
test-fixture helper.

```bash
.venv/bin/python - <<'PYTEST'
import ray, pytest
raise SystemExit(pytest.main([
    '--import-mode=importlib',
    'python/ray/serve/tests/unit/test_batching.py',
    '--tb=short', '-q',
]))
PYTEST
```

- 15 keyword regressions from the original change fail on the original
implementation; seven review-fix cases fail before their respective
fixes.
- Full batching unit file: **87 passed**, including 26 cases added by
this PR.
- Real CPU-only local Serve deployment: positional and keyword requests
succeed; invalid omitted-default, multi-input-keyword, and
variadic-keyword calls return bounded `TypeError`s; a subsequent valid
request succeeds and all batching tasks remain alive.
- All hooks applicable to the changed files pass; `git diff --check`
passes. Vale is excluded for this documentation path and its environment
separately failed to compile on this Mac because the C++ `cassert`
header was unavailable.
- The test runner prints pending-task teardown diagnostics that were
already present in the earlier 61-test baseline; the run exits
successfully. The local demo logs include the existing
batch-size/ongoing-request advisory and Ray shutdown messages.
- Independent Astra Low reviews of each exact review-fix diff found no
actionable issues in argument mapping, exception propagation, unresolved
futures, cancellation, streaming, or worker survival.

No GPU performance, full-Ray suite, docs build, or upstream CI result is
claimed.

---------

Signed-off-by: Jayesh Suyal <[email protected]>
Signed-off-by: YashwanthRanjanSingaravel <[email protected]>
Co-authored-by: YashwanthRanjanSingaravel <[email protected]>
…exed-batching

Signed-off-by: angryturtlebro <[email protected]>

# Conflicts:
#	python/ray/serve/batching.py
Restore master's batch formation logic while retaining current-batch
tracking and aggregate queue-length reporting. Use the current batch for
idle checks and cancellation, require every queue's batching task to be
alive, and snapshot queues in the batch setters.

Simplify the tests and add coverage for queue mutation during a setter.

Signed-off-by: angryturtlebro <[email protected]>
@angryturtlebro

Copy link
Copy Markdown
Author

Updated this PR:

  • Merged master through b575a6d, retaining the batch_size_fn keyword validation from [Serve] Support keyword inputs with custom batch sizing #66321.
  • Simplified batch tracking and tests, aggregated the queue-length metric, and made the liveness check require every queue's batching task to be alive.
  • Added queue snapshots in the batch setters to prevent dictionary-iteration errors during reconfigure.
  • Updated the description to explain that each model's batch takes its own max_concurrent_batches permit.

Ready for review.

@angryturtlebro

Copy link
Copy Markdown
Author

Hi @abrarsheikh I noticed you working on other pr's related to this. Would you be able to take a look or point me in the right direction for this work? Thanks!

@angryturtlebro

Copy link
Copy Markdown
Author

@harshit-anyscale @akyang-anyscale
It looks like you reviewed the work this is based on. Would you be able to give this a look?

@angryturtlebro

Copy link
Copy Markdown
Author

@abrarsheikh Is there anything I need to do for this to get reviewed? Happy to do more work if needed just not sure how to get a reviewer added

@abrarsheikh

Copy link
Copy Markdown
Contributor

@YashwanthRanjanSingaravel @johntaylor-cell could you review this please

abrarsheikh pushed a commit that referenced this pull request Nov 6, 2026
…#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]>
Comment thread python/ray/serve/batching.py Outdated
self.max_concurrent_batches = max_concurrent_batches
self.handle_batch_func = handle_batch_func
self.batch_size_fn = batch_size_fn
self.semaphore = asyncio.Semaphore(max_concurrent_batches)

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.

With the default max_concurrent_batches=1, this runs batches for different models one at a time, while master runs them concurrently. 3 models: 3.1s vs 1.1s. Give each queue its own semaphore (semaphore=None in get_queue) so the limit is per model?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed, each model queue has its own semaphore now, so max_concurrent_batches is per model ID and different models run concurrently again with the default of 1. This is also required after merging master. #67877 takes the permit before forming a batch, so with a shared semaphore an idle model queue would block every other model.

Added test_multiplexed_batch_queues_limit_concurrency_per_model for it, and reverted the max_concurrent_batches=3 I had added to the context-isolation test. The per-model limit is in the batch() docstring and both docs pages.

"""Returns the _BatchQueue for a multiplexed model ID."""
queue_key = multiplexed_model_id or ""
if queue_key not in self._queues:
self._queues[queue_key] = _BatchQueue(

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.

This logs the max_ongoing_requests warning on every model queue creation, so on almost every request when traffic is sparse (20× vs 1× on master with defaults). Log it once from the wrapper?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Moved this to the wrapper. It checks when it creates its first queue and on later set_max_batch_size calls, and only warns when max_batch_size * max_concurrent_batches is over max_ongoing_requests. Queues the wrapper creates don't log it, so a queue recreated after cleanup doesn't warn again. test_wrapper_warns_about_max_ongoing_requests_once covers multiple model queues, a recreated queue, and the setter with no queues left.

Comment thread python/ray/serve/batching.py Outdated

if self._queue is not None:
self._queue.set_max_batch_size(new_max_batch_size)
# Snapshot to avoid iterating a dictionary that queue creation or

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.

Nit: this loop and comment are repeated in set_batch_wait_timeout_s, and if not self._queues: _ = self.queue is repeated in _is_batching_task_alive and _get_handling_task_stack. Pull each into a helper?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Added _queues_or_default() for the repeated default-queue lines and removed the setter loops. The wrapper and its queues share one _BatchConfig now, so a setter updates existing queues, new queues, and a queue being created at the same time. A batch that's already forming keeps the size and timeout it started with. This also fixes the reconfigure race from the limitations section of the description.

@johntaylor-cell johntaylor-cell 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.

Nice, very useful change that will positively affect performance. I investigated a simpler approach that does not create and destroy queues. It uses one queue and per-model lists, but that required a large edit to this PR, adding significant risk. Totally independent queues seems like the cleanest approach, but the shared semaphore is problematic. I added a related comment inline to help relax this.

Otherwise, there is no e2e test that covers per-model filling. The three multiplex + batching tests in test_multiplex.py pass on master too. Add one with interleaved model IDs that asserts full per-model batches?

I would also like to see a test that covers queue lifecycle, namely a model queue recreated after cleanup. With sparse traffic this is what happens on most requests, and it’s the riskiest lifecycle step. The old loop is cancelled, a new queue is created, and leftover callbacks have to do nothing. A cheap unit test covers it.

And finally, I would like to see a test that that waits for a slot before forming the next batch. This changes behavior for every @serve.batch user, so a unit test should pin it down. For example, with max_concurrent_batches=1, requests that arrive while a batch waits go into the next, fuller batch.

Give each model queue its own semaphore so max_concurrent_batches
applies per model ID, and log the max_ongoing_requests warning once
from the wrapper. Share one batch config and one set of batch metrics
across the wrapper's queues, so setters reach queues created at any
time and creating a queue stays cheap.

Add an e2e test for full per-model batches, and unit tests for queue
recreation after cleanup, per-model concurrency, waiting for a permit,
cancellation, shared metrics and the setters. Document the per-model
concurrency limit.

Signed-off-by: angryturtlebro <[email protected]>
@angryturtlebro
angryturtlebro requested review from a team as code owners November 8, 2026 02:08
@angryturtlebro

angryturtlebro commented Nov 8, 2026 •

Copy link
Copy Markdown
Author

Thanks for the review @johntaylor-cell! Updated this PR:

  • Merged master. [serve] Take the max_concurrent_batches permit before forming a batch #67877 now waits for a max_concurrent_batches permit before forming a batch, so requests that come in while every permit is in use go into the next, fuller batch. That's the behavior you wanted a test for, and [serve] Take the max_concurrent_batches permit before forming a batch #67877 added test_requests_arriving_while_batches_run_form_one_batch. Model queues keep the same ordering, and I parametrized that test to run on a model queue too.
  • Added the e2e test, test_multiplexed_with_batching_fills_batches_per_model_id. It alternates two models, waiting for each request to reach the replica before sending the next, and checks for one batch of 3 per model. It fails with master's batching.py, which forms batches of 1 and 2.
  • Added the queue lifecycle test, test_multiplexed_batch_queue_recreated_after_cleanup. It checks that the old queue's loop finishes, the next request gets a new queue, and a leftover idle callback from the old queue doesn't remove the new one.

Benchmarks

All runs go through a single replica with a DeploymentHandle, max_batch_size=8, alternating master and this PR with only batching.py swapped.

With 1 s of work per batch (await asyncio.sleep(1) in the handler, default max_concurrent_batches=1), sending 5 groups of 64 requests over 8 models. Median of 3 runs, master → this PR:

Batch timeout Time per group (p50) Mean batch size Handler calls (all 5 groups)
0 9.05 → 2.03 s 1.11 → 4.00 289 → 80
10 ms 8.06 → 2.04 s 1.10 → 4.00 291 → 80

This PR was faster in every run. On master each model mostly gets batches of 1, and the next shared batch waits for all of the current one's sub-batches. With this PR each model fills and runs its own batches. The sleeps overlap across models, so this shows batching and scheduling, not inference on a shared accelerator.

Cost of cleaning up and recreating queues

A model's queue is removed once it's idle, so with sequential requests for a model ID this PR creates a new queue for every request. Creating the metric objects was most of that cost, so the wrapper now shares one set across its queues. Metric names and labels didn't change (there's no model-ID label), and the queue-length gauge counts queued requests across all the wrapper's queues, same as master's single queue. One change is that serve_batch_wait_time_ms gets recorded once per model batch instead of once per shared batch. test_wrapper_queues_share_metrics and test_shared_queue_length_gauge_reports_all_model_queues cover this.

To measure the overhead, the handler does nothing and batch_wait_timeout_s=0. Measured inside the replica (whole-process CPU), median of 5 runs, master → this PR. In parentheses is how many of the 5 runs this PR came out lower or higher than master:

Traffic CPU per request p50 p99
No model ID, sequential 646 → 619 µs (lower 5/5) 169 → 150 µs (lower 5/5) 195 → 178 µs (lower 5/5)
One model, sequential 652 → 638 µs (lower 4/5) 170 → 158 µs (lower 5/5) 245 → 255 µs (higher 5/5)
20 models rotating, sequential 648 → 636 µs (lower 4/5) 169 → 156 µs (lower 5/5) 197 → 233 µs (higher 4/5)
Groups of 64 over 8 models 716 → 743 µs (higher 4/5) 1.63 → 1.32 ms (lower 5/5) 4.6 → 3.2 ms (lower 5/5)

Recreating a queue shows up mostly in p99, which is typically 20–35 µs higher with model IDs. A microbenchmark without Serve puts creating and removing a queue at roughly 9 µs per request. The groups of 64 reach the replica spread out, so most of those requests still find their model's queue gone.

Queues also stick around while their model has traffic. With 4 models, 16 clients each sending back to back for 10 s with 0.1 s of work per batch, each model kept one queue for all 99 of its batches, and the queues were only removed after traffic stopped.

Out of date in the PR description

  • Model queues don't share one semaphore anymore. Each has its own max_concurrent_batches limit, so different models run concurrently with the default.
  • Queues don't form a batch before getting a permit anymore. [serve] Take the max_concurrent_batches permit before forming a batch #67877 takes the permit first.
  • The reconfigure limitation is fixed. Setters update a config shared by all queues.


# Cancel once the request is dequeued into a batch that is still filling.
await async_wait_for_condition(
lambda: bool(queue._current_batch), retry_interval_ms=1

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.

On Python 3.10/3.11 this can hang. If the poll fires while the loop is still in its first wait_for with the event already set, wait_for swallows the cancel and await queue._handle_batch_task never returns. I t hung 1 in 160 runs under load. Poll bool(queue._current_batch) and not queue.requests_available_event.is_set() instead?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks, good catch. Fixed with that poll. I ran it 300 times with every core busy: the old version hung 13 times and the new one passed all 300.

queue.put(request)
futures.append(request.future)

await async_wait_for_condition(lambda: bool(recorded), retry_interval_ms=1)

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.

Same race as above. _shut_down_queues can hang if model-a’s loop is still in its first wait_for. Maybe poll len(recorded) >= 2 instead?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed, it now polls len(recorded) >= 2. Same check: the old version hung 31 times in 300 runs and the new one passed all 300.

start_times.extend(queue.curr_iteration_start_times.values())
return _RuntimeSummaryStatistics(start_times)

async def _is_batching_task_alive(self) -> bool:

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.

These three debug helpers now cover every model queue, but tests only use the default queue, so reverting any of them to default-only still passes. Add a test with two blocked model queues that checks 2 start times, 2 stacks, and _is_batching_task_alive() False after one queue’s loop is cancelled?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Added test_debug_helpers_cover_every_model_queue with those checks. It fails if I revert any one of the three helpers to default-only.



@pytest.mark.asyncio
@pytest.mark.parametrize(

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.

As a nit, this parametrize list is repeated at line 756; hoist it into a constant like METRIC_ATTRIBUTES?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done, both setter tests use BATCH_SETTER_CASES now.

@johntaylor-cell johntaylor-cell 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.

Thanks, everything from my last review is addressed. Please update the PR description as it still describes the shared semaphore, forming a batch before taking a permit, and the reconfigure limitation.

@angryturtlebro

Copy link
Copy Markdown
Author

Thanks again for the review! Made a new commit based on your latest comments and updated the description as requested!

Comment thread python/ray/serve/batching.py Outdated
task = asyncio.create_task(self._process_batch_inner(func, batch))
except BaseException as e:
self.semaphore.release()
if isinstance(e, asyncio.CancelledError):

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.

Production never cancels this loop while it holds dequeued requests: shutdown() only runs on idle queues, a busy queue stays in queues (so no del), and replica shutdown drains and exits without cancelling user-loop tasks. So this block and both test_cancelled_batch_queue* tests only cover a hypothetical. Drop them?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed, removed the block and both tests.

del self._queues[queue_key]
queue.shutdown()

def _total_queue_length(self) -> int:

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.

The description says serve_batch_queue_length reports queued requests across all queues, but it’s only set while some queue is filling a batch. With one model’s permit busy and 5 requests queued, it reports 0. Also record it on enqueue and after forming a batch?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch. It's now also recorded after a batch forms, and on enqueue while the queue waits for a permit. test_queue_length_gauge_recorded_on_enqueue_and_after_batch covers your example.

new_queue.put(request)
await async_wait_for_condition(lambda: bool(new_queue.tasks), retry_interval_ms=1)

# A leftover idle notification from the old queue leaves the new one alone.

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.

This can’t happen in production. A removed queue has no tasks and its loop dies on the cancel (Queue.get and Semaphore.acquire re-raise), so it never calls _on_idle again. I was wrong to ask for this step, drop these four lines?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Removed them, along with the blocking request that only that step needed.

Your comment prompted me to check for other code that production never hits, and as a result I dropped the _handle_batch_task is None checks in the debug helpers. @serve.batch always passes a handler, so queues it creates always have a background task.

@johntaylor-cell johntaylor-cell 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.

Thanks, all four addressed. Another pass found a couple more.

@angryturtlebro

Copy link
Copy Markdown
Author

Made it through your new findings!

@johntaylor-cell johntaylor-cell 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, thanks

@johntaylor-cell johntaylor-cell added the go add ONLY when ready to merge, run all tests label Nov 11, 2026

This branch has not been deployed

No deployments
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 unstale A PR that has been marked unstale. It will not get marked stale again if this label is on it.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants