Asyncio Worker Pool in Python: Queues, Backpressure and Graceful Shutdown

Build an asyncio worker pool in Python: Semaphore vs pool, bounded queues, per-job timeouts, sentinels, grace periods and SIGTERM.

Guide ยท 8 min read

An asyncio worker pool is a fixed number of worker tasks that take jobs from a shared asyncio.Queue and process them concurrently, so at most N jobs run at once no matter how many are queued. It is the right shape when the input is large, unbounded or arrives over time, and when you want backpressure: with a bounded queue, the producer's await queue.put() waits while the workers are behind. A correct pool has three more properties that interviews check: one failing job never kills a worker, results can be matched back to their inputs, and shutdown either drains the queue or stops within a deadline without leaving tasks running. In Python 3.12 that is asyncio.Queue, asyncio.TaskGroup, a sentinel per worker and asyncio.timeout.

The asyncio interview guide shows the basic pool with queue.join(). This guide goes further: choosing between a semaphore and a pool, streaming input with backpressure, per-job timeouts, graceful shutdown with a grace period, and handling SIGTERM. Every snippet is complete and runs on Python 3.12 or newer.

Semaphore or worker pool?

Both cap concurrency. The difference is how many tasks exist.

import asyncio


async def job(i: int) -> int:
    await asyncio.sleep(0)
    return i


async def with_semaphore(n: int, limit: int) -> int:
    sem = asyncio.Semaphore(limit)

    async def one(i: int) -> int:
        async with sem:
            return await job(i)

    async with asyncio.TaskGroup() as tg:
        for i in range(n):
            tg.create_task(one(i))
        return len(asyncio.all_tasks()) - 1


async def with_pool(n: int, workers: int) -> int:
    queue: asyncio.Queue = asyncio.Queue(maxsize=workers * 2)

    async def worker() -> None:
        while (i := await queue.get()) is not None:
            await job(i)

    async with asyncio.TaskGroup() as tg:
        for _ in range(workers):
            tg.create_task(worker())
        peak = len(asyncio.all_tasks()) - 1
        for i in range(n):
            await queue.put(i)
        for _ in range(workers):
            await queue.put(None)
    return peak


print("semaphore tasks:", asyncio.run(with_semaphore(10_000, limit=8)))  # semaphore tasks: 10000
print("pool tasks:", asyncio.run(with_pool(10_000, workers=8)))  # pool tasks: 8

The semaphore version creates all 10,000 tasks up front and lets 8 run at a time. That is simple and fine for thousands of items. For millions, or for an input that never ends, such as messages from a socket, the task objects themselves become the memory problem, and the pool's fixed 8 tasks plus a queue of 16 items is the better shape. The pool also gives you backpressure for free: the producer waits at put instead of reading the whole input into memory.

A pool with ordered results and isolated failures

This version uses TaskGroup, so no worker can outlive the function, and a sentinel per worker for shutdown. Each job carries its input index, and results go into a list slot by index, because jobs finish out of order.

import asyncio
import random

DONE = object()


async def fetch(url: str) -> str:
    await asyncio.sleep(random.uniform(0.001, 0.01))
    if "bad" in url:
        raise ValueError(f"cannot fetch {url}")
    return url.upper()


async def run_pool(urls: list[str], workers: int) -> list:
    queue: asyncio.Queue = asyncio.Queue(maxsize=workers * 2)
    results: list = [None] * len(urls)

    async def worker() -> None:
        while (entry := await queue.get()) is not DONE:
            index, url = entry
            try:
                results[index] = await fetch(url)
            except Exception as exc:
                results[index] = exc

    async with asyncio.TaskGroup() as tg:
        for _ in range(workers):
            tg.create_task(worker())
        for entry in enumerate(urls):
            await queue.put(entry)
        for _ in range(workers):
            await queue.put(DONE)
    return results


urls = ["a", "b", "bad-c", "d", "e"]
print(asyncio.run(run_pool(urls, workers=2)))
# ['A', 'B', ValueError('cannot fetch bad-c'), 'D', 'E']

The marks are in the details.

  • except Exception inside the loop. A job's error is stored as its result and the worker moves on. Without it, the error escapes, the worker dies, and in a TaskGroup the whole pool is cancelled. In the queue.join() style, the dead worker never calls task_done() and join() hangs forever.
  • One sentinel per worker. Each worker exits after reading one, so W workers need W sentinels. A private object() is safer than None if None could be a real job.
  • The sentinels go in after the real jobs. The queue is FIFO, so every real job is taken before any worker sees a sentinel.
  • A bounded queue. maxsize=workers * 2 keeps a little work buffered without reading the whole input into memory.

queue.join() plus cancelling the workers is the other standard shutdown. Use sentinels when workers should drain and exit on their own, as in a pipeline, and join() plus cancel when you own the pool and the producer. join() only works if every get() is matched by a task_done() in a finally.

Streaming input and pipelines

The producer doesn't need a list. Any async iterator works, and because the queue is bounded, a fast producer is slowed to the workers' pace instead of buffering everything.

import asyncio

DONE = object()


async def read_lines(n: int):
    for i in range(n):
        yield f"line {i}"


async def main() -> None:
    raw: asyncio.Queue = asyncio.Queue(maxsize=4)
    parsed: asyncio.Queue = asyncio.Queue(maxsize=4)
    peak = 0
    total = 0

    async def produce() -> None:
        nonlocal peak
        async for line in read_lines(1000):
            await raw.put(line)
            peak = max(peak, raw.qsize())
        await raw.put(DONE)

    async def parse() -> None:
        while (line := await raw.get()) is not DONE:
            await asyncio.sleep(0)
            await parsed.put(len(line))
        await parsed.put(DONE)

    async def sink() -> None:
        nonlocal total
        while (size := await parsed.get()) is not DONE:
            total += size

    async with asyncio.TaskGroup() as tg:
        tg.create_task(produce())
        tg.create_task(parse())
        tg.create_task(sink())
    print(f"total={total} peak raw queue={peak}")  # total=7890 peak raw queue=4


asyncio.run(main())

The producer can read lines far faster than the parser handles them, yet the first queue never held more than four. Each put on a full queue suspended the producer until the parser took an item. Each stage forwards the sentinel to the next when it finishes, so shutdown runs down the pipeline in order. With several workers in one stage, the last worker to finish forwards the sentinel, or the stage's owner does after all of them exit.

Per-job timeouts

One hung job should not take a worker out of the pool forever. Put asyncio.timeout around the job inside the worker, and record a TimeoutError like any other failure.

import asyncio

DONE = object()


async def process(seconds: float) -> str:
    await asyncio.sleep(seconds)
    return f"slept {seconds}"


async def main() -> None:
    jobs = [0.01, 5.0, 0.01, 0.02]
    results: list = [None] * len(jobs)
    queue: asyncio.Queue = asyncio.Queue()

    async def worker() -> None:
        while (entry := await queue.get()) is not DONE:
            index, seconds = entry
            try:
                async with asyncio.timeout(0.1):
                    results[index] = await process(seconds)
            except Exception as exc:
                results[index] = exc

    for entry in enumerate(jobs):
        queue.put_nowait(entry)
    async with asyncio.TaskGroup() as tg:
        for _ in range(2):
            tg.create_task(worker())
            queue.put_nowait(DONE)
    print([type(r).__name__ if isinstance(r, Exception) else r for r in results])


asyncio.run(main())
# ['slept 0.01', 'TimeoutError', 'slept 0.01', 'slept 0.02']

TimeoutError is a subclass of Exception, so the worker's existing handler catches it. A CancelledError from outside, such as the pool itself being cancelled, is not, and still stops the worker.

Graceful shutdown with a grace period

In a long-running service, shutdown means: stop taking new jobs, let in-flight jobs finish for a few seconds, then cancel whatever is still running and report it. A shared asyncio.Event tells workers to stop taking jobs, and asyncio.timeout around the drain bounds the wait.

import asyncio


class Pool:
    def __init__(self, workers: int) -> None:
        self.queue: asyncio.Queue = asyncio.Queue()
        self.stopping = asyncio.Event()
        self.done: list[str] = []
        self.tasks = [asyncio.create_task(self._worker()) for _ in range(workers)]

    async def _worker(self) -> None:
        while not self.stopping.is_set():
            name, seconds = await self.queue.get()
            try:
                await asyncio.sleep(seconds)
                self.done.append(name)
            except Exception:
                pass
            finally:
                self.queue.task_done()

    def submit(self, name: str, seconds: float) -> None:
        if self.stopping.is_set():
            raise RuntimeError("pool is shutting down")
        self.queue.put_nowait((name, seconds))

    async def shutdown(self, grace: float) -> list[str]:
        self.stopping.set()
        dropped = []
        while not self.queue.empty():
            dropped.append(self.queue.get_nowait()[0])
            self.queue.task_done()
        try:
            async with asyncio.timeout(grace):
                await self.queue.join()
        except TimeoutError:
            pass
        for task in self.tasks:
            task.cancel()
        await asyncio.gather(*self.tasks, return_exceptions=True)
        return dropped


async def main() -> None:
    pool = Pool(workers=2)
    for name, seconds in [("quick", 0.01), ("hung", 10), ("queued-1", 0.01), ("queued-2", 0.01)]:
        pool.submit(name, seconds)
    await asyncio.sleep(0.005)
    dropped = await pool.shutdown(grace=0.1)
    print("finished:", pool.done, "| never started:", dropped)


asyncio.run(main())
# finished: ['quick'] | never started: ['queued-1', 'queued-2']

After 5 ms both workers are busy, one with quick and one with hung. Shutdown removes the two jobs that never started, so the caller can requeue or report them, waits up to 100 ms for in-flight work, sees quick finish, and cancels hung when the grace period ends. The gather(..., return_exceptions=True) after cancelling waits until every worker has actually exited, so nothing is left running when shutdown returns.

Whether queued jobs should be dropped or drained depends on the spec. A batch job usually drains them. A web server shutting down for a deploy usually stops taking new work and finishes only what it has started. Ask.

Handling SIGTERM

Container platforms stop a service by sending SIGTERM and then, after a grace period, SIGKILL. Register a handler on the event loop that triggers your shutdown, instead of catching KeyboardInterrupt. loop.add_signal_handler is available on Unix only.

import asyncio
import os
import signal


async def main() -> None:
    loop = asyncio.get_running_loop()
    stop = asyncio.Event()
    loop.add_signal_handler(signal.SIGTERM, stop.set)

    async def serve() -> None:
        while True:
            await asyncio.sleep(0.01)

    server = asyncio.create_task(serve())
    loop.call_later(0.05, os.kill, os.getpid(), signal.SIGTERM)
    await stop.wait()
    server.cancel()
    await asyncio.gather(server, return_exceptions=True)
    print("received SIGTERM, shut down cleanly")


asyncio.run(main())
# received SIGTERM, shut down cleanly

The snippet sends itself SIGTERM after 50 ms to stand in for the platform. In a real service, stop.wait() would be followed by the pool's shutdown(grace=...), with the grace period set a little below the platform's.

Follow-ups interviewers ask

  • How many workers? For I/O-bound jobs, as many as the downstream service tolerates, which is often a rate limit or connection pool size rather than a CPU count. For CPU-bound work, asyncio workers don't help at all. Use ProcessPoolExecutor through loop.run_in_executor, or asyncio.to_thread for blocking calls that release the GIL.
  • Retries. Retry inside the worker with backoff, or put the failed job back on the queue with an attempt count. Requeueing frees the worker during the backoff. See the retry guide.
  • Results as they finish. Put results on an output queue instead of into slots, and let the consumer read them in completion order.
  • Priorities. Use asyncio.PriorityQueue with (priority, seq, job) tuples. The sequence number keeps ties FIFO and stops Python from comparing job objects.
  • Python 3.13's Queue.shutdown(). It makes get() raise QueueShutDown once the queue is empty, which replaces sentinels. Mention it, but write the sentinel version if the target is 3.12.

Common mistakes

  • An exception escaping the worker loop. The pool shrinks silently, or join() hangs.
  • task_done() outside finally. One error and join() never returns.
  • Fewer sentinels than workers. The extra workers wait forever.
  • An unbounded queue fed from a large input. Memory grows with the input, and there is no backpressure.
  • Cancelling workers without awaiting them. Their cleanup may not have run when the function returns.
  • time.sleep or blocking I/O in a worker. It blocks every worker, since they share one thread.

Practise it

The Inference Worker Pool problem asks for a fixed pool of asyncio workers sharing one queue, with isolated failures and results in input order, checked by hidden tests on real CPython in your browser. Budget 25 minutes.

  1. 06Sliding Window Rate Limitermedium

    Build a per-user sliding window log rate limiter that allows at most N requests in any window of W seconds.

  2. 12Inference Worker Poolmedium

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

  3. 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.

  4. 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.

  5. 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.

  6. 22Async Retry with Exponential Backoffmedium

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

  7. 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 asyncio, queue and concurrency topic pages collect related problems. The dynamic batching guide applies the same queue and shutdown patterns to batching requests.

Frequently asked questions

How do I create a worker pool with asyncio?

Create an asyncio.Queue, start a fixed number of worker tasks that loop on await queue.get() and process each job, and put the jobs on the queue. Catch exceptions per job inside the loop, and stop the workers with one sentinel each or with queue.join() followed by cancelling them.

Should I use asyncio.Semaphore or a worker pool to limit concurrency?

A Semaphore is simplest when the input is a list of a few thousand items, because one task per item is cheap. A worker pool is better for very large or unbounded input, since it keeps a fixed number of tasks and a bounded queue gives backpressure to the producer.

How do I gracefully shut down asyncio workers?

Stop accepting new jobs, decide whether to drain or drop queued jobs, wait for in-flight jobs with a timeout such as asyncio.timeout around queue.join(), then cancel the remaining workers and await them with gather(..., return_exceptions=True) so none are left running.

Why does asyncio queue.join() hang forever?

join() waits until task_done() has been called once for every item put on the queue. If a worker raises before calling task_done(), or dies, the count never reaches zero. Call task_done() in a finally block and catch per-job exceptions inside the worker loop.

How many workers should an asyncio pool have?

For I/O-bound work, as many as the downstream system tolerates, often set by its rate limit or connection pool size. More asyncio workers do not help CPU-bound work, which belongs in a process pool.

What is asyncio.Queue.shutdown?

A method added in Python 3.13 that closes the queue: put() raises QueueShutDown, and get() raises it once the queue is empty, so workers can exit without sentinels. Code that must run on Python 3.12 still needs sentinels or join() and cancel.