Sub topic 4
Dynamic Batching: Grouping Requests on the Server
Assume you know how to serve a trained model through an HTTP or gRPC endpoint. You should also know latency percentiles such as p50 and p99, basic Python, and how a Kubernetes Deployment runs replicas.
Dynamic batching is a server-side technique that combines requests that arrive close together. The server sends one batch to the model instead of sending one model call per request. The batch ends when it reaches a size limit or a short waiting deadline.
How a Dynamic Batcher Works
Each incoming request enters a queue. A batcher takes the first queued request, starts a deadline, and collects additional requests until one of these conditions is true:
- The batch reaches
max_batch_size. max_queue_delayexpires.- The model server cannot accept more work.
The server then runs one inference call. It maps each output back to the future or connection belonging to the original request.
A small Python implementation shows the main control flow:
import asyncio
class DynamicBatcher:
def __init__(self, model_fn, max_batch_size=8, max_wait_s=0.01):
self.model_fn = model_fn
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()
result = loop.create_future()
await self.queue.put((item, result))
return await result
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:
item = await asyncio.wait_for(
self.queue.get(), remaining
)
batch.append(item)
except asyncio.TimeoutError:
break
inputs = [item for item, _ in batch]
try:
outputs = await loop.run_in_executor(
None, self.model_fn, inputs
)
for (_, result), output in zip(batch, outputs):
result.set_result(output)
except Exception as exc:
for _, result in batch:
result.set_exception(exc)
async def main():
batcher = DynamicBatcher(
lambda values: [value * 2 for value in values],
max_batch_size=4,
max_wait_s=0.005,
)
worker = asyncio.create_task(batcher.run())
results = await asyncio.gather(
*(batcher.submit(value) for value in range(10))
)
print(results)
worker.cancel()
asyncio.run(main())The model function must preserve input order. If the batch contains requests A, B, and C, output position two must belong to B. Production servers also need request cancellation, timeouts, input-shape checks, and clean handling when the model call fails.
Choosing the Two Main Parameters
max_batch_size limits the amount of work in one model call. Larger batches often improve accelerator utilization, but they can require more memory and increase the time needed for one call.
max_queue_delay limits how long the first request waits for other requests. A longer delay can create larger batches during moderate traffic. It also adds waiting time even when the model itself is fast.
| Parameter | Increasing it usually does | Main risk |
|---|---|---|
| `max_batch_size` | Raises throughput | Memory pressure and slower individual calls |
| `max_queue_delay` | Forms larger batches | Higher queueing and tail latency |
Dynamic batching differs from static batching because the server does not require the client to assemble a fixed-size batch. It also differs from continuous batching used by many language-model servers. Dynamic batching forms discrete inference calls. Continuous batching admits and removes sequence tokens during generation, so different requests can make progress together across multiple decoding steps.
Exercise
Exercise
A service receives requests at irregular intervals. Which setting controls the maximum time the first request waits for additional requests, and what is the trade-off?
Show answer
maxqueuedelay controls that wait. Increasing it may produce larger, more efficient batches, but it also increases queueing latency, especially for p99 requests.