Sub topic 4
Dynamic batching: grouping requests on the server
This chapter assumes you can read basic Python and YAML. It also assumes you know what p50 and p99 latency mean, and that you have served a model behind an HTTP or gRPC endpoint. The earlier chapters explained why accelerators run more efficiently on batches. Here the server forms those batches itself.
What dynamic batching does
Clients send requests one at a time, at unpredictable moments. A GPU does much better work on 8 or 16 inputs together than on one input at a time. Dynamic batching puts a queue inside the server to close that gap. Requests wait briefly in the queue, the server groups them, and the model runs once on the whole group. The server then splits the outputs and returns each result to the client that asked for it.
The client sees an ordinary single-request API. It does not need to know that other clients' requests shared the same model call.
Two parameters control the behavior:
- Max batch size: the most requests allowed in one model call. This caps memory use and the worst-case compute time per call.
- Max wait (queue delay): the longest the server holds the first request of a batch while waiting for others to arrive. This caps the latency that batching adds.
A batch is sent to the model when either limit is reached, whichever comes first.
The batching loop
The loop is the same in every inference server, though the names differ.
The deadline starts when the first request is taken, not when the batcher becomes idle. Each request therefore waits at most max_wait_s for batch formation, plus any time spent behind earlier batches that are still running.
A minimal implementation
This asyncio version shows the whole mechanism in about 40 lines. Each caller gets a future, the queue holds the input together with that future, and a single worker task forms batches.
import asyncio
class DynamicBatcher:
"""Collects requests until the batch is full or a deadline passes."""
def __init__(self, model_fn, max_batch_size=8, max_wait_s=0.01):
self.model_fn = model_fn # takes a list of inputs, returns a list of outputs
self.max_batch_size = max_batch_size
self.max_wait_s = max_wait_s
self.queue = asyncio.Queue()
async def submit(self, item):
loop = asyncio.get_running_loop()
fut = loop.create_future()
await self.queue.put((item, fut))
return await fut
async def run(self):
loop = asyncio.get_running_loop()
while True:
batch = [await self.queue.get()]
deadline = loop.time() + self.max_wait_s
while len(batch) < self.max_batch_size:
remaining = deadline - loop.time()
if remaining <= 0:
break
try:
batch.append(await asyncio.wait_for(self.queue.get(), remaining))
except asyncio.TimeoutError:
break
inputs = [item for item, _ in batch]
try:
outputs = await loop.run_in_executor(None, self.model_fn, inputs)
for (_, fut), out in zip(batch, outputs):
fut.set_result(out)
except Exception as exc:
for _, fut in batch:
fut.set_exception(exc)
async def main():
batcher = DynamicBatcher(lambda xs: [x * 2 for x in xs], max_batch_size=4, max_wait_s=0.005)
worker = asyncio.create_task(batcher.run())
results = await asyncio.gather(*(batcher.submit(i) for i in range(10)))
print(results)
worker.cancel()
asyncio.run(main())Running it prints [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]. Ten requests arrive at once, so the batcher forms batches of 4, 4, and 2. The last batch is smaller because the queue empties and the deadline expires.
Four details in the code matter in production:
await self.queue.get()blocks with no timeout for the first item. An idle server does not spin.asyncio.wait_for(..., remaining)shrinks the timeout on each pass, so the total wait never exceedsmax_wait_s.run_in_executormoves the model call to a thread so the event loop keeps accepting requests while the model runs. Without it, a blocking model call would stall the queue.- Results are matched to futures by position. The model function must return outputs in the same order as its inputs.
The same idea in Triton
Inference servers expose these two parameters as configuration. This is a Triton Inference Server model configuration fragment:
max_batch_size: 32
dynamic_batching {
preferred_batch_size: [ 8, 16 ]
max_queue_delay_microseconds: 5000
}max_batch_size: 32 is the hard cap. max_queue_delay_microseconds: 5000 is a 5 ms maximum wait. preferred_batch_size lists sizes the server tries to form, which is useful when the model engine is optimized for specific shapes. Preferred sizes must not exceed the maximum. Many models do not need the preferred list, and leaving it out is a safe default.
What it costs and what it gains
Batching adds latency to every request, but the amount depends on load.
- Low load: requests rarely arrive together. Each one waits the full
max_wait_sand then runs alone. You pay the maximum added latency and gain almost no throughput. - High load: the batch fills before the deadline. The added wait is small, and throughput per accelerator rises.
Suppose max_wait_s is 5 ms and the model takes 20 ms per batch. The worst case for batching alone adds 5 ms, so a request takes about 25 ms. If a batch of 8 runs in 28 ms instead of 8 separate 20 ms calls, the server handles the same traffic with far fewer accelerator-seconds. Real numbers vary, so measure your own model.
| Property | Static batching | Dynamic batching |
|---|---|---|
| Who forms the batch | Client or fixed pipeline | Server queue |
| Batch size | Fixed | Varies up to the maximum |
| Latency under light load | Waits for a full batch, or the client batches itself | Bounded by max wait |
| Client complexity | Higher | None |
| Fits unpredictable traffic | Poorly | Well |
Edge cases and common errors
One bad input fails the whole batch. In the code above, an exception from model_fn is set on every future in the batch. One malformed request can therefore fail seven healthy ones. Validate inputs before they enter the queue. If your model can fail per item, return per-item errors instead of raising.
Variable-length inputs need padding. A batch must usually be a rectangular tensor. Padding short inputs to the longest one wastes compute, and one long request slows the whole batch. Where the lengths differ widely, a common remedy is to batch by similar size, which means one queue per size bucket.
Cancelled callers. If a client disconnects and its future is cancelled, fut.set_result raises InvalidStateError, which can kill the worker. A production version should check fut.done() before setting results.
Unbounded queues. The queue above has no size limit. During overload, requests pile up, latency grows without bound, and clients time out while the server still processes their abandoned work. Set a queue limit and reject excess requests quickly. Autoscaling, covered in later chapters, relies on this queue growth as a signal.
Wait set too long. If max_wait_s is large compared to the latency target, you spend your latency budget waiting. A common rule of thumb is to keep the wait to a small fraction of the p99 target, then verify with measurements.
Warm batch shapes. Some runtimes compile or tune for each batch shape on first use. A new size seen in production can cause a slow call. Run warmup requests at the sizes you expect.
Where this leads
Dynamic batching groups requests whole: every request in a batch starts and ends together. That works well when each request costs about the same. For text generation, where requests produce different numbers of tokens, a later chapter covers continuous batching. The next chapters cover how to choose the two parameters against a latency objective and how replica count interacts with them.
Exercise
A server uses dynamic batching with maxbatchsize = 16 and max_wait = 10 ms. Traffic drops to about 3 requests per second, evenly spaced. Roughly how much latency does batching add to a typical request, and how large are the batches? What would you change if the p99 target is 40 ms and the model itself takes 25 ms?
Show answer
Requests arrive about 333 ms apart, far longer than the 10 ms wait. Each request opens a batch, waits the full 10 ms, and runs alone, so batches have size 1 and batching adds about 10 ms to every request with no throughput benefit. With a 25 ms model time and a 40 ms p99 target, only 15 ms of budget remains for queueing and overhead, so 10 ms of waiting is a large share of it. Reduce max_wait to about 2 to 5 ms, or lower it further if low-traffic periods are common, and confirm p99 under both light and heavy load.