No. 12medium25 min15 tests

Inference Worker Pool

Description

You have a batch of inference requests and an async model client. Calling the client for every request at once would overload the GPU, so you run them through a fixed pool of workers that pull from one shared queue.

Write run_worker_pool(requests, infer_fn, num_workers):

async def run_worker_pool(requests: list[dict], infer_fn, num_workers: int) -> list[dict]:
    ...
  • Each request is {"id": str, "prompt": str}.
  • infer_fn(prompt) is an async function that returns a string or raises.
  • Start exactly num_workers worker tasks that pull requests from a shared asyncio.Queue. At most num_workers calls to infer_fn run at the same time.
  • Process every request exactly once.
  • A request that succeeds produces {"id": id, "status": "ok", "output": output}.
  • A request whose infer_fn raises an Exception produces {"id": id, "status": "error", "error": str(exc)}. One failure must not stop the worker or affect other requests.
  • Return one result per request, in the same order as requests, regardless of completion order. Ids are not guaranteed to be unique, so match results by position, not by id.
  • When the function returns, every worker task has finished. Nothing is left running in the background.
  • If the caller cancels run_worker_pool, the cancellation propagates to the caller, and every in-flight infer_fn call and worker task is cancelled before it does. Cancellation is not an error result.

Example

async def infer(prompt):
    if prompt == "bad":
        raise RuntimeError("GPU unavailable")
    return prompt.upper()

await run_worker_pool(
    [{"id": "a", "prompt": "good"}, {"id": "b", "prompt": "bad"}, {"id": "c", "prompt": "fine"}],
    infer,
    num_workers=2,
)
# [
#   {"id": "a", "status": "ok", "output": "GOOD"},
#   {"id": "b", "status": "error", "error": "GPU unavailable"},
#   {"id": "c", "status": "ok", "output": "FINE"},
# ]

Constraints

  • 0 <= len(requests) <= 10^4
  • 1 <= num_workers <= 100. It may be larger than len(requests).
  • All inputs are valid.

Solution

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

Approach

Put every request on the queue with its input index, then one None sentinel per worker. Each worker loops on queue.get() until it pulls a sentinel. Because every worker takes exactly one sentinel, all of them exit once the real work is gone, and asyncio.gather over the workers is the whole shutdown.

Write each result into a preallocated list at the request's index. That gives input order for free, whatever order the workers finish in.

Wrap only the infer_fn call in try/except Exception. The worker records the error and moves on to the next item, so one bad request never kills a worker.

Filling the queue before starting the workers is fine here because the input is a finite list. With an unbounded producer you would use a maxsize and put while the workers run.

Complexity

O(n) time over the requests plus the inference calls themselves. O(n) space for the queue and the results list. At most num_workers inference calls are in flight.

Pitfalls

  • Catching the exception outside the worker loop. The worker dies after its first failure and the remaining items are never processed, so gather or join hangs.
  • Appending results as they finish. That returns completion order, not input order.
  • Using asyncio.gather(*[infer_fn(...) for ...]) with no limit. It works on small inputs and launches 10,000 concurrent GPU calls on large ones.
  • Forgetting the sentinels and returning after queue.join(). The workers are still blocked on get(), so they leak as pending tasks.
  • Catching BaseException. That swallows CancelledError and makes the pool impossible to cancel.
  • Starting workers with create_task and waiting on queue.join(). If the caller is cancelled during the join, nothing cancels the workers and they keep calling infer_fn in the background. Awaiting asyncio.gather over the workers (or using asyncio.TaskGroup) cancels them along with the caller.
  • Keying results by id. Ids can repeat, so two requests would share one result. Index by position.

Follow-ups interviewers ask

  • Add a per-request timeout. Wrap the call in asyncio.wait_for or asyncio.timeout and report "status": "timeout".
  • Retry transient errors with backoff before giving up on a request.
  • Stream results back as they finish with an async generator, while still tagging each with its index.

Reference solution

import asyncio


async def run_worker_pool(requests: list[dict], infer_fn, num_workers: int) -> list[dict]:
    queue: asyncio.Queue = asyncio.Queue()
    results: list[dict | None] = [None] * len(requests)

    for index, request in enumerate(requests):
        queue.put_nowait((index, request))
    # One sentinel per worker: each worker exits after taking exactly one.
    for _ in range(num_workers):
        queue.put_nowait(None)

    async def worker() -> None:
        while (job := await queue.get()) is not None:
            index, request = job
            try:
                output = await infer_fn(request["prompt"])
                results[index] = {"id": request["id"], "status": "ok", "output": output}
            except Exception as exc:
                results[index] = {"id": request["id"], "status": "error", "error": str(exc)}

    await asyncio.gather(*(worker() for _ in range(num_workers)))
    return results

Notes

solution.pySaved
import asyncio


async def run_worker_pool(requests: list[dict], infer_fn, num_workers: int) -> list[dict]:
    """
    Run every request through infer_fn using exactly num_workers worker tasks
    that share one asyncio.Queue.

    Return one result dict per request, in input order:
      {"id": id, "status": "ok", "output": output}
      {"id": id, "status": "error", "error": str(exc)}
    """
    raise NotImplementedError
Python loads on first run

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