Skip to content

[Serve] add support for custom batch size function - #59059

Merged
abrarsheikh merged 4 commits into
masterfrom
58956-abrar-batch
Dec 4, 2025
Merged

abrarsheikh merged 4 commits into
masterfrom
58956-abrar-batch

Conversation

@abrarsheikh

@abrarsheikh abrarsheikh commented Nov 28, 2025 •

Copy link
Copy Markdown
Contributor

fixes #58956

  • update documentation
  • add tests
  • add code examples and link to docs
  • compare performance with len(batch) baseline

script

from ray import serve
from typing import List

@serve.deployment(max_ongoing_requests=200)
class BatchSizeFnExample:
    @serve.batch(
        max_batch_size=50,
        batch_wait_timeout_s=0.5,
        # batch_size_fn=lambda items: len(items),
    )
    async def handle_batch(self, requests: List):
        return [req["value"] * 2 for req in requests]

    async def __call__(self, request):
        body = await request.json()
        return await self.handle_batch(body)

app = BatchSizeFnExample.bind()

load test

# First, create a file with the JSON payload
echo '{"value": 5}' > /tmp/post_data.json

# Run Apache Bench: 1000 requests, 50 concurrent connections
ab -n 1000 -c 100 -p /tmp/post_data.json -T "application/json" http://localhost:8000/

results

batch size 10
master
Requests per second:    317.68 [#/sec] (mean)
Time per request:       314.780 [ms] (mean)
Time per request:       3.148 [ms] (mean, across all concurrent requests)

PR
Requests per second:    307.80 [#/sec] (mean)
Time per request:       324.891 [ms] (mean)
Time per request:       3.249 [ms] (mean, across all concurrent requests)



batch size 50
master
Requests per second:    328.21 [#/sec] (mean)
Time per request:       304.684 [ms] (mean)
Time per request:       3.047 [ms] (mean, across all concurrent requests)

pr
Requests per second:    329.03 [#/sec] (mean)
Time per request:       303.922 [ms] (mean)
Time per request:       3.039 [ms] (mean, across all concurrent requests)

@abrarsheikh abrarsheikh added the go add ONLY when ready to merge, run all tests label Nov 28, 2025
@abrarsheikh
abrarsheikh marked this pull request as ready for review December 1, 2025 18:47
@abrarsheikh
abrarsheikh requested review from a team as code owners December 1, 2025 18:47
Comment thread python/ray/serve/batching.py Resolved
@ray-gardener ray-gardener Bot added serve Ray Serve Related Issue docs An issue or change related to documentation labels Dec 1, 2025
@lbluque lbluque mentioned this pull request Dec 2, 2025
2 of 4 tasks
Comment thread python/ray/serve/batching.py Outdated
Comment on lines +257 to +259
# Put deferred item back in queue for next batch
if deferred_item is not None:
self.queue.put_nowait(deferred_item)

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 would put the request it in the back of the queue correct?

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.

correct.

Comment thread python/ray/serve/batching.py Outdated
batch.append(self.queue.get_nowait())

# Put deferred item back in queue for next batch
if deferred_item is not None:

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: we can put this block after

while not self.queue.empty():
    next_item = self.queue.get_nowait()
    # Temporarily add to check size
    batch.append(next_item)
    new_size = self._compute_batch_size(batch)
    
    if new_size > max_batch_size:
        # Would exceed limit, remove it and save for later
        batch.pop()
        deferred_item = next_item
        break
    # Size is OK, keep it in the batch (already added above)

args, kwargs = recover_args(request.flattened_args)
# The batch function expects a single positional argument (the item)
# after 'self' has been extracted (if it was a method)
items.append(args[0])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Bug: Potential IndexError when using keyword arguments with batch_size_fn

The _compute_batch_size method assumes that requests are always passed as positional arguments, accessing args[0] without checking if args is empty. If a user defines a batch method with keyword-only parameters (e.g., async def handle_batch(self, *, request)) and calls it with keyword arguments, recover_args will return an empty args list, causing an IndexError: list index out of range. This would result in a confusing error message rather than a clear explanation that batch_size_fn requires the batched argument to be passed positionally.

Fix in Cursor Fix in Web

@abrarsheikh
abrarsheikh merged commit 0d75cbc into master Dec 4, 2025
@abrarsheikh
abrarsheikh deleted the 58956-abrar-batch branch December 4, 2025 21:39
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs An issue or change related to documentation 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.

[serve] Add an optional batch_size_fn to batch decorator

3 participants