Dynamic Batching in Python with asyncio

Build an asyncio dynamic batcher that flushes on size or deadline, handles cancelled requests and errors, and shuts down cleanly.

Guide ยท 9 min read

Dynamic batching groups requests that arrive one at a time into batches, and sends a batch when either it reaches a maximum size or its oldest request has waited a maximum time. Model servers use it because a GPU processes 32 inputs in about the time it takes to process one, and databases and APIs use it to turn many small writes into one bulk call. The two limits trade throughput against latency: a larger batch size or a longer wait means fewer, fuller batches, and a shorter wait bounds how long any single request is held. In Python with asyncio the core is a queue of (item, future) pairs and one background task that collects up to max_size items or until a deadline, calls the batch function once, and resolves each caller's future with its own result.

This guide builds that batcher, then adds cancellation, error handling and a clean shutdown, which is where interview versions of the question spend most of their tests. Every snippet is complete and runs on Python 3.12 or newer.

The shape

Each caller awaits submit(item) as if it were an ordinary single-item call. Behind it:

  1. submit creates a future, puts (arrival_time, item, future) on an asyncio.Queue, and awaits the future.
  2. One worker task waits for the first item, then keeps taking items until it has max_size of them or the first item's deadline passes.
  3. The worker calls batch_fn(items) once and sets each future's result from the returned list, in order.

Only the worker calls batch_fn, so at most one batch runs at a time unless you choose otherwise. The queue gives FIFO order for free.

A first batcher

import asyncio
import time


class Batcher:
    def __init__(self, batch_fn, max_size: int, max_wait: float) -> None:
        self.batch_fn = batch_fn
        self.max_size = max_size
        self.max_wait = max_wait
        self.queue: asyncio.Queue = asyncio.Queue()
        self.worker = asyncio.create_task(self._run())

    async def submit(self, item):
        loop = asyncio.get_running_loop()
        future = loop.create_future()
        self.queue.put_nowait((loop.time(), item, future))
        return await future

    async def _run(self) -> None:
        while True:
            first = await self.queue.get()
            batch = [first]
            try:
                async with asyncio.timeout_at(first[0] + self.max_wait):
                    while len(batch) < self.max_size:
                        batch.append(await self.queue.get())
            except TimeoutError:
                pass
            await self._send(batch)

    async def _send(self, batch) -> None:
        items = [item for _, item, _ in batch]
        try:
            outputs = await self.batch_fn(items)
        except Exception as exc:
            for _, _, future in batch:
                future.set_exception(exc)
            return
        for (_, _, future), output in zip(batch, outputs):
            future.set_result(output)


async def main() -> None:
    seen: list[list[int]] = []

    async def double(items: list[int]) -> list[int]:
        seen.append(items)
        await asyncio.sleep(0.01)
        return [x * 2 for x in items]

    batcher = Batcher(double, max_size=3, max_wait=0.05)
    start = time.monotonic()
    results = await asyncio.gather(*(batcher.submit(i) for i in range(7)))
    print(results)  # [0, 2, 4, 6, 8, 10, 12]
    print(seen)  # [[0, 1, 2], [3, 4, 5], [6]]
    print("last batch waited for the deadline:", time.monotonic() - start >= 0.05)  # last batch waited for the deadline: True
    batcher.worker.cancel()


asyncio.run(main())

The first two batches go out full and immediately. Item 6 is alone, so it waits until 50 ms after it was submitted and goes out as a batch of one.

The deadline is measured from the oldest item's arrival time, which submit records, not from when the worker picked it up. If the previous batch took 40 ms to run, items that arrived during it have already used most of their wait, and their batch should go out soon after the worker returns. Starting the clock when the worker dequeues the first item is a common bug that lets latency grow to max_wait plus the batch time.

asyncio.timeout_at takes an absolute deadline in loop.time() units, which is why submit stamps items with loop.time() rather than time.monotonic(). In CPython's default event loop the two read the same clock, but timeout_at is defined in terms of loop.time(), and a custom event loop may use a different one.

Cancellation

A caller can be cancelled while its item is still queued, for example by its own timeout. Its future is then cancelled, and two things must follow. The item should not be sent, because nobody wants the result. And calling set_result on a cancelled future raises InvalidStateError, which in the version above would kill the worker and hang every later caller.

import asyncio


class Batcher:
    def __init__(self, batch_fn, max_size: int, max_wait: float) -> None:
        self.batch_fn, self.max_size, self.max_wait = batch_fn, max_size, max_wait
        self.queue: asyncio.Queue = asyncio.Queue()
        self.worker = asyncio.create_task(self._run())

    async def submit(self, item):
        loop = asyncio.get_running_loop()
        future = loop.create_future()
        self.queue.put_nowait((loop.time(), item, future))
        return await future

    async def _next_live(self):
        while True:
            entry = await self.queue.get()
            if not entry[2].done():
                return entry

    async def _run(self) -> None:
        while True:
            first = await self._next_live()
            batch = [first]
            try:
                async with asyncio.timeout_at(first[0] + self.max_wait):
                    while len(batch) < self.max_size:
                        batch.append(await self._next_live())
            except TimeoutError:
                pass
            batch = [entry for entry in batch if not entry[2].done()]
            if batch:
                await self._send(batch)

    async def _send(self, batch) -> None:
        try:
            outputs = await self.batch_fn([item for _, item, _ in batch])
        except Exception as exc:
            for _, _, future in batch:
                if not future.done():
                    future.set_exception(exc)
            return
        for (_, _, future), output in zip(batch, outputs):
            if not future.done():
                future.set_result(output)


async def main() -> None:
    seen: list[list[str]] = []

    async def upper(items: list[str]) -> list[str]:
        seen.append(items)
        return [s.upper() for s in items]

    batcher = Batcher(upper, max_size=4, max_wait=0.05)
    a = asyncio.create_task(batcher.submit("a"))
    b = asyncio.create_task(batcher.submit("b"))
    c = asyncio.create_task(batcher.submit("c"))
    await asyncio.sleep(0.01)
    b.cancel()
    print(await a, await c, seen)  # A C [['a', 'c']]
    batcher.worker.cancel()


asyncio.run(main())

Three items wait in a batch of up to four, b is cancelled during the 50 ms wait, and only a and c reach the batch function. The worker skips dead entries when it takes them from the queue, filters again just before sending in case a caller was cancelled during collection, as b was here, and checks future.done() before resolving. A cancelled entry does not count toward max_size, so a burst of cancellations can't produce a batch that is "full" of nothing.

Both checks use done(), not cancelled(). A future that is done for any reason can't take a result. A caller cancelled after its batch was sent gets nothing, and the batch still runs for everyone else in it.

Errors

If batch_fn raises, every caller in that batch gets the same exception and the worker moves on to the next batch. The worker must never die. If it did, every later submit would wait forever on a future nobody resolves. Catching Exception (not BaseException) in _send keeps the worker alive while still letting a CancelledError stop it.

For partial failures, have batch_fn return a result object per item, or an exception instance in the failed slots, and call future.set_exception for those slots only. Interviewers often ask for this as a follow-up, and the change is a few lines in _send if you put all future-resolving code in one place.

Shutdown

A clean shutdown stops new submissions, sends everything already accepted without waiting out max_wait, and returns once the worker has finished. A sentinel on the queue does all three, because the queue is FIFO: every item accepted before shutdown is ahead of the sentinel.

import asyncio

STOP = object()


class Batcher:
    def __init__(self, batch_fn, max_size: int, max_wait: float) -> None:
        self.batch_fn, self.max_size, self.max_wait = batch_fn, max_size, max_wait
        self.queue: asyncio.Queue = asyncio.Queue()
        self.closed = False
        self.worker = asyncio.create_task(self._run())

    async def submit(self, item):
        if self.closed:
            raise RuntimeError("batcher is shut down")
        loop = asyncio.get_running_loop()
        future = loop.create_future()
        self.queue.put_nowait((loop.time(), item, future))
        return await future

    async def shutdown(self) -> None:
        if not self.closed:
            self.closed = True
            self.queue.put_nowait(STOP)
        await asyncio.shield(self.worker)

    async def _run(self) -> None:
        stopping = False
        while not stopping:
            first = await self.queue.get()
            if first is STOP:
                return
            batch = [first]
            try:
                async with asyncio.timeout_at(first[0] + self.max_wait):
                    while len(batch) < self.max_size:
                        entry = await self.queue.get()
                        if entry is STOP:
                            stopping = True
                            break
                        batch.append(entry)
            except TimeoutError:
                pass
            await self._send([e for e in batch if not e[2].done()])

    async def _send(self, batch) -> None:
        if not batch:
            return
        try:
            outputs = await self.batch_fn([item for _, item, _ in batch])
        except Exception as exc:
            outputs = [exc] * len(batch)
        for (_, _, future), output in zip(batch, outputs):
            if future.done():
                continue
            if isinstance(output, Exception):
                future.set_exception(output)
            else:
                future.set_result(output)


async def main() -> None:
    async def square(items: list[int]) -> list[int]:
        return [x * x for x in items]

    batcher = Batcher(square, max_size=4, max_wait=10.0)
    loop = asyncio.get_running_loop()
    pending = [asyncio.create_task(batcher.submit(i)) for i in range(6)]
    await asyncio.sleep(0)
    start = loop.time()
    await batcher.shutdown()
    print(await asyncio.gather(*pending), f"flushed in under 1s: {loop.time() - start < 1}")
    try:
        await batcher.submit(99)
    except RuntimeError as exc:
        print(exc)
    await batcher.shutdown()
    print("second shutdown is a no-op")


asyncio.run(main())
# [0, 1, 4, 9, 16, 25] flushed in under 1s: True
# batcher is shut down
# second shutdown is a no-op

With a 10-second max_wait, the last two items would normally wait 10 seconds. Shutdown sends them straight away: the worker takes the four-item batch, then starts the next batch, reads the sentinel, and sends the two items it has. shutdown awaits the worker through asyncio.shield, so if the caller of shutdown is cancelled, the flush still completes and the accepted requests still get their results. Calling shutdown twice is safe because only the first call enqueues the sentinel.

Python 3.13 added asyncio.Queue.shutdown(), which makes get() raise QueueShutDown once the queue is empty. It removes the need for a sentinel, but code that must run on 3.12 still needs one.

Tuning: size versus wait

The right max_wait depends on arrival rate. If requests arrive faster than max_size / max_wait, batches fill before the deadline and the wait rarely matters. If traffic is light, most batches go out at the deadline, partly empty, and every request pays the full wait. A useful interview answer states the two extremes: max_wait=0 sends whatever is queued right now, which still batches under load and adds no latency when idle, and a very long wait maximises batch size at the cost of tail latency. Real servers set max_wait to a small fraction of the latency budget, often a few milliseconds.

Follow-ups interviewers ask

  • Batch by cost, not count. Language model servers limit a batch by total tokens, not number of requests. Track a running total while collecting, and stop when the next item would exceed the budget. Decide what happens to a single item larger than the budget.
  • Overlap batches. With one worker, collection pauses while batch_fn runs. Start batch_fn as a task and limit concurrent batches with a semaphore to keep the device busy.
  • Backpressure. An unbounded queue lets a traffic spike grow memory without limit. Use asyncio.Queue(maxsize=n) and make submit await put, or reject with an overload error when full.
  • Priorities. Swap the queue for a heap keyed by (priority, arrival_seq) and decide whether the deadline belongs to the oldest item or the most urgent one.
  • Testing. Inject the batch function and assert on the batches it saw, as above. Avoid exact timing assertions. Check lower bounds tightly and upper bounds loosely.

Common mistakes

  • Measuring the wait from when the worker dequeues instead of from when the request arrived.
  • Resetting the deadline on every new item. The batch then never closes under steady traffic.
  • Setting results on cancelled futures. InvalidStateError kills the worker and hangs every later caller.
  • Letting an exception from batch_fn escape the worker. Same result: a dead worker and hung callers.
  • Counting cancelled requests toward max_size.
  • A shutdown that waits out max_wait, or one that the caller's cancellation can interrupt halfway through the flush.

Practise it

The Dynamic Request Batcher problem asks for this batcher with every rule above, including deadlines that move when the oldest request is cancelled and a shutdown that is safe to call concurrently. It is the hardest open problem on the site, so give it 45 minutes.

  1. 12Inference Worker Poolmedium

    Run inference requests through a fixed pool of asyncio workers sharing one queue, isolate failures, and return results in input order.

  2. 16Async Circuit Breakerhard

    Implement an asyncio circuit breaker with closed, open and half-open states, a single recovery probe, and protection against stale in-flight calls.

  3. 20Dynamic Request Batcherhard

    Group concurrent inference requests into batches that flush when full or when the oldest request has waited long enough, with cancellation and drain.

  4. 21Async TTL Cache with Request Coalescingmedium

    Build an asyncio cache whose entries expire after a TTL, where concurrent misses for the same key share one fetch that survives caller cancellation.

  5. 22Async Retry with Exponential Backoffmedium

    Retry a failing coroutine with capped exponential backoff, re-raise the last error, and never swallow cancellation.

  6. 25Async Request Deduplicatorhard

    Collapse concurrent fetches for the same key into one shared call, with per-caller timeouts that never cancel the shared work.

The batching and asyncio topic pages collect related problems. The asyncio worker pool guide covers the queue and shutdown patterns this batcher is built on.

Frequently asked questions

What is dynamic batching?

Grouping requests that arrive one at a time into batches, sending each batch when it reaches a maximum size or when its oldest request has waited a maximum time. It raises throughput on hardware or APIs that handle a batch almost as fast as a single item, such as GPUs serving a model.

How do you implement request batching with asyncio?

Each caller puts its item and a new future on an asyncio.Queue and awaits the future. One background task takes the first item, keeps taking items until the batch is full or the first item's deadline passes, calls the batch function once, and sets each future's result in order.

How do you choose the batch size and maximum wait?

The batch size usually comes from the hardware or API limit. The maximum wait is a slice of your latency budget, often a few milliseconds. Under heavy traffic batches fill before the deadline, and under light traffic every request pays the full wait, so measure both cases.

What happens to a cancelled request in a batcher?

If it is still queued, the worker should skip it so it does not take a slot in the batch. If its batch is already running, the batch continues for the other requests and the cancelled caller simply gets no result. Always check future.done() before setting a result.

How do you shut down an asyncio batcher without losing requests?

Mark the batcher closed so new submissions raise, put a sentinel on the queue, and let the worker send everything ahead of the sentinel without waiting for deadlines. Await the worker through asyncio.shield so cancelling the shutdown call does not interrupt the flush.

Is dynamic batching the same as continuous batching?

No. Dynamic batching forms a batch, runs it to completion and then forms the next. Continuous batching, used by language model servers, adds and removes sequences from a running batch at every generation step, which needs control of the model loop itself.