No. 20hard45 min16 tests

Dynamic Request Batcher

Description

GPUs are far more efficient on a batch of inputs than on one at a time. Model servers therefore hold individual requests for a few milliseconds and send them to the model together. Build that batcher.

class DynamicBatcher:
    def __init__(self, batch_size: int, max_wait_seconds: float, batch_fn): ...
    async def submit(self, item): ...
    async def shutdown(self) -> None: ...

batch_fn(items: list) is an async function that returns a list of outputs, one per item, in the same order.

  • The constructor starts one background task (it is called inside a running event loop). It raises ValueError if batch_size <= 0 or max_wait_seconds <= 0.
  • submit(item) waits for the item to be processed and returns its output.
  • Requests are batched in FIFO order. A batch is sent to batch_fn as soon as either:
    • batch_size requests are waiting, or
    • the oldest waiting request has been waiting max_wait_seconds. Measure from when that request was submitted, even if an earlier batch was still running at the time. Cancelled requests are no longer waiting: if the oldest one is cancelled, the deadline is the next oldest request's.
  • A batch holds at most batch_size items. Only one batch_fn call runs at a time.
  • If batch_fn raises, every submit in that batch raises the same exception. Later batches are unaffected.
  • If a submit is cancelled before its batch is sent, its item is left out of the batch and does not count toward batch_size. If it is cancelled while its batch is running, the batch still runs for the others and the cancelled caller just gets no result.
  • shutdown() stops accepting requests, sends everything already accepted without waiting out max_wait_seconds, and returns when the background task has finished. Once shutdown has started, submit raises RuntimeError. shutdown may be called more than once, also concurrently. Cancelling a shutdown call does not stop the flush: accepted requests still get their results.

Python 3.13 added asyncio.Queue.shutdown(). Do not rely on it. Your solution must also run on Python 3.12.

Example

async def double(items):
    return [x * 2 for x in items]

batcher = DynamicBatcher(batch_size=3, max_wait_seconds=0.05, batch_fn=double)
await asyncio.gather(*(batcher.submit(i) for i in range(7)))
# [0, 2, 4, 6, 8, 10, 12]
# batch_fn saw [0, 1, 2], then [3, 4, 5] (both full), then [6] after 50 ms
await batcher.shutdown()

Constraints

  • 1 <= batch_size <= 1024, 0 < max_wait_seconds <= 10
  • batch_fn always returns exactly one output per input.

Solution

Reference solution and explanationTry it first. The explanation covers the approach, complexity, pitfalls and follow-ups.
Reveal solution

Approach

One background task owns batching. Each submit creates a future, appends (item, future, submitted_at) to a deque under an asyncio.Condition, notifies, and awaits the future. The worker resolves the futures after batch_fn returns. Callers just see an await that returns their output.

The worker loop has two waits:

  1. Wait until there is at least one request, or shutdown has started with nothing left (then exit).
  2. If the batch is full or shutdown has started, send it. Otherwise compute the deadline as the oldest request's submitted_at + max_wait. If it has passed, send; if not, wait on the condition inside asyncio.timeout_at(deadline) and loop. Recomputing on every wake-up matters: if the oldest request was cancelled while the worker slept, the next check uses the new oldest request's deadline instead of firing early on a request that is gone.

Then pop up to batch_size requests, release the lock, and call batch_fn outside it. That way new requests can queue while the model runs, and only one batch is ever in flight.

Using the oldest request's submit time, not the time the worker picked it up, bounds every request's queueing delay by max_wait, even when it arrived during a slow batch. If the deadline has already passed, the batch goes out immediately.

Cancellation uses the future. Cancelling a submit cancels the future it awaits. If the request is still in the deque, submit removes it so it does not take a batch slot. If the batch was already popped, the worker filters out done futures before calling batch_fn and checks done() again before setting each result.

Shutdown sets closing and notifies. Both waits have closing in their predicate, so the worker flushes whatever is queued without waiting out the timer, and exits once the deque is empty. Re-check closing inside the lock in submit, or a request can be accepted after the worker has already exited and hang forever.

Complexity

O(1) amortized per request for the deque operations, plus one batch_fn call per batch. Removing a cancelled request is O(n) in the queue length. Space is O(n) for the pending requests.

Pitfalls

  • Restarting the timer each time a request arrives. Under steady traffic the batch then never times out.
  • Calling batch_fn while holding the lock. Submits block for the length of a model call.
  • Calling future.set_result on a future whose caller was cancelled. That raises InvalidStateError and kills the worker.
  • Computing the deadline once when the batch opens. If the oldest request is then cancelled, the batch goes out early, on the deadline of a request nobody is waiting for.
  • Sending cancelled items to the model. That wastes GPU time and returns outputs nobody reads.
  • Not waking the worker on shutdown, so a partial batch waits the full max_wait or the worker sleeps forever on an empty queue.
  • await self._worker without shield in shutdown. Cancelling a shutdown caller then cancels the worker and strands every pending future.

Follow-ups interviewers ask

  • Pad or bucket by input length so a batch does not mix very short and very long sequences.
  • Pipeline: let the next batch form while one runs, and run up to N batches concurrently on N GPUs.
  • Make batch_size adaptive, larger under load and smaller when idle, to trade throughput for latency.
  • Add a per-request deadline and fail requests that would miss it instead of batching them.

Reference solution

import asyncio
from collections import deque
from dataclasses import dataclass


@dataclass(eq=False)  # identity equality, so deque.remove finds this exact request
class _Request:
    item: object
    future: asyncio.Future
    submitted_at: float


class DynamicBatcher:
    def __init__(self, batch_size: int, max_wait_seconds: float, batch_fn):
        if batch_size <= 0 or max_wait_seconds <= 0:
            raise ValueError("batch_size and max_wait_seconds must be positive")
        self._batch_size = batch_size
        self._max_wait = max_wait_seconds
        self._batch_fn = batch_fn
        self._pending: deque[_Request] = deque()
        self._closing = False
        self._changed = asyncio.Condition()
        self._worker = asyncio.create_task(self._run())

    async def submit(self, item):
        loop = asyncio.get_running_loop()
        request = _Request(item, loop.create_future(), loop.time())
        async with self._changed:
            if self._closing:
                raise RuntimeError("batcher is shutting down")
            self._pending.append(request)
            self._changed.notify_all()
        try:
            return await request.future
        except asyncio.CancelledError:
            if request in self._pending:
                self._pending.remove(request)
            raise

    async def _next_batch(self) -> list[_Request] | None:
        loop = asyncio.get_running_loop()
        async with self._changed:
            while True:
                await self._changed.wait_for(lambda: self._pending or self._closing)
                if not self._pending:
                    return None
                if len(self._pending) >= self._batch_size or self._closing:
                    break
                # Recomputed on every wake-up: if the oldest request was cancelled,
                # the deadline moves to the new oldest one.
                deadline = self._pending[0].submitted_at + self._max_wait
                if loop.time() >= deadline:
                    break
                try:
                    async with asyncio.timeout_at(deadline):
                        await self._changed.wait()
                except TimeoutError:
                    pass
            count = min(self._batch_size, len(self._pending))
            return [self._pending.popleft() for _ in range(count)]

    async def _run(self) -> None:
        while (batch := await self._next_batch()) is not None:
            live = [r for r in batch if not r.future.done()]
            if not live:
                continue
            try:
                outputs = await self._batch_fn([r.item for r in live])
            except Exception as exc:
                for r in live:
                    if not r.future.done():
                        r.future.set_exception(exc)
                continue
            for r, output in zip(live, outputs):
                if not r.future.done():
                    r.future.set_result(output)

    async def shutdown(self) -> None:
        async with self._changed:
            self._closing = True
            self._changed.notify_all()
        # shield: a cancelled shutdown caller must not kill the flush for everyone.
        await asyncio.shield(self._worker)

Notes

solution.pySaved
import asyncio
from collections import deque


class DynamicBatcher:
    def __init__(self, batch_size: int, max_wait_seconds: float, batch_fn):
        """Start the background batching task. ValueError on non-positive arguments."""
        raise NotImplementedError

    async def submit(self, item):
        """Wait for item's batch to run and return its output. RuntimeError after shutdown."""
        raise NotImplementedError

    async def shutdown(self) -> None:
        """Reject new requests, flush accepted ones, wait for the background task."""
        raise NotImplementedError
Python loads on first run

Run checks the 2 example tests. Submit runs all 16 and marks the problem solved when they pass.