Skip to content

asyncio patterns that survive production

The asyncio constructs and rules of thumb that hold up under real load — task groups, cancellation, timeouts, bounded concurrency, and the patterns that blow up at 3 a.m.

asyncio looks simple on first read and breaks in surprising ways under load. The constructs you use during a hackathon — asyncio.gather with raw coroutines, asyncio.sleep for backoff, no timeout anywhere — are not the constructs that survive a year in production. This article is a reference for the patterns we actually run in client systems: structured concurrency via TaskGroup, explicit timeouts, bounded concurrency via semaphore, and the half-dozen anti-patterns that cause the 3 a.m. pages.

How to verify

Look at the running event loop and what it’s stuck on:

pip install py-spy
sudo py-spy dump --pid $(pgrep -f 'uvicorn.*app')
pip install aiomonitor
# in app: aiomonitor.start_monitor(loop)
nc localhost 50101
# then: ps; where TASK_ID; signal_SIGTERM
journalctl -u fastapi-app -n 200 | grep -E 'asyncio|never awaited|CancelledError'

py-spy dump on a Python 3.11+ process shows the awaiting stack of every task — the single most useful diagnostic when the loop is wedged.

What’s happening

An asyncio program runs one event loop on one thread per process. Coroutines suspend on await; the loop runs other ready coroutines while one is waiting on I/O. There is no preemption — a coroutine that doesn’t await (or that calls a blocking function like time.sleep, requests.get, or os.read on a regular file) holds the loop and every other task stalls.

asyncio.gather runs N coroutines and returns when all complete. If one raises, the others continue to completion in the background — unless return_exceptions=False, in which case the exception propagates but the in-flight coroutines are not cancelled by default. The result is half-finished work and resources held open. TaskGroup (3.11+) fixes this: if one task raises, the others are cancelled and the group raises an ExceptionGroup.

Cancellation is cooperative. When you cancel a task, the loop injects a CancelledError at its next await. Code that catches BaseException or that runs CPU-bound work between awaits delays cancellation indefinitely. Always re-raise CancelledError after cleanup; never catch and swallow it.

The decision

Default patterns for production async code:

  1. Structured concurrency with TaskGroup for any parallel I/O:

    async with asyncio.TaskGroup() as tg:
        t1 = tg.create_task(fetch_user(uid))
        t2 = tg.create_task(fetch_orders(uid))
    user, orders = t1.result(), t2.result()

    If either raises, both are cancelled, resources close, and an ExceptionGroup propagates.

  2. Explicit timeout on every external call:

    async with asyncio.timeout(5.0):
        resp = await http.get(url)

    asyncio.timeout (3.11+) is a context manager — cleaner than wait_for and composes properly with TaskGroup. Without a timeout, a network glitch turns into a hung worker.

  3. Bounded concurrency via semaphore when fanning out to an external service:

    sem = asyncio.Semaphore(20)
    
    async def fetch_one(url):
        async with sem:
            async with asyncio.timeout(5.0):
                return await http.get(url)
    
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch_one(u)) for u in urls]

    Without the semaphore, len(urls) == 10_000 opens 10k sockets and the downstream API rate-limits all of them. With it, you get a constant 20-in-flight pipeline.

  4. Never run CPU-bound work in the loop. Offload to a thread pool for one-off CPU work, a process pool for sustained CPU work, or a worker queue (Celery, RQ) for anything substantial:

    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(None, cpu_heavy_function, data)

    The default executor is a thread pool of min(32, os.cpu_count() + 4) — fine for the occasional sync call, not a strategy for CPU saturation.

  5. Never call sync I/O from an async function. requests.get, time.sleep, psycopg2.connect, open() on a slow filesystem — all block the loop. Use the async equivalent (httpx, asyncio.sleep, asyncpg, aiofiles) or wrap in run_in_executor.

  6. Background tasks need a reference. asyncio.create_task(...) without storing the returned Task is the most common bug:

    _background_tasks: set[asyncio.Task] = set()
    
    def fire_and_forget(coro):
        task = asyncio.create_task(coro)
        _background_tasks.add(task)
        task.add_done_callback(_background_tasks.discard)

    Without the reference, the garbage collector may collect the task mid-execution and you get Task was destroyed but it is pending! warnings — the work silently disappears.

Common pitfalls

  • await some_coro() inside a for loop is sequential — N requests take N × latency. Use TaskGroup or asyncio.gather for parallelism.
  • Catching Exception instead of specific exceptions: this swallows asyncio.CancelledError on Python < 3.8 and breaks cancellation. Always catch by type or re-raise CancelledError explicitly.
  • Reusing an aiohttp.ClientSession or httpx.AsyncClient across requests is correct — creating one per request opens and closes the connection pool on every call, defeating the whole point.
  • A signal.SIGINT handler that does loop.stop() without cancelling tasks leaves the event loop in a half-shut state and connections leak. Use asyncio.run for top-level entry — it handles graceful shutdown.
  • asyncio.Queue.put_nowait in a producer that outpaces the consumer raises QueueFull — bound the queue with maxsize and await put() instead, applying backpressure naturally.

For the runtime that serves these coroutines under load — Uvicorn workers — see Deploying FastAPI under Uvicorn workers. Stack Harbor’s managed operations practice insists on TaskGroup over gather, explicit timeouts on every external call, and a semaphore on every fan-out as the minimum bar for async Python code in production — these three rules eliminate the majority of async-related incidents we see.