Skip to content

Async Python: asyncio, Event Loop, await, Tasks, Blocking Calls, Thread Pools ​

"The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses." — Python documentation, "Event Loop", docs.python.org/3/library/asyncio-eventloop.html

Summary: asyncio runs many coroutines on ONE thread: an async def function returns a coroutine object, a Task wraps it and puts it on the event loop, and an await on something that is not ready yet (a socket read, a timer, a pending Future) is where the task gives the thread back, so the loop can ask the operating system which I/O is ready (a selector with epoll/kqueue on Unix, IOCP completions in the Windows proactor loop) and resume whichever task can continue. An await on something already finished does not switch at all; await asyncio.sleep(0) is the explicit yield. That makes thousands of concurrent network waits cheap, and it makes one blocking call (time.sleep, requests, a sync database driver, a CPU loop) expensive for everybody, because nothing else on that loop runs until it returns. Blocking work goes to threads (asyncio.to_thread, run_in_executor, Starlette's run_in_threadpool), CPU-bound work to processes, and the GIL decides which of the two actually runs in parallel. Focus: concurrency vs parallelism, the GIL and the free-threaded build, I/O-bound vs CPU-bound, blocking vs non-blocking I/O, the event loop (selectors, callbacks, uvloop), coroutines, async def, await, awaitables, Futures and Tasks, create_task and task references, gather (return_exceptions), TaskGroup, as_completed, wait (FIRST_COMPLETED), cancellation (CancelledError, shield), timeouts (wait_for, asyncio.timeout), structured concurrency with AnyIO cancel scopes, Lock/Semaphore/Event/Condition/Queue, producer/consumer and back-pressure, to_thread/run_in_executor/thread and process pools, async generators and async context managers, contextvars, debug mode and the warnings it prints, httpx.AsyncClient and connection limits, how Uvicorn, Starlette and FastAPI use the loop, testing with pytest-asyncio and the AnyIO plugin, graceful shutdown, and the Go and PHP equivalents. Learning goal: Read any async Python code and say where it waits, what runs while it waits and what would block the loop; fan out I/O with a bound and a timeout; keep a reference to every task you start and cancel it cleanly on shutdown; move blocking and CPU work to the right pool; and prove each of those with a test and a measurement.

This page owns the language-level concurrency model. Its neighbours are linked, not re-taught: the rule "async def routes run on the loop, def routes run in a thread pool" and its first measurement are in FastAPI Fundamentals; type hints and Pydantic are in Typing & Pydantic v2; AsyncSession, async engines and drivers are in SQLAlchemy 2 & SQLModel; BackgroundTasks, retries and calling external APIs with httpx are in Background Tasks, Caching & External APIs; Uvicorn/Gunicorn workers, lifespan in production and performance tuning are in FastAPI in Production; fixtures and test layout are in Testing FastAPI. The design-level view of concurrency (actors, shared state, CSP) is in Designing for Concurrency; the Go twins are Goroutines & Channels, context, Worker Pools & Pipelines and Race Conditions & Deadlocks.

Facts below were checked against the Python 3.15 documentation (asyncio: tasks, event loop, queues, synchronisation primitives, subprocesses, developing with asyncio, exceptions, runners, platforms; concurrent.futures, contextvars, threading, multiprocessing, selectors, the glossary, the free-threading HOWTO, "What's New" 3.4 to 3.14), PEPs 492, 525, 530, 567, 654, 703, 779 and 3156, the CPython 3.9 source of asyncio/base_events.py, tasks.py, threads.py and concurrent/futures/thread.py, the AnyIO 4 docs (tasks, cancellation, synchronisation, threads, testing), the uvloop README, the httpx docs (async, resource limits, timeouts, clients), the FastAPI "Concurrency and async / await" page, Starlette's thread-pool page and concurrency.py, the Uvicorn settings page, the pytest-asyncio docs, the Go tour and the "pipelines" article, the Laravel 13 Octane docs, the PHP Fibers manual, ReactPHP and the Swoole README. The page is written for Python 3.12+. The snippets, however, ran on the only interpreter on the build machine, CPython 3.9.6, so the snippet project pins the newest releases that install there (anyio 4.12.1, httpx 0.28.1, FastAPI 0.128.8, Starlette 0.49.3, Uvicorn 0.39.0 with uvloop 0.23.0, pytest 8.4.2, pytest-asyncio 1.2.0); the resolved set is in the project's requirements.lock. Everything quoted as "real" below is what that run printed. asyncio.TaskGroup and asyncio.timeout() arrived in 3.11 and do not exist on 3.9 (real: AttributeError: module 'asyncio' has no attribute 'TaskGroup'), so their code is in the project behind a version check, their two tests are skipped on 3.9, and their behaviour is described from the docs and marked "expected, not run". The same structured-concurrency behaviour is shown for real with AnyIO task groups and cancel scopes, which run on 3.9.

Page map ​

If you are looking forGo to
The tables you can memorise in one minuteEverything in one minute
Why one thread can serve 10,000 connectionsWhy it exists
Generators, Tulip, async/await, TaskGroup, free threadingWhere it comes from
A dashboard endpoint before and after, with timingsPython
Concurrency is not parallelismConcurrency vs parallelism
GIL, python3.13t, PYTHON_GILThe GIL and free-threaded Python
Which calls blockI/O-bound, CPU-bound, blocking calls
selectors, epoll, kqueue, uvloopThe event loop
async def, await, coroutine, awaitable, FutureCoroutines and awaitables
create_task, fire and forget, "Task was destroyed"Tasks
gather(..., return_exceptions=True)gather
async with asyncio.TaskGroup()TaskGroup
as_completed, wait(FIRST_COMPLETED)as_completed and wait
task.cancel(), CancelledError, shieldCancellation
wait_for, asyncio.timeout, TimeoutErrorTimeouts
AnyIO task groups, move_on_after, cancel scopesStructured concurrency and AnyIO
Lock, Semaphore, Event, ConditionSynchronisation primitives
asyncio.Queue, maxsize, task_done, joinQueues, producer/consumer, back-pressure
to_thread, run_in_executor, default executor sizeRunning blocking code
ProcessPoolExecutor, multiprocessingCPU-bound work
async for, async with, @asynccontextmanagerAsync generators and context managers
Request id in every log linecontextvars
asyncio.run, run_until_complete, nest_asyncioEntry points and nested loops
PYTHONASYNCIODEBUG, slow callbacks, "never awaited"Debugging
httpx.AsyncClient, Limits, timeoutsAsync HTTP clients
Uvicorn's loop, def routes, run_in_threadpoolHow FastAPI, Starlette and Uvicorn use the loop
@pytest.mark.asyncio, @pytest.mark.anyioTesting async code
Stopping tasks on SIGTERMGraceful shutdown
Async database access, sync driversDatabases from async code
How a Task drives a coroutine, exact error texts, version matrixMechanics
The classic bugs and their fixesSolving the classic problems
asyncio vs threads vs processes vs GoChoosing
Monolith to distributed systemIn architecture
Reproduce every number on your machineLab
Swoole, Octane, ReactPHP, FibersFor PHP/Laravel developers
Goroutines vs tasks, channels vs QueueThe Go angle

Everything in one minute ​

The vocabulary in one table. Each row is unpacked in the concept catalogue.

TermWhat it isPlain wordsPython API
Coroutine functionA function defined with async def"A recipe that can pause"async def fetch(): ...
CoroutineWhat calling it returns; runs only when awaited or wrapped in a Task"The paused recipe, not started"fetch()
awaitSuspend this coroutine until the awaitable is done"Wait here, let others run"await fetch()
AwaitableAnything await accepts: coroutine, Task, Future, objects with __await__"Something you can wait on"inspect.isawaitable
FutureLow-level placeholder for a result set later"An empty box someone will fill"loop.create_future()
TaskA Future that drives a coroutine on the loop"A recipe the kitchen is cooking"asyncio.create_task(coro)
Event loopThe scheduler: timers, ready callbacks, selector"The single waiter"asyncio.get_running_loop()
SelectorOS readiness API used by SelectorEventLoop: epoll, kqueue, poll, select"Which tables raised a hand?"selectors.DefaultSelector
ProactorCompletion-based loop on Windows (IOCP): the OS reports finished operations, not ready sockets"Tell me when the dish is done"asyncio.ProactorEventLoop
Blocking callA call that holds the thread until it returns"The waiter stuck at one table"time.sleep, requests.get
Thread poolWorker threads for blocking calls"Kitchen helpers"asyncio.to_thread, run_in_executor
Process poolWorker processes for CPU work"Another kitchen"ProcessPoolExecutor
GILOne thread runs Python bytecode at a time (default CPython)"One pen for all the clerks"sys._is_gil_enabled() (3.13+)

Which tool for which wait. All numbers are from the Lab (CPython 3.9.6, 12-core Mac).

WorkExampleRight toolWhat goes wrong otherwiseMeasured
Network I/O with an async libraryhttpx.AsyncClient, asyncpg, redis.asyncioawait + gather/TaskGroupnothing; this is the sweet spot20 × 100 ms in 0.14 s
Network I/O with a sync libraryrequests, httpx.Client, boto3, sync DB driverasyncio.to_thread or a def routeinside async def: serial and blocks the loop2.07 s, /health waited 0.55 s
A sleep or backoffretry delayawait asyncio.sleeptime.sleep freezes every taskheartbeat gap 0.211 s vs 0.013 s
File I/O, sqlite3read a report, local DBto_threadblocks the loop(see Running blocking code)
Pure-Python CPUparsing, pricing, image work in PythonProcessPoolExecutorthreads give no speed-up (GIL)4 jobs: inline 0.42 s, threads 0.37 s, processes 0.18 s
C extension that releases the GILhashlib, zlib, NumPythread poolnothing; threads run in parallelnot measured
Too many concurrent calls10,000 URLsSemaphore or bounded Queuesockets, memory, upstream overloadSemaphore(5): 0.44 s in 4 waves

Combinators. What each one returns and who cancels what.

APIReturnsOn first errorOn timeoutCancels the others?Since
await gather(*aws)list, input orderraises it; the rest keep runningn/ano (only if gather itself is cancelled)3.4
gather(*aws, return_exceptions=True)list with exceptions as valuesnothing raisedn/ano3.4
async with TaskGroup()(tasks hold results)cancels siblings, raises ExceptionGroupcombine with timeout()yes3.11
as_completed(aws)iterator in completion orderraised when you await that itemTimeoutErrorno3.4 (async iteration 3.13)
wait(aws, return_when=...)(done, pending) setsFIRST_EXCEPTION returns earlyreturns, no errorno3.4
wait_for(aw, t)the resultraises itTimeoutError, inner cancelledyes, the inner awaitable3.4
async with timeout(t)(block)raises itTimeoutError, block cancelledyes, the current task's work3.11
shield(aw)the resultraises itn/aprotects the inner from outer cancel3.4

What prints when something is wrong. Real output from the snippet run.

MistakeWhat you seeWhere
Called a coroutine function without awaitRuntimeWarning: coroutine 'forgotten' was never awaitedstderr, always
Task failed, nobody read the resultTask exception was never retrievedlogger asyncio, at garbage collection
Loop closed with a task still pendingTask was destroyed but it is pending!logger asyncio
A callback held the loop > 100 msExecuting <Task pending name='Task-1' ...> took 0.213 secondslogger asyncio, debug mode only
asyncio.run() inside a running loopRuntimeError: asyncio.run() cannot be called from a running event loopexception
asyncio.TaskGroup on 3.9/3.10AttributeError: module 'asyncio' has no attribute 'TaskGroup'exception

Why it exists ​

A backend spends most of its life waiting: for a database row, an upstream HTTP call, a Redis reply, a client that reads slowly. A thread per connection makes waiting easy to write, but each thread costs a stack, a scheduler entry and, in CPython, a turn at the GIL; tens of thousands of mostly idle threads are expensive. An event loop inverts the model: one thread keeps a list of everything that is waiting, asks the operating system in one call which of those waits are over, and runs the code that can continue. PEP 492 states the goal of the syntax that made this pleasant: "The growth of Internet and general connectivity has triggered the proportionate need for responsive and scalable code. This proposal aims to answer that need by making writing explicitly asynchronous, concurrent Python code easier and more Pythonic."

Thread per request (WSGI, PHP-FPM, def routes)Event loop (asyncio, async def routes)
The OS switches threads at any instruction (preemptive)Tasks switch only at an await that suspends (cooperative)
A blocking call blocks one threadA blocking call blocks every task on the loop
Memory per waiting request: a thread stackMemory per waiting request: a coroutine frame and a Task
Shared state needs locks everywhereShared state is safe between two awaits; locks only around awaits
Any library worksLibraries must be async (or be offloaded to threads)
Concurrency limited by thread count (FastAPI: 40 tokens)Concurrency limited by sockets, memory and your own bounds
CPU parallelism: threads, if the GIL allowsCPU parallelism: none on the loop; use processes

An everyday picture. A restaurant with one waiter (the event loop) and a kitchen. The waiter takes table 1's order, gives it to the kitchen and, instead of standing at the pass until the dish is ready, goes to table 2 (await). When a bell rings (the selector says a socket is ready), he picks up the dish and serves it. One waiter can serve fifty tables because almost all the time is cooking time, not walking time. The rule that makes it work: the waiter never does anything slow himself. If he sits down to peel potatoes (time.sleep, a sync driver, a CPU loop), every table waits, even those whose food is ready. Slow manual jobs go to kitchen helpers (the thread pool); a job that needs real extra hands, such as baking a hundred cakes (CPU work), goes to a second kitchen with its own staff (a process pool), because the helpers in this kitchen share one oven (the GIL). The reservation book with a cap of ten tables at a time is a Semaphore; the order rail with room for five tickets is a bounded Queue; a waiter who walks away from a table that took too long is a timeout; a manager who sends the whole party home when one guest has a problem is a TaskGroup.

Three common misunderstandings, up front ​

  1. "async def makes code run in parallel." It makes it able to wait concurrently. Only one coroutine runs at any instant on a loop; if the work is CPU, async adds overhead and no speed. Measured: 20 sequential 100 ms requests took 2.07 s; the same 20 with a sync client inside async def coroutines under gather() took 2.07 s too, because nothing awaited.
  2. "Calling a coroutine function starts it." It builds a coroutine object and nothing else. Without await (or create_task) it never runs, and Python prints coroutine '...' was never awaited when the object is garbage collected.
  3. "create_task() and forget is fine." The loop keeps only weak references to tasks; a task nobody references "may get garbage collected at any time, even before it's done" (the docs). Its exceptions are also never seen. Keep tasks in a set or a TaskGroup.

Where it comes from ​

Python's coroutines grew out of generators. yield let a function pause; PEP 342 (created 2005-05-10, Python 2.5) let the caller send values back in with send(), which is the mechanism every coroutine scheduler since has used; PEP 380 (created 2009-02-13, Python 3.3) added yield from so a generator could delegate to another. PEP 3156 (created 2012-12-12, author Guido van Rossum; "A reference implementation exists under the code name Tulip") defined the asyncio event loop, transports, protocols and coroutines; Python 3.4 (released March 16, 2014) shipped it as "New provisional API for asynchronous IO (PEP 3156)". Coroutines were still generators decorated with @asyncio.coroutine and written with yield from. PEP 492 (created 2015-04-09, Python 3.5, released September 13, 2015) introduced async def, await, async for and async with, and made "native coroutines" their own type. PEP 525 (3.6) added asynchronous generators, PEP 530 (3.6) asynchronous comprehensions. Python 3.7 (final 2018-06-27) made async and await reserved keywords, added asyncio.run() and the contextvars module (PEP 567, "similar to thread-local storage (TLS), but, unlike TLS, it also allows correctly keeping track of values per asynchronous task"). In 3.8 (final 2019-10-14), "The exception asyncio.CancelledError now inherits from BaseException rather than Exception". 3.9 (final 2020-10-05) added asyncio.to_thread(). 3.11 (final 2022-10-24) added TaskGroup ("For new code this is recommended over using create_task() and gather() directly"), timeout() ("recommended over using wait_for() directly"), Runner and Barrier, plus ExceptionGroup and except* (PEP 654). 3.12 (released October 2, 2023) reported that "The asyncio package has had a number of performance improvements, with some benchmarks showing a 75% speed up" and added eager task factories. 3.13 (released October 7, 2024) added Queue.shutdown(), made as_completed() usable as an async iterator and shipped an experimental free-threaded build (PEP 703). 3.14 (final 2025-10-07) made free-threaded Python officially supported (PEP 779, resolved 2025-06-16), added python -m asyncio ps PID / pstree PID introspection and deprecated the asyncio policy system ("will be removed in Python 3.16"). 3.15 (released 9 October 2026, the version of the docs quoted here) added TaskGroup.cancel().

Outside the standard library, MagicStack's uvloop ("a fast, drop-in replacement of the built-in asyncio event loop … implemented in Cython and uses libuv under the hood") became Uvicorn's default loop where it is installed, and AnyIO (1.0.0 uploaded to PyPI on 2019-05-14) brought Trio-style structured concurrency to asyncio; Starlette and FastAPI are built on it.

1  2005  PEP 342 created (Python 2.5): generators that receive values with send() = the coroutine mechanism
2  2012  PEP 3156 "Tulip" created (2012-12-12); PEP 380 (2009, Python 3.3) had added yield from
3  2014  Python 3.4 (2014-03-16): asyncio, provisional; @asyncio.coroutine + yield from
4  2015  Python 3.5 (2015-09-13): PEP 492 async def / await / async with / async for
5  2016  PEP 525 async generators and PEP 530 async comprehensions created (Python 3.6)
6  2018  Python 3.7 (2018-06-27): asyncio.run(), contextvars (PEP 567), async/await reserved keywords
7  2019  Python 3.8 (2019-10-14): CancelledError becomes a BaseException; AnyIO 1.0.0
8  2020  Python 3.9 (2020-10-05): asyncio.to_thread()
9  2022  Python 3.11 (2022-10-24): TaskGroup, timeout(), Runner, Barrier, ExceptionGroup / except*
10 2023  Python 3.12 (2023-10-02): asyncio up to 75% faster on some benchmarks, eager tasks
11 2024  Python 3.13 (2024-10-07): Queue.shutdown, async-iterable as_completed, free-threaded build (experimental)
12 2025  Python 3.14 (2025-10-07): free threading officially supported (PEP 779), asyncio ps / pstree, policies deprecated
13 2026  Python 3.15 (2026-10-09): TaskGroup.cancel() for an early, non-exceptional exit

Python ​

Before ​

A dashboard endpoint that gathers five sections (orders, invoices, tickets, shipments, reviews) from an internal upstream that answers each call in 100 ms. It is async def, so it looks non-blocking; inside, it uses the sync httpx.Client one call at a time, "renders" with time.sleep, fires an audit task with asyncio.create_task() and drops the reference, and the audit task swallows CancelledError.

py
"""BEFORE: a dashboard endpoint that looks async but blocks the event loop.

Bad design, not broken code: it returns the right JSON on a quiet day.
- a sync HTTP client (httpx.Client) called inside `async def`: one upstream call at a time,
  and the whole loop (every other request) waits with it;
- time.sleep() to "render" inside `async def`;
- fire-and-forget asyncio.create_task() with no reference kept and no error handling;
- CancelledError swallowed in the audit task, so shutdown cannot stop it cleanly.
"""
from __future__ import annotations

import asyncio
import time

import httpx
from fastapi import FastAPI

SECTIONS = ["orders", "invoices", "tickets", "shipments", "reviews"]


def create_app(upstream: str, delay_ms: int = 100) -> FastAPI:
    app = FastAPI(title="dashboard (before)")
    audit_log: list[str] = []
    app.state.audit_log = audit_log

    async def write_audit(user: str) -> None:
        try:
            await asyncio.sleep(0.01)
            audit_log.append(user)
        except asyncio.CancelledError:
            pass  # swallowed: the task reports success even when it was cancelled

    @app.get("/health")
    async def health() -> dict[str, str]:
        return {"status": "ok"}

    @app.get("/dashboard/{user}")
    async def dashboard(user: str) -> dict[str, object]:
        data = {}
        with httpx.Client(base_url=upstream, trust_env=False) as client:  # sync client
            for section in SECTIONS:
                data[section] = client.get(f"/delay/{delay_ms}").json()  # blocks the loop
        time.sleep(0.05)  # "render a chart": blocks the loop again
        asyncio.create_task(write_audit(user))  # no reference kept, errors never seen
        return {"user": user, "sections": data}

    return app

After ​

The same endpoint, async end to end: one httpx.AsyncClient per process opened in the lifespan with explicit Limits and Timeout; the five calls fanned out with gather() under a Semaphore, each bounded by wait_for; a 504 on upstream timeouts; the blocking render moved to asyncio.to_thread(); the audit task kept in a tracked set and drained on shutdown; plus a def route and a run_in_threadpool call to show where FastAPI and Starlette put sync code.

py
"""AFTER: the same endpoint, async end to end, bounded, with timeouts and a clean shutdown.

- one httpx.AsyncClient per process, opened in the lifespan, with explicit connection limits;
- upstream calls fanned out with gather() under a Semaphore, each with a timeout;
- the blocking "render" step moved to a worker thread with asyncio.to_thread();
- background work tracked in a set (strong references) and drained on shutdown;
- a plain `def` route for a blocking library: FastAPI runs it in the AnyIO thread pool.
"""
from __future__ import annotations

import asyncio
import logging
import threading
import time
from contextlib import asynccontextmanager
from typing import AsyncIterator

import httpx
from fastapi import FastAPI, HTTPException
from starlette.concurrency import run_in_threadpool

from app.tasks import BackgroundTasks

log = logging.getLogger(__name__)

SECTIONS = ["orders", "invoices", "tickets", "shipments", "reviews"]


def render_chart(data: dict[str, object]) -> int:
    time.sleep(0.05)  # stands in for a blocking library (PDF, image, legacy SDK)
    return len(data)


def create_app(upstream: str, delay_ms: int = 100, max_in_flight: int = 10, timeout_s: float = 1.0) -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI) -> AsyncIterator[None]:
        limits = httpx.Limits(max_connections=max_in_flight, max_keepalive_connections=max_in_flight)
        timeout = httpx.Timeout(timeout_s, connect=0.5)
        async with httpx.AsyncClient(base_url=upstream, limits=limits, timeout=timeout, trust_env=False) as client:
            app.state.client = client
            app.state.sem = asyncio.Semaphore(max_in_flight)
            app.state.background = BackgroundTasks()
            app.state.audit_log = []
            yield
            # Graceful shutdown: give background tasks 2 s, then cancel what is left.
            app.state.cancelled_on_shutdown = await app.state.background.drain(timeout=2.0)
            if app.state.background.errors:  # failures were logged one by one; summarise too
                log.error("%d background task(s) failed during this run", len(app.state.background.errors))

    app = FastAPI(title="dashboard (after)", lifespan=lifespan)

    async def write_audit(user: str) -> None:
        await asyncio.sleep(0.01)
        app.state.audit_log.append(user)

    async def fetch_section(section: str) -> object:
        async with app.state.sem:  # bound the fan-out, whatever the number of sections
            response = await asyncio.wait_for(app.state.client.get(f"/delay/{delay_ms}"), timeout_s)
            response.raise_for_status()
            return response.json()

    @app.get("/health")
    async def health() -> dict[str, object]:
        # Background failures are visible to monitoring, not only in the logs.
        return {"status": "ok", "background_errors": len(app.state.background.errors)}

    @app.get("/dashboard/{user}")
    async def dashboard(user: str) -> dict[str, object]:
        try:
            results = await asyncio.gather(*(fetch_section(s) for s in SECTIONS))
        except (asyncio.TimeoutError, httpx.HTTPError) as exc:
            raise HTTPException(status_code=504, detail=f"upstream: {type(exc).__name__}") from exc
        data = dict(zip(SECTIONS, results))
        charts = await asyncio.to_thread(render_chart, data)  # loop stays free meanwhile
        app.state.background.spawn(write_audit(user), name=f"audit:{user}")
        return {"user": user, "sections": data, "charts": charts}

    @app.get("/report")
    def report() -> dict[str, str]:
        # `def`, not `async def`: FastAPI calls it via the AnyIO worker-thread pool (40 tokens).
        time.sleep(0.05)
        return {"thread": threading.current_thread().name}

    @app.get("/legacy")
    async def legacy() -> dict[str, str]:
        # Inside `async def`, Starlette's helper offloads one blocking call explicitly.
        name = await run_in_threadpool(lambda: threading.current_thread().name)
        return {"thread": name}

    return app

The tracked-task helper used by after.py (strong references, error collection, drain with timeout) lives with the task examples:

py
"""Tasks vs coroutines, fire-and-forget done right, gather / as_completed / wait / TaskGroup."""
from __future__ import annotations

import asyncio
import logging
import sys
from typing import Any, Awaitable, Callable

log = logging.getLogger(__name__)


async def step(name: str, delay: float, fail: bool = False) -> str:
    await asyncio.sleep(delay)
    if fail:
        raise ValueError(f"{name} failed")
    return name


class BackgroundTasks:
    """Keeps a strong reference to every fire-and-forget task.

    The event loop holds only weak references to tasks, so a task nobody references can be
    garbage collected before it finishes. The set below is the pattern from the asyncio docs,
    plus logging of failures and a drain() for graceful shutdown.
    """

    def __init__(self) -> None:
        self._tasks: set[asyncio.Task[Any]] = set()
        self.errors: list[BaseException] = []

    def spawn(self, coro: Awaitable[Any], *, name: str | None = None) -> asyncio.Task[Any]:
        task = asyncio.ensure_future(coro)
        if name:
            task.set_name(name)
        self._tasks.add(task)
        task.add_done_callback(self._done)
        return task

    def _done(self, task: asyncio.Task[Any]) -> None:
        self._tasks.discard(task)
        if task.cancelled():
            return
        exc = task.exception()
        if exc is not None:
            # Retrieving the exception silences asyncio's "Task exception was never retrieved"
            # report, so the owner MUST report it itself: log it with the traceback and keep it.
            log.error("background task %s failed", task.get_name(), exc_info=exc)
            self.errors.append(exc)

    def __len__(self) -> int:
        return len(self._tasks)

    async def drain(self, timeout: float) -> int:
        """Graceful shutdown: wait up to `timeout`, then cancel the rest. Returns #cancelled."""
        if not self._tasks:
            return 0
        _, pending = await asyncio.wait(set(self._tasks), timeout=timeout)
        for task in pending:
            task.cancel()
        await asyncio.gather(*pending, return_exceptions=True)
        return len(pending)


async def create_task_starts_immediately() -> list[str]:
    """create_task() schedules the coroutine; it starts at the next await of the caller."""
    order: list[str] = []

    async def child() -> None:
        order.append("child runs")

    task = asyncio.create_task(child())
    order.append("after create_task")  # child has not run yet: we have not yielded
    await asyncio.sleep(0)
    order.append("after first await")
    await task
    return order


async def gather_fail_fast() -> tuple[str, list[str]]:
    """return_exceptions=False: first error propagates, the others keep running."""
    finished: list[str] = []

    async def tracked(name: str, delay: float, fail: bool = False) -> str:
        result = await step(name, delay, fail)
        finished.append(name)
        return result

    try:
        await asyncio.gather(tracked("a", 0.01, fail=True), tracked("b", 0.05))
        outcome = "no error"
    except ValueError as exc:
        outcome = str(exc)
    await asyncio.sleep(0.08)  # "b" was NOT cancelled by the failure of "a"
    return outcome, finished


async def gather_collect() -> list[Any]:
    """return_exceptions=True: exceptions come back as values in input order."""
    return await asyncio.gather(
        step("a", 0.02), step("b", 0.01, fail=True), step("c", 0.0), return_exceptions=True
    )


async def first_finished_order() -> list[str]:
    """as_completed() yields results in completion order, not input order."""
    order = []
    for next_done in asyncio.as_completed([step("slow", 0.05), step("fast", 0.01), step("mid", 0.03)]):
        order.append(await next_done)
    return order


async def race_first_completed() -> tuple[str, int]:
    """wait(FIRST_COMPLETED) returns (done, pending); cancelling the losers is YOUR job."""
    tasks = {asyncio.create_task(step(n, d)) for n, d in (("replica-a", 0.05), ("replica-b", 0.01))}
    done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    for task in pending:
        task.cancel()
    await asyncio.gather(*pending, return_exceptions=True)
    return done.pop().result(), sum(t.cancelled() for t in pending)


async def taskgroup_fail_fast() -> tuple[list[str], list[str]]:
    """Python 3.11+: one failure cancels the siblings and raises an ExceptionGroup."""
    if sys.version_info < (3, 11):  # pragma: no cover - documented, run on 3.11+ only
        raise RuntimeError("asyncio.TaskGroup needs Python 3.11+")
    cancelled: list[str] = []

    async def slow(name: str) -> str:
        try:
            await asyncio.sleep(1)
            return name
        except asyncio.CancelledError:
            cancelled.append(name)
            raise

    try:
        async with asyncio.TaskGroup() as tg:  # type: ignore[attr-defined]
            tg.create_task(slow("b"))
            tg.create_task(slow("c"))
            tg.create_task(step("a", 0.01, fail=True))
    except Exception as eg:  # an ExceptionGroup; `except* ValueError` needs 3.11 syntax
        messages = [str(e) for e in eg.exceptions]  # type: ignore[attr-defined]
        return messages, sorted(cancelled)
    return [], cancelled


async def bounded_gather(funcs: list[Callable[[], Awaitable[Any]]], limit: int) -> list[Any]:
    """gather() with at most `limit` in flight: the classic Semaphore fan-out."""
    sem = asyncio.Semaphore(limit)

    async def run(fn: Callable[[], Awaitable[Any]]) -> Any:
        async with sem:
            return await fn()

    return await asyncio.gather(*(run(f) for f in funcs))

The test drives both apps on the test's own event loop through httpx.ASGITransport, fires /dashboard and 20 ms later /health, and measures what the client sees. Real run: Before /dashboard 0.574s, /health during it 0.554s; After /dashboard 0.158s, /health during it 0.002s. The health check, which does nothing, waited half a second in the Before app because the loop was stuck inside the dashboard handler.

py
from __future__ import annotations

import asyncio
import time
from typing import Any

import httpx
import pytest
from fastapi.testclient import TestClient

from app import after, before


async def dashboard_and_health(app: Any) -> tuple[float, float]:
    """Fire /dashboard, then /health 20 ms later, on the same event loop as the app."""
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://app") as client:

        async def timed(path: str, wait: float) -> float:
            t0 = time.perf_counter()
            await asyncio.sleep(wait)  # a blocked loop also delays this wake-up
            assert (await client.get(path)).status_code == 200
            return time.perf_counter() - t0 - wait  # latency as the client sees it

        return tuple(await asyncio.gather(timed("/dashboard/ana", 0), timed("/health", 0.02)))  # type: ignore[return-value]


@pytest.mark.asyncio
async def test_before_blocks_every_request(upstream: str) -> None:
    app = before.create_app(upstream)
    dash, health = await dashboard_and_health(app)
    print(f"\nBEFORE: /dashboard {dash:.3f}s, /health during it {health:.3f}s")
    assert dash >= 0.5  # 5 x 100 ms one after another + 50 ms render
    assert health >= 0.3  # /health waited for the blocked loop


@pytest.mark.asyncio
async def test_after_keeps_the_loop_free(upstream: str) -> None:
    app = after.create_app(upstream)
    async with app.router.lifespan_context(app):  # ASGITransport does not run the lifespan
        dash, health = await dashboard_and_health(app)
        await asyncio.sleep(0.05)
        assert app.state.audit_log == ["ana"]
    print(f"\nAFTER: /dashboard {dash:.3f}s, /health during it {health:.3f}s")
    assert dash < 0.4  # 5 overlapped calls (~100 ms) + render in a thread (~50 ms)
    assert health < 0.05  # answered while the dashboard was waiting


def test_after_def_route_runs_in_worker_thread(upstream: str) -> None:
    with TestClient(after.create_app(upstream)) as client:
        assert client.get("/report").json()["thread"].startswith("AnyIO worker thread")
        assert client.get("/legacy").json()["thread"].startswith("AnyIO worker thread")


def test_after_upstream_timeout_is_a_504(upstream: str) -> None:
    app = after.create_app(upstream, delay_ms=500, timeout_s=0.1)
    with TestClient(app) as client:
        response = client.get("/dashboard/ana")
    assert response.status_code == 504
    assert response.json()["detail"].startswith("upstream: ")


def test_after_shutdown_drains_background_tasks(upstream: str) -> None:
    app = after.create_app(upstream)
    with TestClient(app) as client:
        assert client.get("/dashboard/bo").status_code == 200
    assert app.state.cancelled_on_shutdown == 0
    assert app.state.audit_log == ["bo"]

The upstream is a 60-line HTTP/1.1 server written with asyncio.start_server (keep-alive, ephemeral port, own loop in a background thread). The same module holds the five client strategies of the fan-out measurement:

py
"""Sync vs async fan-out against a local test server: the measurement used on the page.

The server is written with asyncio streams (asyncio.start_server), answers GET /delay/<ms>
after sleeping <ms> milliseconds, supports HTTP/1.1 keep-alive and runs on its own event loop
in a background thread, so both sync and async clients can call it.

Run:  python -m app.fanout        (prints the timing table)
"""
from __future__ import annotations

import asyncio
import concurrent.futures
import contextlib
import threading
import time
from typing import Callable, Iterator

import httpx


async def _handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    try:
        while True:
            request_line = await reader.readline()
            if not request_line:
                break  # client closed the keep-alive connection
            while (await reader.readline()) not in (b"\r\n", b"\n", b""):
                pass  # skip headers; GET has no body here
            path = request_line.split()[1].decode()
            ms = int(path.rsplit("/", 1)[-1]) if path.startswith("/delay/") else 0
            await asyncio.sleep(ms / 1000)  # the "slow upstream": waits without blocking
            body = f'{{"slept_ms": {ms}}}'.encode()
            writer.write(
                b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\n"
                + f"content-length: {len(body)}\r\n\r\n".encode()
                + body
            )
            await writer.drain()  # flow control: wait if the socket buffer is full
    except (ConnectionResetError, asyncio.IncompleteReadError):
        pass
    finally:
        writer.close()


@contextlib.contextmanager
def serve_in_thread() -> Iterator[str]:
    """Start the test server on an ephemeral port; yield its base URL."""
    loop = asyncio.new_event_loop()
    started = threading.Event()
    holder: dict[str, object] = {}

    async def start() -> None:
        server = await asyncio.start_server(_handle, "127.0.0.1", 0, backlog=512)
        holder["server"] = server
        holder["port"] = server.sockets[0].getsockname()[1]
        started.set()

    def run() -> None:
        asyncio.set_event_loop(loop)
        loop.run_until_complete(start())  # the 3.6-era API: drive one coroutine to completion
        loop.run_forever()

    thread = threading.Thread(target=run, name="test-upstream", daemon=True)
    thread.start()
    started.wait(5)
    try:
        yield f"http://127.0.0.1:{holder['port']}"
    finally:
        server = holder["server"]
        loop.call_soon_threadsafe(server.close)  # type: ignore[attr-defined]
        loop.call_soon_threadsafe(loop.stop)
        thread.join(5)
        loop.close()


def sync_sequential(urls: list[str]) -> float:
    start = time.perf_counter()
    with httpx.Client(trust_env=False) as client:
        for url in urls:
            client.get(url).raise_for_status()
    return time.perf_counter() - start


def sync_threads(urls: list[str], workers: int) -> float:
    start = time.perf_counter()
    limits = httpx.Limits(max_connections=workers, max_keepalive_connections=workers)
    with httpx.Client(trust_env=False, limits=limits) as client:  # httpx.Client is thread-safe
        with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
            for response in pool.map(client.get, urls):
                response.raise_for_status()
    return time.perf_counter() - start


async def async_gather(urls: list[str]) -> float:
    start = time.perf_counter()
    async with httpx.AsyncClient(trust_env=False) as client:  # default: 100 connections max
        responses = await asyncio.gather(*(client.get(u) for u in urls))
    for r in responses:
        r.raise_for_status()
    return time.perf_counter() - start


async def async_bounded(urls: list[str], limit: int) -> float:
    """At most `limit` requests in flight: protects the upstream and our own pool."""
    sem = asyncio.Semaphore(limit)
    start = time.perf_counter()
    async with httpx.AsyncClient(trust_env=False) as client:

        async def one(url: str) -> None:
            async with sem:
                (await client.get(url)).raise_for_status()

        await asyncio.gather(*(one(u) for u in urls))
    return time.perf_counter() - start


async def async_with_sync_client(urls: list[str]) -> float:
    """BAD: a sync client inside coroutines. gather() cannot overlap blocking calls."""
    start = time.perf_counter()
    with httpx.Client(trust_env=False) as client:

        async def one(url: str) -> None:
            client.get(url).raise_for_status()  # blocks the loop thread

        await asyncio.gather(*(one(u) for u in urls))
    return time.perf_counter() - start


def measure(n: int = 20, delay_ms: int = 100, limit: int = 5) -> dict[str, float]:
    with serve_in_thread() as base:
        urls = [f"{base}/delay/{delay_ms}" for _ in range(n)]
        runs: dict[str, Callable[[], float]] = {
            "sync sequential (httpx.Client)": lambda: sync_sequential(urls),
            f"sync + ThreadPoolExecutor({n})": lambda: sync_threads(urls, n),
            "async gather (httpx.AsyncClient)": lambda: asyncio.run(async_gather(urls)),
            f"async gather + Semaphore({limit})": lambda: asyncio.run(async_bounded(urls, limit)),
            "sync client inside async def": lambda: asyncio.run(async_with_sync_client(urls)),
        }
        return {name: round(fn(), 3) for name, fn in runs.items()}


if __name__ == "__main__":
    n, delay = 20, 100
    print(f"{n} GET requests, each answered after {delay} ms by a local asyncio server")
    for name, seconds in measure(n, delay).items():
        print(f"{name:<36} {seconds:6.3f} s")
py
from __future__ import annotations

import asyncio

import pytest

from app import fanout

N, DELAY = 20, 100


@pytest.fixture
def urls(upstream: str) -> list[str]:
    return [f"{upstream}/delay/{DELAY}" for _ in range(N)]


def test_sync_vs_async_fanout(urls: list[str]) -> None:
    seq = fanout.sync_sequential(urls)
    threads = fanout.sync_threads(urls, N)
    gathered = asyncio.run(fanout.async_gather(urls))
    bounded = asyncio.run(fanout.async_bounded(urls, 5))
    wrong = asyncio.run(fanout.async_with_sync_client(urls))
    print(
        f"\n{N} x {DELAY} ms: sequential {seq:.3f}s | threads {threads:.3f}s | gather {gathered:.3f}s"
        f" | Semaphore(5) {bounded:.3f}s | sync client in async def {wrong:.3f}s"
    )
    assert seq >= N * DELAY / 1000  # one after another
    assert gathered < seq / 5  # all 20 waits overlap
    assert threads < seq / 5
    assert bounded >= 4 * DELAY / 1000  # 20 / 5 = 4 waves
    assert wrong >= N * DELAY / 1000 * 0.9  # gather() cannot overlap blocking calls

The project file pins the stack; asyncio_mode = "strict" lets pytest-asyncio and the AnyIO plugin share the suite:

toml
[project]
name = "async-python-asyncio"
version = "0.1.0"
description = "Snippets for the Async Python chapter: event loop, coroutines, tasks, cancellation, timeouts, queues, thread pools, contextvars, a fan-out measurement"
# The page targets Python 3.12+; the pins below are the newest releases that still install on 3.9,
# the only interpreter on the build machine. TaskGroup and asyncio.timeout() (3.11+) are used only
# behind a version check, and their tests are skipped on 3.9.
requires-python = ">=3.9"
dependencies = [
    "fastapi==0.128.8",
    "starlette==0.49.3",
    "pydantic==2.13.5",
    "anyio==4.12.1",
    "httpx==0.28.1",
    # The standard extra pulls uvloop and httptools where wheels exist (not on Windows).
    "uvicorn[standard]==0.39.0",
    # Lets Pydantic evaluate `str | None` annotations on Python 3.9; not needed on 3.10+.
    "eval-type-backport==0.4.0; python_version < '3.10'",
]

[project.optional-dependencies]
test = [
    "pytest==8.4.2",
    # 1.2.0 is the last release that admits 3.9 (1.3.0 needs >=3.10).
    "pytest-asyncio==1.2.0",
]

[build-system]
requires = ["setuptools>=61"]
build-backend = "setuptools.build_meta"

[tool.setuptools]
packages = ["app"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q -p no:cacheprovider"
pythonpath = ["."]
# Strict mode: only tests marked @pytest.mark.asyncio run under pytest-asyncio, so the AnyIO
# plugin's @pytest.mark.anyio tests can live in the same suite (auto mode in both would conflict).
asyncio_mode = "strict"
asyncio_default_fixture_loop_scope = "function"
py
from __future__ import annotations

import sys
from typing import Iterator

import pytest

from app.fanout import serve_in_thread

needs_311 = pytest.mark.skipif(sys.version_info < (3, 11), reason="asyncio.TaskGroup / asyncio.timeout() are 3.11+")


@pytest.fixture(scope="session")
def upstream() -> Iterator[str]:
    """The local slow-upstream server (ephemeral port), shared by the whole session."""
    with serve_in_thread() as base:
        yield base

The Python angle ​

asyncio is a library, not a runtime feature: the interpreter only provides coroutine objects (async def, await, async for, async with, PEP 492/525/530), and everything else (the loop, Tasks, Futures, timers, transports, the thread-pool bridge) is Python code in Lib/asyncio/ with C accelerators for Task and Future. That is why alternatives can replace the loop (uvloop) or the whole framework (Trio), and why AnyIO can offer one API over both. Two other standard-library pieces matter as much as asyncio itself: concurrent.futures (the thread and process pools behind run_in_executor and to_thread) and contextvars (per-task state). The GIL is the third: it is what makes threads useless for pure-Python CPU work in the default build and what the free-threaded build (3.13 experimental, 3.14 supported) removes. Version facts that change code: 3.9 has to_thread but not TaskGroup, timeout(), except* or ExceptionGroup (AnyIO depends on the exceptiongroup backport there); 3.10 removed the loop= parameter from the high-level APIs; 3.11 made asyncio.TimeoutError an alias of the builtin TimeoutError (on 3.9 they are different classes, real: asyncio.TimeoutError is TimeoutError: False) and forbade passing bare coroutines to wait() (3.9 accepts them with DeprecationWarning: The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.).

The concept catalogue ​

One turn of the event loop (one thread, BaseEventLoop._run_once)1. Timers (heap)call_later / asyncio.sleeptimeout = nearest deadline(0 if callbacks are ready)2. wait for I/O (timeout)Selector loop: readiness,epoll / kqueue / selectProactor (Windows): IOCP completions3. Ready queueready / completed I/O callbacks+ expired timers+ call_soon callbacks4. Run every ready callback, one at a time, on the loop threadTask A resumesruns to next await~50 µsTask B resumesawaits a socket read~30 µsTask C: time.sleep(0.2)never yields: 200 msdebug: "took 0.213 seconds"Task D waitsbehind C evenif its data is readyAt an await that suspends, the task registers interest (socket, timer, Future)and gives the thread back; then the loop goes round to step 1 again

Concurrency vs parallelism Must-know ​

In plain words: Concurrency is dealing with many things at once: several jobs are in progress and their steps interleave. Parallelism is doing many things at once: several jobs execute at the same instant on different cores. A single waiter serving fifty tables is concurrent; ten waiters are parallel.

Common misunderstanding: "asyncio gives me parallelism." One event loop is one thread; at any instant exactly one coroutine is running. asyncio gives concurrency for waits. Parallel CPU work in CPython needs processes (or the free-threaded build, or C code that releases the GIL).

Definition: Concurrency: the program is structured so that several tasks can make progress in overlapping time periods. Parallelism: the hardware executes several of them simultaneously. In Python: asyncio = cooperative concurrency on one thread; threading = preemptive concurrency, parallel only where the GIL is released; multiprocessing / ProcessPoolExecutor = parallelism across processes.

     one event loop (concurrency)               4 processes (parallelism)
1    t=0     A: send request, await             core1: A computes ...
2    t=1us   B: send request, await             core2: B computes ...
3    t=2us   C: send request, await             core3: C computes ...
4    t=100ms A resumes: parse reply             core4: D computes ...
5    t=101ms B resumes: parse reply             all four finish at about the same time
6    -> 3 waits overlap; 1 core used            -> 4 computations overlap; 4 cores used

Real scenario: an API gateway that calls five services per request (concurrency: total latency = slowest call, not the sum); a nightly report that prices 2 million order lines (parallelism: processes); a crawler with 10,000 URLs (concurrency with a bound); a thumbnail service (parallel C code in threads, Pillow releases the GIL for much of its work, check per operation).

ModelPython APISwitches whenParallel CPU?Memory per jobTypical use
Cooperative tasksasyncio, AnyIO, Trioat awaitnoKBs (frame + Task)many network waits
Preemptive threadsthreading, ThreadPoolExecutorany bytecode boundary / I/Oonly where the GIL is released (or free-threaded build)a thread stackblocking libraries
Processesmultiprocessing, ProcessPoolExecutorOS scheduleryesa whole interpreterCPU-bound work
Free-threaded threadspython3.13t / 3.14tOS scheduleryesa thread stackCPU work in threads, if extensions support it
Go goroutinesruntimeblocking points, preemptionyes (GOMAXPROCS)~KBs, growableboth

Fix / how to use it: name the bottleneck first. Waiting on the network: asyncio. Waiting inside a sync library: threads. Computing: processes. Choosing turns that into a table.

The GIL and free-threaded Python Must-know ​

In plain words: In the default CPython build only one thread at a time executes Python bytecode. Threads still help when they wait (the lock is released during I/O), but two threads doing pure-Python arithmetic take turns instead of running side by side. Since 3.13 there is a separate build without that lock.

Common misunderstanding: "The GIL makes my code thread-safe." It makes individual bytecode operations atomic with respect to the interpreter's own data structures; a read-modify-write across several operations (x = x + 1, check-then-act on a dict) can still interleave between threads. And asyncio code does not need the GIL for safety at all: it is safe between two awaits because nothing else runs.

Definition: The glossary: "The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time … Locking the entire interpreter makes it easier for the interpreter to be multi-threaded, at the expense of much of the parallelism afforded by multi-processor machines. However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O." PEP 703: "CPython's global interpreter lock ("GIL") prevents multiple threads from executing Python code at the same time … This PEP proposes adding a build configuration (--disable-gil)". The free-threading HOWTO: "Starting with the 3.13 release, CPython has support for a build of Python called free threading where the global interpreter lock (GIL) is disabled."

     default build, 2 threads, pure-Python loop         free-threaded build (3.13t/3.14t)
1    T1 holds GIL: runs bytecode                        T1 runs on core 1
2    T2 waits for GIL                                   T2 runs on core 2 at the same time
3    switch interval (sys.getswitchinterval() = 0.005 s, real) -> T2 gets GIL      per-object locking inside the interpreter
4    T1 waits                                           ~1% (macOS aarch64) to 8% (x86-64 Linux) single-thread overhead
5    -> total time ~= sequential (measured: 0.37 s vs 0.42 s inline)

Real scenario: a team moves a CPU-heavy pricing loop into ThreadPoolExecutor and sees no speed-up (the measured 0.37 s vs 0.42 s); the same job in ProcessPoolExecutor takes 0.18 s for four jobs; a service that hashes uploads with hashlib does benefit from threads because the C code releases the lock; a data team evaluates python3.14t for a threaded pipeline and finds one C extension that re-enables the GIL on import.

Build / versionGILHow to checkStatus
CPython 3.12 and earlier (default)always onn/athe standard build
CPython 3.13 default buildonsys._is_gil_enabled() → Truestandard
CPython 3.13t (--disable-gil)off (can be re-enabled by PYTHON_GIL=1, -X gil=1, or a non-supporting C extension)python -VV contains "free-threading build"; sysconfig.get_config_var("Py_GIL_DISABLED")experimental (PEP 703)
CPython 3.14toffsame"officially supported but still optional" (PEP 779, phase II)
PyPyhas a GILn/aalternative implementation

Fix / how to use it: for CPU work in the default build, use processes; for I/O, the GIL is irrelevant (it is released while waiting); for asyncio, the GIL changes nothing because there is one thread. Treat the free-threaded build as an option to test, not a default: the HOWTO warns that "Some third-party packages, in particular ones with an extension module, may not be ready for use in a free-threaded build, and will re-enable the GIL", and in that build threads inherit the caller's context by default (thread_inherit_context is true), which changes contextvars behaviour.

I/O-bound, CPU-bound, blocking calls and non-blocking I/O Must-know ​

In plain words: I/O-bound work spends its time waiting for something outside the CPU (network, disk, database); CPU-bound work spends it computing. A blocking call keeps the thread until it returns; a non-blocking call starts the operation and lets the thread do other things until the OS says it is ready.

Common misunderstanding: "If a library is fast, it does not block." Blocking is about holding the thread, not about speed. sqlite3 returning in 2 ms blocks the loop for 2 ms; 500 such calls per second is a full second of loop time. And async def around a blocking call changes nothing: measured, the sync httpx.Client inside 20 coroutines under gather() took 2.07 s, the same as a plain loop.

Definition: A blocking call is any call that does not return control to the event loop until its work is complete: time.sleep, requests.*, httpx.Client.*, urllib, socket.recv on a blocking socket, psycopg2/pymysql/sqlite3, open().read() on slow storage, subprocess.run, a long CPU loop. Non-blocking I/O sets sockets to non-blocking mode and registers interest with a selector; asyncio's transports and streams, httpx.AsyncClient, asyncpg, redis.asyncio and asyncio.create_subprocess_exec are built that way. The docs: "Directly calling blocking_io() in any coroutine would block the event loop for its duration".

     heartbeat every 10 ms + one 200 ms job (real run, tests/test_offload.py)
1    job = time.sleep(0.2) inside async def      worst heartbeat gap 0.211 s  (loop frozen)
2    job = await asyncio.to_thread(time.sleep, 0.2)   worst gap 0.011 s  (loop free)
3    job = await asyncio.sleep(0.2)              worst gap 0.013 s  (loop free)

Real scenario: a FastAPI async def route calls requests.post to a payment provider and p99 latency of every route rises during an outage; a Celery-style worker uses time.sleep for retry backoff inside a coroutine; a Django developer moves to FastAPI and keeps psycopg2 in async def routes; a log shipper reads files with open() in a coroutine on a network file system.

CallBlocks the loop?Async alternativeOr offload with
time.sleep(s)yesawait asyncio.sleep(s)n/a
requests.get, httpx.Client.get, urllib.requestyesawait httpx.AsyncClient().get / aiohttpto_thread
psycopg2, pymysql, sqlite3yesasyncpg, psycopg 3 async, aiomysql, aiosqlite, SQLAlchemy AsyncSessionto_thread / def route
redis.Redisyesredis.asyncio.Redisto_thread
open().read(), pathlib.read_textyes (usually short)anyio.Path / anyio.open_file (AnyIO: "Operations that perform disk I/O (like read_bytes()) are run in a worker thread")to_thread
subprocess.runyesasyncio.create_subprocess_execto_thread
boto3yesaiobotocore (README: an async client for AWS services built on botocore and aiohttp/asyncio) / aioboto3to_thread
json.loads of 50 MB, Pydantic on huge payloadsyes (CPU)n/aProcessPoolExecutor if it matters

Fix / how to use it: in async def, every call either awaits an async library or is handed to a thread; the heartbeat test in Running blocking code is a cheap way to prove a code path does not block, and debug mode logs any callback above 100 ms.

The event loop: selectors, callbacks and uvloop Must-know ​

In plain words: The event loop is a while True that keeps three things: timers (who wants to wake at what time), ready callbacks (who can run now), and registered sockets. Each turn it asks the operating system "which of my sockets are ready?" (waiting at most until the next timer), queues the matching callbacks and runs them one by one.

Common misunderstanding: "The loop runs tasks in the background, in parallel." The loop is the thread that runs your tasks. While one callback runs, the loop is not looking at sockets or timers; that is the whole story of "blocking the loop".

Definition: The docs: "Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses." BaseEventLoop._run_once in CPython computes the select timeout from the nearest scheduled handle, calls self._selector.select(timeout) (on the proactor loop the same call waits on the IOCP completion port, which reports finished operations instead of ready sockets), adds the resulting I/O callbacks and expired timers to _ready, and runs every handle in _ready; in debug mode it logs 'Executing %s took %.3f seconds' when one took longer than slow_callback_duration (default 0.1 s). The selectors module picks the best OS mechanism (DefaultSelector: epoll on Linux, kqueue on macOS/BSD); on Windows the default since 3.8 is the ProactorEventLoop built on IOCP. uvloop replaces the whole loop with libuv (the event library of Node.js).

     one loop iteration (_run_once), simplified
1    timeout = 0 if ready callbacks exist else (nearest timer - now)
2    events = selector.select(timeout)             <- the only place the loop sleeps (epoll/kqueue; IOCP on Windows proactor)
3    for each ready socket: append its reader/writer callback to _ready
4    for each expired timer: append its callback to _ready
5    for each handle in _ready (FIFO): handle._run()   <- your coroutine resumes here
6         ... runs until its next await, which registers a socket/timer/Future and returns
7    go to 1

Real scenario: Uvicorn runs one loop per worker process and every request of that worker on it; a test server in this chapter's snippets runs its own loop in a background thread (loop.run_forever()); a GUI or Jupyter already has a running loop, which is why asyncio.run() fails there; Uvicorn picks uvloop automatically when installed (real: --loop auto: uvloop.Loop).

LoopPlatformBackendHow you get itNotes
SelectorEventLoopUnix default; Windows optionalselectors.DefaultSelector (epoll / kqueue / poll / select)asyncio.runreal on macOS: _UnixSelectorEventLoop
ProactorEventLoopWindows default since 3.8IOCPasyncio.run on Windowssubprocess and pipes supported
uvloop LoopLinux, macOS (no Windows)libuv, Cythonuvloop.run(main()); the README's alternative for 3.11 and earlier: asyncio.Runner(loop_factory=uvloop.new_event_loop) or uvloop.install()README: "uvloop makes asyncio 2-4x faster"
Uvicorn --loop autoanyuvloop if importable, else asynciouvicorn[standard] installs uvloopUvicorn docs: "not compatible with Windows or PyPy"
Trio / AnyIO trio backendanyTrio's own loopanyio.run(main, backend="trio")different cancellation model

Fix / how to use it: never call blocking code on the loop thread; get the loop with asyncio.get_running_loop() inside coroutines (the docs prefer it to get_event_loop(), whose behaviour changed across versions); install uvicorn[standard] to get uvloop on Linux and macOS; the snippet test tests/test_uvloop.py shows the same coroutines running unchanged on uvloop.

py
from __future__ import annotations

import asyncio
import sys

import pytest

from app import basics

uvloop = pytest.importorskip("uvloop")  # no wheels on Windows


def test_same_code_runs_on_uvloop() -> None:
    async def main() -> tuple[str, list[str]]:
        loop_type = type(asyncio.get_running_loop()).__module__
        results, _ = await basics.concurrent([0.01, 0.01])
        return loop_type, results

    if sys.version_info >= (3, 11):
        loop_type, results = uvloop.run(main())
    else:  # 3.9/3.10: the policy API (deprecated in 3.14 and scheduled for removal in 3.16)
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
        try:
            loop_type, results = asyncio.run(main())
        finally:
            asyncio.set_event_loop_policy(None)
    assert loop_type.startswith("uvloop")
    assert results == ["job0", "job1"]

Coroutines, async def, await, awaitables and Futures Must-know ​

In plain words: async def defines a function that can pause. Calling it gives you a paused object (a coroutine); await on it runs it until it either finishes or reaches an await of something not ready yet, at which point the whole chain of awaiting coroutines pauses and the loop runs something else.

Common misunderstanding: "await starts something in the background." await coro() runs coro now, inline, in the current task; the caller waits for it. Running two things at once needs two Tasks (create_task, gather, TaskGroup). Three awaits in a row take the sum of their times (real: sequential() 3 × 50 ms ≥ 0.15 s; concurrent() < 0.12 s).

Definition: PEP 492 made coroutines "a proper standalone concept in Python" with async def (a function containing await cannot be a plain def). An awaitable is a coroutine, a Future, a Task, or any object with __await__ returning an iterator. A Future (asyncio.Future) is a low-level object with result(), exception(), done(), cancelled(), add_done_callback(); awaiting it suspends until someone calls set_result/set_exception. A Task is a Future subclass that drives a coroutine. Await expressions are only valid inside async def (or at top level in python -m asyncio).

     await chain inside one Task
1    Task.__step: coro.send(None)        -> handler() runs
2    handler: await service()            -> service() runs inline (no new task)
3    service: await client.get(url)      -> ... down to a socket read
4    socket not ready: a Future is yielded up the chain to the Task
5    Task registers a wake-up callback on that Future, returns to the loop
6    loop runs other tasks; later the selector reports the socket ready
7    Future.set_result(data) -> callback schedules Task.__step again
8    Task: coro.send(None) resumes the innermost await; values flow back up

Real scenario: a service method that is async def only because it calls one async client (fine); a "helper" written async def that never awaits (it still costs a coroutine object and forces every caller to be async); a callback API (a message consumer) wrapped into an awaitable with loop.create_future(); a test that calls an async def function without await and passes because nothing ran.

KindCreated byRuns whenAwaitable twice?Cancel
Coroutinecalling an async defwhen awaited or wrapped in a Taskno (RuntimeError: cannot reuse already awaited coroutine)close()
Taskcreate_task, ensure_future, gather, TaskGroup.create_taskscheduled at once; starts at the creator's next awaityes (returns the same result)task.cancel()
Futureloop.create_future(), run_in_executorwhen someone sets its resultyesfut.cancel()
concurrent.futures.Futurethread/process poolsin a workerno (wrap: asyncio.wrap_future)cancel() before it starts
Async generatorasync def with yieldper async for stepn/aaclose()

Fix / how to use it:

py
"""Coroutines, awaitables and the event loop: what `async def` and `await` really do."""
from __future__ import annotations

import asyncio
import time


async def fetch(name: str, delay: float) -> str:
    # A coroutine function: calling it returns a coroutine object, nothing runs yet.
    await asyncio.sleep(delay)  # yields to the event loop until the timer fires
    return name


async def sequential(delays: list[float]) -> tuple[list[str], float]:
    """Awaiting one coroutine after another: total time is the SUM of the delays."""
    start = time.perf_counter()
    results = [await fetch(f"job{i}", d) for i, d in enumerate(delays)]
    return results, time.perf_counter() - start


async def concurrent(delays: list[float]) -> tuple[list[str], float]:
    """gather() wraps each coroutine in a Task: total time is the MAX of the delays."""
    start = time.perf_counter()
    results = await asyncio.gather(*(fetch(f"job{i}", d) for i, d in enumerate(delays)))
    return list(results), time.perf_counter() - start


def interleaving_trace() -> list[str]:
    """Shows the loop switching between two tasks only at `await` points."""
    trace: list[str] = []

    async def worker(name: str) -> None:
        for step in range(2):
            trace.append(f"{name} step {step}")
            await asyncio.sleep(0)  # a bare yield point: let other ready tasks run

    async def main() -> None:
        await asyncio.gather(worker("A"), worker("B"))

    asyncio.run(main())
    return trace


def await_without_suspension() -> list[str]:
    """`await` yields to the loop only if the awaitable actually suspends.

    Awaiting a coroutine that returns at once, or a Future that is already done, continues
    without a task switch; `await asyncio.sleep(0)` is the explicit "let others run" point.
    """
    order: list[str] = []

    async def instant() -> int:
        return 1

    async def main() -> None:
        async def child() -> None:
            order.append("child")

        task = asyncio.create_task(child())
        await instant()
        order.append("after await instant()")
        done = asyncio.get_running_loop().create_future()
        done.set_result(None)
        await done
        order.append("after await done Future")
        await asyncio.sleep(0)
        order.append("after await asyncio.sleep(0)")
        await task

    asyncio.run(main())
    return order


def awaitable_kinds() -> dict[str, bool]:
    """Coroutines, Tasks and Futures are all awaitables; a plain function result is not."""

    async def main() -> dict[str, bool]:
        coro = fetch("x", 0)
        task = asyncio.ensure_future(fetch("y", 0))  # same as create_task for a coroutine
        fut = asyncio.get_running_loop().create_future()
        fut.set_result("z")
        kinds = {
            "coroutine": asyncio.iscoroutine(coro),
            "task_is_future": isinstance(task, asyncio.Future),
            "future_awaitable": hasattr(fut, "__await__"),
        }
        await asyncio.gather(coro, task, fut)
        return kinds

    return asyncio.run(main())
py
from __future__ import annotations

import asyncio

import pytest

from app import basics


@pytest.mark.asyncio
async def test_sequential_awaits_add_up() -> None:
    results, elapsed = await basics.sequential([0.05, 0.05, 0.05])
    assert results == ["job0", "job1", "job2"]
    assert elapsed >= 0.15


@pytest.mark.asyncio
async def test_gather_overlaps_the_waits() -> None:
    results, elapsed = await basics.concurrent([0.05, 0.05, 0.05])
    assert results == ["job0", "job1", "job2"]  # input order, not completion order
    assert elapsed < 0.12


def test_tasks_switch_only_at_await_points() -> None:
    assert basics.interleaving_trace() == ["A step 0", "B step 0", "A step 1", "B step 1"]


def test_await_does_not_yield_unless_it_suspends() -> None:
    assert basics.await_without_suspension() == [
        "after await instant()",
        "after await done Future",
        "child",
        "after await asyncio.sleep(0)",
    ]


def test_awaitable_kinds() -> None:
    assert basics.awaitable_kinds() == {"coroutine": True, "task_is_future": True, "future_awaitable": True}


def test_calling_a_coroutine_function_runs_nothing() -> None:
    coro = basics.fetch("x", 0)
    assert asyncio.iscoroutine(coro)
    assert asyncio.run(coro) == "x"  # only the event loop runs it


@pytest.mark.asyncio
async def test_asyncio_run_inside_a_running_loop_fails() -> None:
    coro = basics.fetch("x", 0)
    with pytest.raises(RuntimeError, match="cannot be called from a running event loop"):
        asyncio.run(coro)
    coro.close()  # avoid "coroutine was never awaited"

Tasks: create_task, scheduling, fire and forget, task references Must-know ​

In plain words: A Task is the unit of concurrency in asyncio: "please run this coroutine alongside me". asyncio.create_task(coro) schedules it and returns at once; the new task starts the next time the current one awaits.

Common misunderstanding: "If I don't need the result, I can drop the task." The docs say: "Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn't referenced elsewhere may get garbage collected at any time, even before it's done. For reliable "fire-and-forget" background tasks, gather them in a collection". A dropped task's exception is also lost (you get Task exception was never retrieved at garbage collection at best), and nothing cancels it on shutdown (Task was destroyed but it is pending!).

Definition: asyncio.create_task(coro, *, name=None, context=None) wraps the coroutine in a Task, schedules its first step with loop.call_soon and returns the Task (context added in 3.11; current versions also accept eager_start). The task runs in a copy of the current contextvars context. Since 3.12 a loop can use asyncio.eager_task_factory, which runs the coroutine synchronously during create_task until its first real suspension ("Tasks are only scheduled on the event loop if they block").

     caller task                                   new task (real order, test_tasks.py)
1    t = create_task(child())                       scheduled, not started
2    order.append("after create_task")
3    await asyncio.sleep(0)   -- yields --------->  child runs: order.append("child runs")
4    order.append("after first await")   <-------  child done
5    await t                                        result (or exception) delivered here
     -> ["after create_task", "child runs", "after first await"]

Real scenario: an endpoint that sends a webhook "in the background" and returns 202; a WebSocket handler that starts a reader task and a writer task; a lifespan that starts a periodic cache-refresh task; an audit-log write that must not delay the response. Each needs an owner that keeps the reference, logs failures and cancels at shutdown.

PatternKeeps referenceSees errorsCancelled on shutdownVerdict
asyncio.create_task(x()) and drop itnononobug
tasks.add(t); t.add_done_callback(tasks.discard) (docs pattern)yesonly if you read themif you cancel the setminimal
BackgroundTasks class in the snippet (set + done-callback that logs each failure with its traceback + drain(timeout))yesyes, logged by the owner and counted in /healthyes, after a grace periodgood default; retrieving the exception silences asyncio's own report, so the owner must log it
async with TaskGroup() / AnyIO task groupyesyes (ExceptionGroup)normal exit WAITS for every child; children are cancelled only if one fails or the body raises (or on tg.cancel() 3.15+ / tg.cancel_scope.cancel())best when the lifetime is a block; a never-ending worker must be cancelled explicitly
FastAPI BackgroundTasksyes (runs after the response, same request)loggedruns to completionsmall post-response work (chapter)
A job queue (Celery, arq, RQ, Dramatiq)durableyes, with retriessurvives restartsanything that must not be lost

Fix / how to use it: never call create_task without storing the result. If the owner reads task.exception() in a done-callback, asyncio no longer prints Task exception was never retrieved, so the callback must log the failure itself (the snippet uses log.error(..., exc_info=exc)) and expose it (the After app's /health returns background_errors). In a service, own background tasks in one object created in the lifespan (the snippet's BackgroundTasks, used by app/after.py), drain it on shutdown, and move anything that must survive a crash to a real queue.

gather and return_exceptions Must-know ​

In plain words: await asyncio.gather(a(), b(), c()) runs the three concurrently and gives you their results as a list in the order you passed them.

Common misunderstanding: "If one fails, gather cancels the others." It does not. The docs: "If return_exceptions is False (default), the first raised exception is immediately propagated to the task that awaits on gather(). Other awaitables in the aws sequence won't be cancelled and will continue to run." The snippet proves it: after a failed, b still finished (finished == ["b"]). With return_exceptions=True, "exceptions are treated the same as successful results, and aggregated in the result list".

Definition: asyncio.gather(*aws, return_exceptions=False): coroutines are wrapped in Tasks; the result list follows input order; "If gather() is cancelled, all submitted awaitables (that have not completed yet) are also cancelled"; after gather has propagated an exception, calling gather.cancel() "won't cancel any other awaitables". It is unbounded: gather(*(fetch(u) for u in urls)) with 10,000 URLs starts 10,000 tasks at once.

     gather(a: fails at 10 ms, b: 50 ms), return_exceptions=False (real, test_tasks.py)
1    t=0     both tasks start
2    t=10ms  a raises ValueError -> gather raises it in the caller
3    t=10ms  caller handles the error and moves on ...
4    t=50ms  b still completes; its result is discarded unless someone awaits it
     same with return_exceptions=True -> ["a", ValueError("b failed"), "c"] in input order

Real scenario: a product page that loads price, stock and reviews; a health check that pings three dependencies and reports each (return_exceptions=True); a batch import that sends 50 rows at a time (gather inside a loop over chunks, or a Semaphore); an aggregation where one failed source must not fail the page.

NeedUseWhy
All results, fail fast, siblings may keep runninggather()simple; know that siblings are not cancelled
All results, partial failure allowedgather(..., return_exceptions=True)inspect each item with isinstance(r, Exception)
Fail fast AND cancel siblingsTaskGroup (3.11+) or AnyIO task groupstructured concurrency
Results as they arriveas_completedstream partial results
A bound on concurrencySemaphore around each call, or a worker Queueprotects the upstream and your pool
Very large fan-outworker pool over a Queueconstant number of tasks

Fix / how to use it: tasks.gather_fail_fast, gather_collect and bounded_gather in app/tasks.py (imported in After above, tested in tests/test_tasks.py below); bounded_gather is the Semaphore fan-out that the measurement uses.

py
from __future__ import annotations

import asyncio

import pytest

from app import tasks
from tests.conftest import needs_311


@pytest.mark.asyncio
async def test_create_task_runs_at_next_await() -> None:
    assert await tasks.create_task_starts_immediately() == ["after create_task", "child runs", "after first await"]


@pytest.mark.asyncio
async def test_gather_propagates_first_error_and_does_not_cancel_others() -> None:
    outcome, finished = await tasks.gather_fail_fast()
    assert outcome == "a failed"
    assert finished == ["b"]  # b kept running after a failed


@pytest.mark.asyncio
async def test_gather_return_exceptions_keeps_order() -> None:
    results = await tasks.gather_collect()
    assert results[0] == "a" and results[2] == "c"
    assert isinstance(results[1], ValueError)


@pytest.mark.asyncio
async def test_as_completed_yields_in_completion_order() -> None:
    assert await tasks.first_finished_order() == ["fast", "mid", "slow"]


@pytest.mark.asyncio
async def test_wait_first_completed_then_cancel_losers() -> None:
    winner, cancelled = await tasks.race_first_completed()
    assert winner == "replica-b"
    assert cancelled == 1


@pytest.mark.asyncio
async def test_background_tasks_keeps_references_and_collects_errors(caplog: pytest.LogCaptureFixture) -> None:
    bg = tasks.BackgroundTasks()
    bg.spawn(tasks.step("ok", 0.01))
    bg.spawn(tasks.step("bad", 0.01, fail=True))
    assert len(bg) == 2  # strongly referenced until done
    await asyncio.sleep(0.05)
    assert len(bg) == 0
    assert [str(e) for e in bg.errors] == ["bad failed"]
    assert any("background task" in r.message and "failed" in r.message for r in caplog.records)


@pytest.mark.asyncio
async def test_drain_cancels_what_does_not_finish_in_time() -> None:
    bg = tasks.BackgroundTasks()
    bg.spawn(tasks.step("quick", 0.01))
    slow = bg.spawn(asyncio.sleep(5))
    assert await bg.drain(timeout=0.1) == 1
    assert slow.cancelled()


@pytest.mark.asyncio
async def test_bounded_gather_preserves_order() -> None:
    funcs = [lambda i=i: tasks.step(str(i), 0.01) for i in range(10)]
    assert await tasks.bounded_gather(funcs, limit=3) == [str(i) for i in range(10)]


@needs_311
@pytest.mark.asyncio
async def test_taskgroup_cancels_siblings_and_groups_errors() -> None:  # expected on 3.11+
    messages, cancelled = await tasks.taskgroup_fail_fast()
    assert messages == ["a failed"]
    assert cancelled == ["b", "c"]

TaskGroup and structured concurrency Important ​

In plain words: A task group is a block that owns the tasks started inside it: on a normal exit the block waits until all of them have ended; only if one fails (or the body raises) are the others cancelled, and the errors come out together. No task outlives the code that started it, which also means a child that never ends (a while True consumer) keeps the block open forever until something cancels it. AnyIO says the same: "If a child task, or the code in the enclosed context block raises an exception, all child tasks are cancelled. Otherwise the context manager just waits until all child tasks have exited before proceeding." To stop perpetual children: tg.cancel() (3.15+), cancel their tasks yourself (keep the Task from tg.create_task and call .cancel(), or set an Event they watch), an enclosing asyncio.timeout(), or in AnyIO tg.cancel_scope.cancel().

Common misunderstanding: "TaskGroup is gather with nicer syntax." The difference is cancellation and lifetime: gather leaves the siblings running after the first error; a TaskGroup cancels them, waits for them to finish their cleanup and raises an ExceptionGroup with every non-cancellation error. It also cannot lose a task: there is no way to leave the async with while a child still runs.

Definition (3.11+, expected, not run on 3.9): "The async with statement will wait for all tasks in the group to finish … The first time any of the tasks belonging to the group fails with an exception other than asyncio.CancelledError, the remaining tasks in the group are cancelled. No further tasks can then be added to the group … Once all tasks have finished, if any tasks have failed with an exception other than asyncio.CancelledError, those exceptions are combined in an ExceptionGroup or BaseExceptionGroup … which is then raised." KeyboardInterrupt and SystemExit are re-raised as themselves. 3.13 improved "handling of simultaneous internal and external cancellations"; 3.15 (released 2026-10-09) added tg.cancel(), "a non-exceptional, early exit of the task group's lifetime" (What's New 3.15: "Previously this would involve unintuitive boilerplate such as an extra task raising a custom exception which is then suppressed as it exits the task group"). Errors are handled with except* (PEP 654), which is a syntax error before 3.11. "Structured concurrency" is the name for this rule (every task has a parent scope that waits for it); it comes from Trio, and AnyIO brings the same model to asyncio on older versions.

     async with asyncio.TaskGroup() as tg:  (expected on 3.11+; same shape ran for real with AnyIO)
1    tg.create_task(slow("b"))       tg.create_task(slow("c"))       tg.create_task(fail("a"))
2    t=10ms  a raises ValueError("a failed")
3            group cancels b and c -> CancelledError inside each; their finally/except blocks run
4            the body of `async with` is cancelled too if it is still awaiting
5            __aexit__ waits until b and c have finished cancelling
6            raise ExceptionGroup(..., [ValueError("a failed")])   # every non-cancellation error
7    except* ValueError as eg: ...   # handle; other exception types keep propagating

Real scenario: a checkout that must reserve stock, authorise payment and compute shipping, and must stop all three if one fails; a WebSocket session with a reader and a writer task that should both stop when either does; a scatter-gather search where a broken shard should fail the query fast; a lifespan that runs several background loops under one group.

gather()gather(return_exceptions=True)TaskGroup (3.11+)AnyIO create_task_group()
Siblings on first errorkeep runningkeep runningcancelledcancelled
What you getfirst exceptionlist with exceptionsExceptionGroupExceptionGroup (backport on ≤ 3.10)
Can a child outlive the block?yes (if not awaited)yesnono
Add tasks laternonoyes (tg.create_task while open)yes (tg.start_soon)
Python versionsallall3.11+3.9+ (AnyIO 4.12.1 on 3.9)
Resultsreturn valuereturn valuetask.result() after the blockvia shared state or start()

Fix / how to use it: on 3.11+, prefer TaskGroup for any fan-out whose results you need together, wrap the whole group in asyncio.timeout(), and catch with except*. The snippet tasks.taskgroup_fail_fast() is written for 3.11 (it catches the group with plain except Exception so the file stays valid 3.9 syntax) and its test is skipped on 3.9; the AnyIO version below ran for real.

python
# Python 3.11+ (expected, not run here): fail fast, cancel siblings, handle by type
async def checkout(order_id: int) -> Receipt:
    async with asyncio.timeout(2.0):
        async with asyncio.TaskGroup() as tg:
            stock = tg.create_task(reserve_stock(order_id))
            payment = tg.create_task(authorise_payment(order_id))
            shipping = tg.create_task(quote_shipping(order_id))
    return Receipt(stock.result(), payment.result(), shipping.result())

try:
    receipt = await checkout(42)
except* PaymentDeclined as eg:      # one or more PaymentDeclined in the group
    log.warning("declined: %s", eg.exceptions)
except* TimeoutError:
    log.error("checkout budget exceeded")

as_completed and wait (FIRST_COMPLETED) Important ​

In plain words: as_completed hands you results in the order they finish, so you can act on the fastest first. wait returns two sets, finished and still running, when a condition is met: the first one finished, the first error, or all done.

Common misunderstanding: "wait(timeout=...) cancels what did not finish." It does not: "Futures or Tasks that aren't done when the timeout occurs are simply returned in the second set", and "Unlike wait_for(), wait() does not cancel the futures when a timeout occurs." The same is true for as_completed ("does not cancel the tasks running the supplied awaitables"). Cancelling the losers is your job; forgetting it leaks tasks and connections.

Definition: asyncio.as_completed(aws, *, timeout=None) returns an iterator (since 3.13 also an asynchronous iterator) of awaitables; each yields the next result to finish; TimeoutError if the timeout passes first. asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED) returns (done, pending); return_when is FIRST_COMPLETED ("when any future finishes or is cancelled"), FIRST_EXCEPTION or ALL_COMPLETED; it does not raise on timeout. Since 3.11 wait() accepts only Tasks/Futures; on 3.9 bare coroutines produce a DeprecationWarning (real).

     race two replicas (real, tasks.race_first_completed)
1    tasks = {create_task(step("replica-a", 0.05)), create_task(step("replica-b", 0.01))}
2    done, pending = await asyncio.wait(tasks, return_when=FIRST_COMPLETED)   # at ~10 ms
3    done = {replica-b}; pending = {replica-a}
4    for t in pending: t.cancel(); await gather(*pending, return_exceptions=True)
5    -> winner "replica-b", 1 task cancelled
     as_completed([slow 50 ms, fast 10 ms, mid 30 ms]) -> "fast", "mid", "slow" (real)

Real scenario: hedged requests (send to two replicas, take the first answer, cancel the other); a search page that renders each provider's results as they arrive; a supervisor that waits for the first of several worker tasks to crash (FIRST_EXCEPTION) and restarts it; a deploy script that waits up to 30 s for all health checks and reports the pending ones.

WantCallThen
Fastest of N, cancel the restwait(..., return_when=FIRST_COMPLETED)cancel pending, await them
Each result as it arrivesfor aw in as_completed(aws): r = await aw (3.13+: async for)cancel the rest on early exit
Stop on first error, inspect the restwait(..., return_when=FIRST_EXCEPTION)done has the failed task
Deadline without cancellingwait(..., timeout=t)decide what to do with pending
Deadline with cancellingwait_for / timeout()n/a

Fix / how to use it: first_finished_order() and race_first_completed() in app/tasks.py; always pair wait/as_completed with an explicit cancel of what you no longer need.

From coroutine object to finished Task, and what cancel() really doescoroutine objectfetch() called,nothing runs yetcreate_taskpendingin the ready queueweak ref from looprunninguntil the next awaitthen suspended on aFuture / socket / timerawait / resumedone: result()done: exception()cancelled()task.cancel() is a request1. cancel() returns at once; nothing stops yet2. CancelledError raised at the task's next await3. finally / async with exits run (cleanup)4. error propagates: state becomes cancelled()a CPU loop without await is never interruptedexcept CancelledError: return ...swallowed: task ends "done" with a result,TaskGroup / timeout() can misbehaveawait asyncio.shield(inner)the awaiting task gets CancelledError,the inner task keeps running (keep a reference)

Cancellation: CancelledError and shield Must-know ​

In plain words: task.cancel() asks a task to stop. Python delivers the request as a CancelledError exception raised at the task's next await, so the task unwinds like any exception: finally blocks and async with exits run, and then the task is marked cancelled.

Common misunderstanding: "Catching CancelledError is good error handling." Catching it to clean up is fine; not re-raising it breaks cancellation. The docs: "In case asyncio.CancelledError is explicitly caught, it should generally be propagated when clean-up is complete … The asyncio components that enable structured concurrency, like asyncio.TaskGroup and asyncio.timeout(), are implemented using cancellation internally and might misbehave if a coroutine swallows asyncio.CancelledError." The snippet's stubborn() returns a value from except CancelledError and the task ends as "done, not cancelled" (real: swallowed_cancel() is True). The Before app's audit task does exactly this. Also: except Exception does not catch it, because since 3.8 CancelledError is a BaseException (real: base class BaseException on 3.9).

Definition: "Tasks can easily and safely be cancelled. When a task is cancelled, asyncio.CancelledError will be raised in the task at the next opportunity. It is recommended that coroutines use try/finally blocks to robustly perform clean-up logic." task.cancel(msg=None) returns immediately; task.cancelled() is true only if the error propagated out. A task that never awaits (a CPU loop) cannot be cancelled until it does. 3.11 added Task.cancelling() and Task.uncancel() for libraries that need to count requests. asyncio.shield(aw): "if the coroutine containing it is cancelled, the Task running in something() is not cancelled. From the point of view of something(), the cancellation did not happen. Although its caller is still cancelled, so the "await" expression still raises a CancelledError." Shield needs its own reference to the inner task ("Save a reference to tasks passed to this function").

     cancel_with_cleanup (real, test_cancellation.py)
1    worker: log "started"; await asyncio.sleep(10)
2    caller: await asyncio.sleep(0.01); task.cancel()      # a request, returns at once
3    worker: CancelledError raised at the sleep -> finally: log "cleanup ran"
4    caller: await task -> raises CancelledError -> log "caller saw CancelledError"
5    task.cancelled() == True
     shield: outer cancelled -> outer.cancelled() True; inner still returns "payment committed"

Real scenario: a client disconnects and Uvicorn/Starlette cancel the request's work (for streaming responses and in ASGI disconnect handling); a timeout cancels a slow upstream call; shutdown cancels background loops; a payment capture that must not be abandoned halfway is shielded and allowed to finish, with its result recorded by someone who holds the inner task.

SituationWhat happensRight code
Need cleanup on cancelCancelledError unwinds the stacktry/finally or async with
Need to log the cancelcatch, log, re-raiseexcept CancelledError: log(); raise
Want the task to "survive" a cancelswallowing breaks TaskGroup/timeoutdo not; use shield for an inner operation
Critical inner operationcaller cancelled, inner continuesawait asyncio.shield(task) + keep task
CPU loop with no awaitcancel cannot interruptawait asyncio.sleep(0) every N iterations, or move to a process
except Exception: around an awaitdoes not catch CancelledError (3.8+)correct as is
except BaseException: / bare except:catches itre-raise

Fix / how to use it:

py
"""Cancellation, shielding and timeouts in asyncio and in AnyIO (the layer under Starlette)."""
from __future__ import annotations

import asyncio
import sys

import anyio


async def cancel_with_cleanup() -> list[str]:
    """task.cancel() raises CancelledError at the task's next await; finally still runs."""
    log: list[str] = []

    async def worker() -> None:
        try:
            log.append("started")
            await asyncio.sleep(10)
        finally:
            log.append("cleanup ran")  # release locks, close connections, roll back

    task = asyncio.create_task(worker())
    await asyncio.sleep(0.01)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        log.append("caller saw CancelledError")
    log.append(f"task.cancelled()={task.cancelled()}")
    return log


async def swallowed_cancel() -> bool:
    """BAD: catching CancelledError and not re-raising makes the task look successful."""

    async def stubborn() -> str:
        try:
            await asyncio.sleep(10)
        except asyncio.CancelledError:
            return "ignored the cancel"  # the bug: no `raise`
        return "finished"

    task = asyncio.create_task(stubborn())
    await asyncio.sleep(0.01)
    task.cancel()
    result = await task
    return task.cancelled() is False and result == "ignored the cancel"


async def shield_keeps_inner_running() -> tuple[bool, str]:
    """shield(): the outer await is cancelled, the inner task keeps going."""
    inner = asyncio.create_task(asyncio.sleep(0.05, result="payment committed"))

    async def caller() -> str:
        return await asyncio.shield(inner)  # e.g. a request handler awaiting a commit

    outer = asyncio.create_task(caller())
    await asyncio.sleep(0.01)
    outer.cancel()
    try:
        await outer
    except asyncio.CancelledError:
        pass
    return outer.cancelled(), await inner


async def wait_for_timeout(delay: float, timeout: float) -> str:
    """wait_for() cancels the awaitable on timeout and raises TimeoutError.

    On 3.9-3.10 the exception is asyncio.TimeoutError (a different class); since 3.11 it is an
    alias of the builtin TimeoutError. Catching asyncio.TimeoutError works on every version.
    """
    try:
        return await asyncio.wait_for(asyncio.sleep(delay, result="done"), timeout)
    except asyncio.TimeoutError:
        return "timed out"


async def timeout_block(delay: float, budget: float) -> str:
    """Python 3.11+: asyncio.timeout() bounds a whole block, not one awaitable."""
    if sys.version_info < (3, 11):  # pragma: no cover
        raise RuntimeError("asyncio.timeout() needs Python 3.11+")
    try:
        async with asyncio.timeout(budget):  # type: ignore[attr-defined]
            await asyncio.sleep(delay / 2)
            await asyncio.sleep(delay / 2)
            return "done"
    except TimeoutError:
        return "timed out"


async def anyio_move_on_after(delay: float, budget: float) -> tuple[str, bool]:
    """AnyIO cancel scope: leave the block quietly when the deadline passes (runs on 3.9)."""
    result = "timed out"
    with anyio.move_on_after(budget) as scope:
        await anyio.sleep(delay)
        result = "done"
    return result, scope.cancelled_caught


async def anyio_fail_after(delay: float, budget: float) -> str:
    """fail_after(): same scope, but raises TimeoutError at the deadline."""
    try:
        with anyio.fail_after(budget):
            await anyio.sleep(delay)
        return "done"
    except TimeoutError:
        return "timed out"


async def anyio_group_cancels_siblings() -> list[str]:
    """Structured concurrency on 3.9: an AnyIO task group cancels siblings on failure."""
    cancelled: list[str] = []

    async def slow(name: str) -> None:
        try:
            await anyio.sleep(1)
        except anyio.get_cancelled_exc_class():
            cancelled.append(name)
            raise

    async def broken() -> None:
        await anyio.sleep(0.01)
        raise ValueError("upstream 500")

    try:
        async with anyio.create_task_group() as tg:
            tg.start_soon(slow, "b")
            tg.start_soon(slow, "c")
            tg.start_soon(broken)
    except Exception as eg:  # ExceptionGroup (backport package on 3.9/3.10)
        cancelled.append(type(eg).__name__ + ": " + str(eg.exceptions[0]))  # type: ignore[attr-defined]
    return sorted(cancelled)
py
from __future__ import annotations

import asyncio

import pytest

from app import cancellation as c
from tests.conftest import needs_311


@pytest.mark.asyncio
async def test_cancel_runs_finally_and_propagates() -> None:
    assert await c.cancel_with_cleanup() == [
        "started",
        "cleanup ran",
        "caller saw CancelledError",
        "task.cancelled()=True",
    ]


@pytest.mark.asyncio
async def test_swallowing_cancelled_error_hides_the_cancel() -> None:
    assert await c.swallowed_cancel() is True


@pytest.mark.asyncio
async def test_shield_protects_inner_task() -> None:
    outer_cancelled, inner_result = await c.shield_keeps_inner_running()
    assert outer_cancelled is True
    assert inner_result == "payment committed"


@pytest.mark.asyncio
async def test_wait_for() -> None:
    assert await c.wait_for_timeout(0.01, 0.5) == "done"
    assert await c.wait_for_timeout(0.5, 0.02) == "timed out"


def test_timeout_error_class_on_this_python() -> None:
    import sys

    # 3.11+: asyncio.TimeoutError is TimeoutError. 3.9/3.10: two different classes.
    assert (asyncio.TimeoutError is TimeoutError) == (sys.version_info >= (3, 11))


@needs_311
@pytest.mark.asyncio
async def test_asyncio_timeout_block() -> None:  # expected on 3.11+
    assert await c.timeout_block(0.01, 0.5) == "done"
    assert await c.timeout_block(0.5, 0.05) == "timed out"


@pytest.mark.anyio
async def test_anyio_move_on_after() -> None:
    assert await c.anyio_move_on_after(0.01, 0.5) == ("done", False)
    assert await c.anyio_move_on_after(0.5, 0.02) == ("timed out", True)


@pytest.mark.anyio
async def test_anyio_fail_after() -> None:
    assert await c.anyio_fail_after(0.5, 0.02) == "timed out"


@pytest.mark.anyio
async def test_anyio_task_group_cancels_siblings() -> None:
    assert await c.anyio_group_cancels_siblings() == ["ExceptionGroup: upstream 500", "b", "c"]


@pytest.fixture
def anyio_backend() -> str:
    return "asyncio"  # run the AnyIO-marked tests on asyncio only (trio is not installed)

Timeouts: wait_for and asyncio.timeout Must-know ​

In plain words: A timeout is "cancel this if it takes longer than N seconds, and tell me". wait_for puts the limit on one awaitable; asyncio.timeout() (3.11+) puts it on a whole block of code.

Common misunderstanding: "except TimeoutError catches asyncio timeouts on every version." On 3.9 and 3.10, asyncio.wait_for raises asyncio.TimeoutError, a different class from the builtin (real on 3.9: asyncio.TimeoutError is TimeoutError: False). Since 3.11 the two are the same ("This class was made an alias of TimeoutError"). Code that must run on both catches asyncio.TimeoutError. A second one: a timeout on the HTTP client (httpx.Timeout) and an asyncio timeout are different layers; you usually want both.

Definition: asyncio.wait_for(aw, timeout): "If a timeout occurs, it cancels aw and raises TimeoutError", and "The function will wait until the future is actually cancelled, so the total wait time may exceed the timeout"; since 3.7 it waits for the cancellation to finish before raising; since 3.12 it is "Implemented using asyncio.timeout()". async with asyncio.timeout(delay) (3.11+): cancels the current task's work inside the block when the deadline passes and converts the resulting CancelledError into TimeoutError at the block exit; Timeout.reschedule() moves the deadline; asyncio.timeout_at(when) takes an absolute loop time. AnyIO's equivalents run on every version: fail_after(seconds) raises TimeoutError, move_on_after(seconds) exits silently and sets scope.cancelled_caught.

     wait_for(asyncio.sleep(0.5), 0.02)  (real)            asyncio.timeout(0.05) around 2 x sleep(0.25)  (expected, 3.11+)
1    t=0     inner awaitable wrapped and started            t=0     block starts, deadline = now + 50 ms
2    t=20ms  deadline: inner cancelled                      t=50ms  deadline: current task cancelled at its await
3            wait_for waits for the cancel to complete              CancelledError unwinds the block
4            raises asyncio.TimeoutError -> "timed out"             __aexit__ turns it into TimeoutError -> "timed out"
     anyio.move_on_after(0.02) around sleep(0.5) -> ("timed out", cancelled_caught=True)  (real)

Real scenario: an upstream budget of 300 ms per call inside a 1 s request budget; a database query that must not hold a pooled connection forever; a health check that reports "degraded" instead of hanging; the After app maps asyncio.TimeoutError from wait_for to a 504 (real test: delay_ms=500, timeout_s=0.1 → 504 upstream: ...).

APIScopeOn timeoutVersionNote
asyncio.wait_for(aw, t)one awaitablecancels it, TimeoutErrorall (alias of builtin since 3.11)wraps a coroutine in a Task before 3.12
async with asyncio.timeout(t)a blockcancels the block, TimeoutError3.11+reschedule(), timeout_at()
asyncio.wait(aws, timeout=t)a setreturns (done, pending), nothing cancelledallno exception
anyio.fail_after(t)a block (cancel scope)TimeoutErrorAnyIO 3+works on 3.9
anyio.move_on_after(t)a blockexits quietly, scope.cancelled_caughtAnyIO 3+"best effort" fallbacks
httpx.Timeout(t, connect=...)one HTTP request phasehttpx.TimeoutException subclasseshttpxdefault "5 seconds of network inactivity"
Uvicorn --timeout-graceful-shutdownserver shutdownforces exitUvicornsee shutdown

Fix / how to use it: give every outbound call a client timeout and every request an overall budget (asyncio.timeout on 3.11+, wait_for or AnyIO fail_after before); catch asyncio.TimeoutError if you support 3.10 or older; never catch the CancelledError that the timeout uses internally.

Structured concurrency with AnyIO: task groups and cancel scopes Important ​

In plain words: AnyIO is a library that gives asyncio (and Trio) the structured-concurrency tools that asyncio only got in 3.11, plus a few it still does not have: cancel scopes you can nest, cancel and shield, and timeouts as blocks. Starlette and FastAPI use it internally, so it is already installed in every FastAPI project.

Common misunderstanding: "AnyIO cancellation behaves exactly like asyncio cancellation." AnyIO uses level cancellation inside its scopes: "as long as a task remains within an effectively cancelled cancel scope, it will get hit with a cancellation exception any time it hits a yield point", while asyncio uses edge cancellation ("a CancelledError is raised in the task and the task then gets to handle it however it likes, even opting to ignore it entirely"). Code written for asyncio that swallows one cancellation will be cancelled again at its next await under AnyIO.

Definition: The AnyIO docs: "Cancellation in AnyIO follows the model established by the Trio framework. This means that cancellation of tasks is done via so called cancel scopes. Cancel scopes are used as context managers and can be nested. Cancelling a cancel scope cancels all cancel scopes nested within it." "A task group contains its own cancel scope." APIs: anyio.create_task_group() with tg.start_soon(fn, *args) and await tg.start(fn) (wait until the child signals it is ready), tg.cancel_scope.cancel(), anyio.CancelScope(shield=True), fail_after, move_on_after, anyio.get_cancelled_exc_class(), anyio.to_thread.run_sync, anyio.from_thread.run. FastAPI: "Starlette (and FastAPI) are based on AnyIO, which makes it compatible with both Python's standard library asyncio and Trio."

     anyio task group, one child fails (real on 3.9, cancellation.anyio_group_cancels_siblings)
1    tg.start_soon(slow, "b"); tg.start_soon(slow, "c"); tg.start_soon(broken)
2    t=10ms  broken raises ValueError("upstream 500")
3            the group's cancel scope is cancelled -> b and c get the cancel exception at their sleep
4            b and c log "cancelled" and re-raise
5            group exits: ExceptionGroup("...", [ValueError("upstream 500")])
     -> ["ExceptionGroup: upstream 500", "b", "c"]

Real scenario: a library that must run on asyncio and Trio; a FastAPI dependency that starts a helper task for the duration of a request; a streaming endpoint that reads from an upstream and from the client disconnect signal and stops both together; a worker that must finish a database commit even when the service is shutting down (CancelScope(shield=True) around the commit).

Conceptasyncio (3.11+)AnyIO 4 (3.9+)
Task groupasyncio.TaskGroup, tg.create_task(coro)anyio.create_task_group(), tg.start_soon(fn, *args)
Wait for a child to be readymanual Eventawait tg.start(fn) + task_status.started()
Timeout blockasyncio.timeout(t)fail_after(t) / move_on_after(t)
Shieldasyncio.shield(aw) (protects one awaitable)CancelScope(shield=True) (protects a block)
Cancellation semanticsedgelevel, inside scopes
Cancel exceptionasyncio.CancelledErroranyio.get_cancelled_exc_class() (backend's own)
Threadsasyncio.to_thread (default executor)anyio.to_thread.run_sync (CapacityLimiter, 40 tokens)
Testingpytest-asynciobuilt-in pytest plugin, @pytest.mark.anyio

Fix / how to use it: anyio_move_on_after, anyio_fail_after and anyio_group_cancels_siblings in app/cancellation.py (above) all ran on 3.9 under @pytest.mark.anyio; use AnyIO in libraries and in code that must support Python before 3.11, and keep plain asyncio in application code on 3.11+ if you prefer the standard library.

Synchronisation primitives: Lock, Semaphore, Event, Condition Important ​

In plain words: Even on one thread, tasks interleave wherever an await actually suspends (I/O, a timer, asyncio.sleep(0), a lock that is held). If a task reads shared state, awaits, then writes, another task may have changed the state in between. asyncio has the same tools as threading for that, but they work only between tasks of one loop.

Common misunderstanding: "One thread means no race conditions." The snippet's lost_update(use_lock=False) runs 50 deposits of +1 with an await between read and write and ends with a balance of 1 (real: 49 updates lost). With an asyncio.Lock around the read-await-write, the result is 50. A second misunderstanding: asyncio primitives are not thread locks: "asyncio primitives are not thread-safe, therefore they should not be used for OS thread synchronization (use threading for that)".

Definition: asyncio.Lock ("Implements a mutex lock for asyncio tasks. Not thread-safe."), asyncio.Semaphore(value) / BoundedSemaphore (at most value holders), asyncio.Event (set(), clear(), await wait(); "An event object. Not thread-safe."), asyncio.Condition (await wait(), await wait_for(predicate), notify(n), notify_all() under its lock), asyncio.Barrier(parties) (3.11+). Lock, Semaphore and Condition are used with async with; Barrier too (async with barrier as position:); Event is not a context manager. On 3.9 a primitive binds to the event loop current when it is created (self._loop = events.get_event_loop() in locks.py); 3.10 removed the loop parameter, so create primitives inside coroutines (or in the lifespan), never at import time of a module that several loops import (tests).

     lost update on ONE thread (real, coordination.lost_update)
1    task 1: current = balance (0)      ; await asyncio.sleep(0)  -- yields
2    task 2: current = balance (0)      ; await ...               -- yields
3    ...  all 50 tasks read 0 before anyone writes
4    task 1: balance = 0 + 1
5    task 2: balance = 0 + 1   ... -> final balance 1, expected 50
     with `async with lock:` around read-await-write -> 50

Real scenario: refreshing an OAuth token once when 30 concurrent requests find it expired (a Lock plus a re-check: "single flight"); limiting calls to a partner API to 5 at a time (Semaphore); holding all workers until the configuration is loaded (Event); a cache that waits for "at least N items" (Condition); a rate-limited scraper.

PrimitiveHoldsTypical useThread-safe?Since
asyncio.Lock1 taskcritical section that awaits insideno3.4
asyncio.Semaphore(n)n tasksconcurrency limit, connection budgetno3.4
asyncio.BoundedSemaphore(n)n, error on extra releasesame, catches bugsno3.4
asyncio.Eventflagone-to-many signalno3.4
asyncio.Conditionlock + wait queuewait for a predicate over shared stateno3.4
asyncio.Barrier(n)n arrivalsphase synchronisationno3.11
threading.Lock1 threadstate shared with worker threadsyesn/a
anyio.Lock, anyio.Semaphore, CapacityLimiteras abovebackend-neutral codenoAnyIO

Fix / how to use it: keep shared mutable state small; prefer atomic operations without an await between read and write; when an await is unavoidable, hold an asyncio.Lock; state shared with threads needs threading.Lock (or loop.call_soon_threadsafe to hand values to the loop). The database version of this bug is a lost update and is fixed in SQL, not with an in-process lock.

Queues, producer/consumer and back-pressure Important ​

In plain words: An asyncio.Queue is a buffer between tasks that produce work and tasks that consume it. If you give it a maximum size, a fast producer has to wait when the buffer is full, so it slows down to the consumers' pace instead of piling up work in memory. That waiting is back-pressure.

Common misunderstanding: "An unbounded queue is safer, nothing gets rejected." An unbounded queue turns a slow consumer into unbounded memory growth and unbounded latency for every queued item. A bound plus a policy (wait, drop, or reject with 503/429) is what keeps a service alive under load.

Definition: asyncio.Queue(maxsize=0) (0 = unbounded); await put(item) waits while full, put_nowait raises QueueFull (real); await get() waits while empty; task_done() marks one item processed and await join() waits until every item put has been marked; qsize(), full(), empty(). Also PriorityQueue and LifoQueue. 3.13 added Queue.shutdown(immediate=False) and QueueShutDown ("Raises QueueShutDown if the queue has been shut down"), which replaces the sentinel trick; on 3.9 (real: hasattr Queue.shutdown: False) you put one sentinel per consumer, as the snippet does. Like the other primitives, it is not thread-safe; from a thread use loop.call_soon_threadsafe(q.put_nowait, x).

     maxsize=5, 40 items, 4 consumers x 10 ms each (real, coordination.producer_consumer)
1    producer: put 0..4   -> queue full
2    producer: put(5) waits ...                    consumers: get 0,1,2,3 ; sleep 10 ms
3    consumers task_done -> space -> producer resumes, refills
4    ... producer total waiting time 0.088 s; qsize never above 5
5    producer: put(None) x 4  (one sentinel per consumer)
6    consumers exit; await queue.join() returns
     -> {'processed': 40, 'max_qsize': 5, 'producer_wait_s': 0.088, 'elapsed_s': 0.11}

Real scenario: a webhook receiver that accepts events fast and writes them to the database at the database's pace; a crawler with a URL frontier and N fetchers; a log shipper batching lines to a remote API; a WebSocket broadcaster with one bounded queue per client, dropping or disconnecting slow clients.

Policy when fullHowUse when
Producer waits (back-pressure)await q.put(x)producer can slow down (internal pipeline)
Reject the requestq.put_nowait(x) → QueueFull → 503 / 429producer is a client that can retry
Drop newest / oldestput_nowait in try, or get_nowait() then putmetrics, telemetry, live prices
Disconnect the slow consumerper-client queue full → closeWebSockets, SSE fan-out
Persist insteadRedis Streams, RabbitMQ, Kafka, SQSmust survive restarts (messaging)

Fix / how to use it:

py
"""Lock, Semaphore, Event, Condition and Queue: coordination between tasks on ONE loop."""
from __future__ import annotations

import asyncio
import time


async def lost_update(use_lock: bool, workers: int = 50) -> int:
    """A read-await-write sequence loses updates without a Lock, even on one thread."""
    balance = {"value": 0}
    lock = asyncio.Lock()  # create primitives inside a coroutine (3.9 binds them to a loop)

    async def deposit() -> None:
        if use_lock:
            async with lock:
                current = balance["value"]
                await asyncio.sleep(0)  # e.g. a DB round trip between read and write
                balance["value"] = current + 1
        else:
            current = balance["value"]
            await asyncio.sleep(0)
            balance["value"] = current + 1

    await asyncio.gather(*(deposit() for _ in range(workers)))
    return balance["value"]


async def semaphore_peak(limit: int, jobs: int) -> int:
    """At most `limit` coroutines inside the `async with sem` block at any moment."""
    sem = asyncio.Semaphore(limit)
    inside = peak = 0

    async def job() -> None:
        nonlocal inside, peak
        async with sem:
            inside += 1
            peak = max(peak, inside)
            await asyncio.sleep(0.01)
            inside -= 1

    await asyncio.gather(*(job() for _ in range(jobs)))
    return peak


async def event_gate() -> list[str]:
    """Event: many waiters released by one set() (e.g. 'config loaded', 'shutdown started')."""
    ready = asyncio.Event()
    log: list[str] = []

    async def waiter(name: str) -> None:
        await ready.wait()
        log.append(f"{name} released")

    tasks = [asyncio.create_task(waiter(n)) for n in ("w1", "w2")]
    await asyncio.sleep(0.01)
    log.append("set()")
    ready.set()
    await asyncio.gather(*tasks)
    return log


async def condition_handoff() -> list[int]:
    """Condition: wait until a predicate over shared state is true, under a lock."""
    cond = asyncio.Condition()
    items: list[int] = []
    got: list[int] = []

    async def consumer() -> None:
        async with cond:
            await cond.wait_for(lambda: len(items) >= 3)
            got.extend(items)

    task = asyncio.create_task(consumer())
    for i in range(3):
        async with cond:
            items.append(i)
            cond.notify_all()
        await asyncio.sleep(0)
    await task
    return got


async def producer_consumer(maxsize: int, items: int, consumers: int, work: float) -> dict[str, float]:
    """Bounded Queue = back-pressure: put() waits while the queue is full."""
    queue: asyncio.Queue[int | None] = asyncio.Queue(maxsize=maxsize)
    processed: list[int] = []
    max_seen = 0
    producer_wait = 0.0

    async def producer() -> None:
        nonlocal max_seen, producer_wait
        for i in range(items):
            t0 = time.perf_counter()
            await queue.put(i)  # blocks when consumers are behind
            producer_wait += time.perf_counter() - t0
            max_seen = max(max_seen, queue.qsize())
        for _ in range(consumers):
            await queue.put(None)  # one sentinel per consumer: "no more work"

    async def consumer() -> None:
        while True:
            item = await queue.get()
            try:
                if item is None:
                    return
                await asyncio.sleep(work)
                processed.append(item)
            finally:
                queue.task_done()

    start = time.perf_counter()
    await asyncio.gather(producer(), *(consumer() for _ in range(consumers)))
    await queue.join()  # every put() has a matching task_done()
    return {
        "processed": len(processed),
        "max_qsize": max_seen,
        "producer_wait_s": round(producer_wait, 3),
        "elapsed_s": round(time.perf_counter() - start, 3),
    }
py
from __future__ import annotations

import pytest

from app import coordination as co


@pytest.mark.asyncio
async def test_lost_update_without_lock() -> None:
    assert await co.lost_update(use_lock=False, workers=50) == 1  # 49 updates lost
    assert await co.lost_update(use_lock=True, workers=50) == 50


@pytest.mark.asyncio
async def test_semaphore_caps_concurrency() -> None:
    assert await co.semaphore_peak(limit=3, jobs=12) == 3


@pytest.mark.asyncio
async def test_event_releases_all_waiters() -> None:
    assert await co.event_gate() == ["set()", "w1 released", "w2 released"]


@pytest.mark.asyncio
async def test_condition_wait_for_predicate() -> None:
    assert await co.condition_handoff() == [0, 1, 2]


@pytest.mark.asyncio
async def test_bounded_queue_applies_back_pressure(capsys: pytest.CaptureFixture[str]) -> None:
    stats = await co.producer_consumer(maxsize=5, items=40, consumers=4, work=0.01)
    print(f"\nqueue maxsize=5, 40 items, 4 consumers x 10 ms: {stats}")
    assert stats["processed"] == 40
    assert stats["max_qsize"] <= 5  # never more than maxsize buffered
    assert stats["producer_wait_s"] > 0.05  # the producer was slowed to the consumers' pace
Getting blocking work off the event loop threadEvent loop threadasync def routes, taskshttpx.AsyncClient, asyncpgawait asyncio.to_thread(f)loop.run_in_executor(None, f)def route (FastAPI)await run_in_threadpool(f)loop.run_in_executor(process_pool, cpu_job)awaits a Future meanwhileDefault ThreadPoolExecutormax_workers = min(32, cpu_count + 4)16 on a 12-core Mac (measured)contextvars copied by to_threadAnyIO worker threadsCapacityLimiter: 40 tokensshared by def routes, sync deps,FileResponse, run_in_threadpoolProcessPoolExecutorone interpreter + GIL per workerargs/results pickled; spawn costGood for threadssync DB driversrequests, boto3file I/O, sqlite3C code that releasesthe GIL (hashlib, zlib)the GIL is releasedwhile a thread waitson I/OPure-Python CPUthreads: 0.37 s vs 0.42 s inlineprocesses: 0.18 s (4 jobs)

Running blocking code: to_thread, run_in_executor and the default executor size Must-know ​

In plain words: When you must call something blocking from async code, hand it to a worker thread and await the result. The loop thread stays free; the worker thread waits; when it is done, the loop resumes your coroutine with the return value.

Common misunderstanding: "The thread pool is unlimited, so offload everything." The default executor has a fixed size, measured here at 16 workers on a 12-core machine, and every to_thread call shares it. If 16 calls are stuck on a slow server, call 17 waits in the executor's queue while the loop looks perfectly healthy. FastAPI's def routes do not use this executor at all; they use AnyIO's limiter (40 tokens, real). Size pools for the blocking work you actually have, and give slow dependencies their own executor.

Definition: asyncio.to_thread(func, /, *args, **kwargs) (3.9+): "Asynchronously run function func in a separate thread … the current contextvars.Context is propagated, allowing context variables from the event loop thread to be accessed in the separate thread." In CPython 3.9 it is three lines: copy the context, functools.partial(ctx.run, func, ...), await loop.run_in_executor(None, func_call). loop.run_in_executor(executor, func, *args) returns an asyncio Future; executor=None means the loop's default ThreadPoolExecutor, created on first use. Its size: "Changed in version 3.8: Default value of max_workers is changed to min(32, os.cpu_count() + 4)", and in current versions min(32, (os.process_cpu_count() or 1) + 4) ("Changed in version 3.13"; process_cpu_count counts only the CPUs the process may use). loop.set_default_executor(ThreadPoolExecutor(max_workers=n)) replaces it; loop.shutdown_default_executor() (called by asyncio.run at exit) joins its threads. The docs' note: "Due to the GIL, asyncio.to_thread() can typically only be used to make IO-bound functions non-blocking."

     await asyncio.to_thread(query_orders, db, 1)    (CPython 3.9 threads.py)
1    loop thread: ctx = contextvars.copy_context()
2    loop thread: fut = loop.run_in_executor(None, partial(ctx.run, query_orders, db, 1))
3    loop thread: await fut  -> task suspended, loop serves other tasks
4    worker thread "asyncio_0": runs sqlite3 query (GIL released while waiting on I/O)
5    worker thread: result ready -> loop.call_soon_threadsafe(set result on fut)
6    loop thread: task resumes with the rows
     default executor: min(32, cpu_count + 4) = min(32, 12 + 4) = 16 (real)

Real scenario: a sync SDK (boto3, a payment provider's client) inside an async service; sqlite3 or psycopg2 in a small app that is otherwise async; reading a large file or computing a checksum with hashlib (which releases the GIL); a legacy module that cannot be rewritten this quarter. In FastAPI the simplest offload is to write the route as def (link: async def vs def).

CallPoolSize by defaultContext copied?Use for
await asyncio.to_thread(f, *a)loop's default ThreadPoolExecutormin(32, cpu + 4)yesblocking I/O in asyncio code
await loop.run_in_executor(None, f, *a)samesameno (wrap with ctx.run yourself)pre-3.9 code, keyword args via partial
await loop.run_in_executor(my_pool, f)your executoryour choicenoisolate a slow dependency
await anyio.to_thread.run_sync(f)AnyIO worker threads40 tokens (CapacityLimiter)yesAnyIO / Starlette code
await starlette.concurrency.run_in_threadpool(f, *a)AnyIO worker threads40 tokensyesinside async def routes (real: thread AnyIO worker thread)
FastAPI def route / sync dependencyAnyIO worker threads40 tokensyeswhole route is sync
loop.run_in_executor(ProcessPoolExecutor(), f)processesos.process_cpu_count() (3.13+)no (pickled)CPU-bound work

Fix / how to use it:

py
"""Blocking calls, the default executor, to_thread, run_in_executor, thread vs process pools."""
from __future__ import annotations

import asyncio
import concurrent.futures
import functools
import os
import sqlite3
import sys
import time


async def heartbeat_lag(blocker: str, seconds: float = 0.2) -> float:
    """Run a 10 ms heartbeat next to a 'blocking' job; return the worst gap between beats.

    blocker="time.sleep" blocks the loop thread, so the heartbeat stalls for the whole job.
    blocker="to_thread" runs the same time.sleep in the default executor: the loop stays free.
    blocker="asyncio.sleep" never blocks at all.
    """
    gaps: list[float] = []
    stop = asyncio.Event()

    async def heartbeat() -> None:
        last = time.perf_counter()
        while not stop.is_set():
            await asyncio.sleep(0.01)
            now = time.perf_counter()
            gaps.append(now - last)
            last = now

    async def job() -> None:
        await asyncio.sleep(0.02)  # let the heartbeat start
        if blocker == "time.sleep":
            time.sleep(seconds)  # BAD inside a coroutine: freezes every task on this loop
        elif blocker == "to_thread":
            await asyncio.to_thread(time.sleep, seconds)
        else:
            await asyncio.sleep(seconds)
        stop.set()

    await asyncio.gather(heartbeat(), job())
    return max(gaps)


def default_executor_workers() -> int:
    """The formula ThreadPoolExecutor uses when max_workers is None.

    3.8-3.12: min(32, os.cpu_count() + 4). 3.13+: os.process_cpu_count(), which counts only
    the CPUs this process may use (affinity, -X cpu_count, PYTHON_CPU_COUNT).
    """
    if sys.version_info >= (3, 13):
        cpus = os.process_cpu_count()  # type: ignore[attr-defined]
    else:
        cpus = os.cpu_count()
    return min(32, (cpus or 1) + 4)


async def default_executor_size() -> int:
    """Read the real size of the loop's default executor after the first to_thread call."""
    await asyncio.to_thread(lambda: None)
    executor = asyncio.get_running_loop()._default_executor  # private: for the demo only
    return executor._max_workers  # type: ignore[union-attr]


def query_orders(db_path: str, customer_id: int) -> list[tuple[int, int]]:
    """A blocking DB driver call (sqlite3). Never call this directly in `async def`."""
    with sqlite3.connect(db_path) as conn:
        return conn.execute(
            "SELECT id, total_cents FROM orders WHERE customer_id = ? ORDER BY id",
            (customer_id,),
        ).fetchall()


async def orders_for(db_path: str, customer_ids: list[int]) -> dict[int, list[tuple[int, int]]]:
    """Several blocking queries at once, each in a worker thread, the loop stays free."""
    rows = await asyncio.gather(*(asyncio.to_thread(query_orders, db_path, c) for c in customer_ids))
    return dict(zip(customer_ids, rows))


def cpu_burn(n: int) -> int:
    """Pure-Python CPU work: holds the GIL the whole time (module level so processes can import it)."""
    total = 0
    for i in range(n):
        total += i * i % 7
    return total


async def cpu_fanout(kind: str, jobs: int, n: int) -> float:
    """Same CPU job x `jobs`: sequential on the loop, in a thread pool, or in a process pool."""
    loop = asyncio.get_running_loop()
    start = time.perf_counter()
    if kind == "inline":
        for _ in range(jobs):
            cpu_burn(n)  # blocks the loop, shown only for the baseline
    else:
        pool_cls = (
            concurrent.futures.ThreadPoolExecutor
            if kind == "threads"
            else concurrent.futures.ProcessPoolExecutor
        )
        with pool_cls(max_workers=jobs) as pool:
            await asyncio.gather(*(loop.run_in_executor(pool, functools.partial(cpu_burn, n)) for _ in range(jobs)))
    return time.perf_counter() - start
py
from __future__ import annotations

import os
import sqlite3
import sys
from pathlib import Path

import pytest

from app import offload


@pytest.mark.asyncio
async def test_heartbeat_time_sleep_blocks_the_loop_to_thread_does_not() -> None:
    blocked = await offload.heartbeat_lag("time.sleep", 0.2)
    offloaded = await offload.heartbeat_lag("to_thread", 0.2)
    free = await offload.heartbeat_lag("asyncio.sleep", 0.2)
    print(f"\nworst heartbeat gap: time.sleep {blocked:.3f}s, to_thread {offloaded:.3f}s, asyncio.sleep {free:.3f}s")
    assert blocked >= 0.18  # the 10 ms heartbeat could not run for ~200 ms
    assert offloaded < 0.1
    assert free < 0.1


@pytest.mark.asyncio
async def test_default_executor_size_formula() -> None:
    size = await offload.default_executor_size()
    print(f"\nos.cpu_count()={os.cpu_count()} default executor max_workers={size}")
    assert size == offload.default_executor_workers()


@pytest.mark.asyncio
async def test_blocking_driver_in_threads(tmp_path: Path) -> None:
    db = tmp_path / "shop.db"
    with sqlite3.connect(db) as conn:
        conn.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER, total_cents INTEGER)")
        conn.executemany(
            "INSERT INTO orders (customer_id, total_cents) VALUES (?, ?)", [(1, 1200), (2, 500), (1, 300)]
        )
    result = await offload.orders_for(str(db), [1, 2])
    assert result == {1: [(1, 1200), (3, 300)], 2: [(2, 500)]}


@pytest.mark.asyncio
async def test_cpu_bound_threads_vs_processes() -> None:
    n = 2_000_000
    inline = await offload.cpu_fanout("inline", 4, n)
    threads = await offload.cpu_fanout("threads", 4, n)
    processes = await offload.cpu_fanout("processes", 4, n)
    print(f"\n4 x cpu_burn({n}): inline {inline:.2f}s, threads {threads:.2f}s, processes {processes:.2f}s")
    assert threads > inline * 0.5  # the GIL: no 4x speed-up from 4 threads (wide margin: shared CI machines)
    if (os.cpu_count() or 1) >= 4:
        assert processes < threads  # separate interpreters, separate GILs

The SELECT that query_orders runs through the blocking driver; with an async driver (asyncpg, aiosqlite, SQLAlchemy AsyncSession) the same statement is awaited directly and the loop multiplexes the connections instead of a thread per query:

sql
-- app/offload.py query_orders(): parameterised, one round trip per customer
SELECT id, total_cents
FROM orders
WHERE customer_id = ?          -- $1 in asyncpg / PostgreSQL
ORDER BY id;

-- What "concurrent" means on the server side: three sessions from three tasks
-- (PostgreSQL; pg_sleep stands in for a slow query)
SELECT pid, state, wait_event_type, now() - query_start AS running_for, left(query, 40)
FROM pg_stat_activity
WHERE application_name = 'dashboard' AND state = 'active';

CPU-bound work: ProcessPoolExecutor and multiprocessing Important ​

In plain words: Pure-Python computation holds the GIL, so threads take turns and an event loop simply stops while it runs. To use several cores you need several processes, each with its own interpreter.

Common misunderstanding: "to_thread fixes CPU-heavy code in async routes." It keeps the loop responsive only partly (the worker thread and the loop thread compete for the GIL) and gives no speed-up. Measured, four cpu_burn(2_000_000) jobs: inline on the loop 0.42 s, four threads 0.37 s, four processes 0.18 s (including process start-up with the macOS spawn method).

Definition: concurrent.futures.ProcessPoolExecutor(max_workers=None) ("If max_workers is None or not given, it will default to os.process_cpu_count()" in current docs; os.cpu_count() on older versions) runs callables in worker processes; functions and arguments must be picklable and importable by the child (module-level functions, not lambdas or closures). multiprocessing is the lower-level module (Process, Pool, Queue, start methods fork, spawn, forkserver). From asyncio: await loop.run_in_executor(process_pool, func, arg). Create the pool once (lifespan), not per request: starting processes costs tens to hundreds of milliseconds.

     4 x cpu_burn(2_000_000) on a 12-core Mac (real, tests/test_offload.py)
1    inline (on the loop)          0.42 s   loop blocked the whole time
2    ThreadPoolExecutor(4)         0.37 s   GIL: one thread runs bytecode at a time
3    ProcessPoolExecutor(4)        0.18 s   4 interpreters, 4 GILs, 4 cores (+ spawn cost)

Real scenario: generating PDF invoices in pure Python; resizing images when the library holds the GIL; computing recommendations for a batch of users; parsing a 200 MB CSV upload. For anything that takes seconds, a job queue (Celery, arq, RQ, Dramatiq) with separate worker processes is usually better than a pool inside the web process: it survives restarts and does not compete with request handling for CPU.

OptionParallel CPUStart costData passingGood for
Inline in async defno, and blocks the loopnonenonemicroseconds of work only
to_thread / thread poolno (GIL), unless C code releases itlowshared memoryC extensions that release the GIL
ProcessPoolExecutor via run_in_executoryeshigh (once per worker)picklingCPU jobs of 10 ms to seconds
multiprocessing.Pool / Processyeshighpickling, shared memory, pipesscripts and batch jobs
Job queue workersyesn/a (long-lived)broker messagesanything slow, retried or scheduled
Free-threaded 3.14t + threadsyeslowshared memoryif every extension supports it

Fix / how to use it: offload.cpu_fanout("processes", ...) above; in a service, create one ProcessPoolExecutor in the lifespan, pass it to run_in_executor, and bound the number of in-flight CPU jobs with a Semaphore so a burst of requests cannot queue unbounded work.

Async generators, async for, async with and async context managers Important ​

In plain words: async for is a loop whose "get next item" step can await (a database cursor, a stream of messages, pages of an API). async with is a with whose enter and exit can await (open a connection, begin and commit a transaction).

Common misunderstanding: "An async generator is cleaned up when the loop ends." If you break out of async for, the generator is left suspended; its finally runs only when it is closed (aclose()), which happens at garbage collection or loop shutdown and can then run on the wrong task or not at all. Use contextlib.aclosing() (3.10+) or an explicit await agen.aclose() for generators that hold resources.

Definition: PEP 525 (3.6) introduced asynchronous generators: an async def with yield; iterate with async for; methods asend, athrow, aclose. PEP 530 (3.6) added asynchronous comprehensions ([x async for x in agen()]) and await inside comprehensions. An asynchronous context manager defines __aenter__/__aexit__; contextlib.asynccontextmanager builds one from an async generator with a single yield (code before = enter, after = exit). asyncio.run and shutdown_asyncgens() finalise leftover generators at loop close.

     async with transaction(pool): raise ValueError  (real, streams.demo)
1    async with Pool() as pool        -> __aenter__: "open"
2      async with transaction(pool)   -> before yield: "BEGIN"
3        body ok                      -> after yield: "COMMIT"
4      async with transaction(pool)   -> "BEGIN"
5        body raises ValueError       -> except branch: "ROLLBACK", re-raise
6    pool __aexit__                   -> "close"
     -> ["open", "BEGIN", "COMMIT", "BEGIN", "ROLLBACK", "close"]; [i*i async for i in ticks(4) if i % 2 == 0] -> [0, 4]

Real scenario: streaming rows from asyncpg with a server-side cursor; consuming a Kafka or Redis Stream topic with async for msg in consumer; FastAPI dependencies with yield (an async generator: session before, commit/close after, see Dependency Injection); async with httpx.AsyncClient(); async with engine.begin() as conn in SQLAlchemy; an SSE endpoint that yields events (Exceptions & Responses).

ConstructProtocolTypical library use
async for x in it__aiter__ / __anext__ (raises StopAsyncIteration)DB cursors, message consumers, response.aiter_bytes()
Async generatorasync def + yield; aclose()paginated API reader, SSE stream
[x async for x in it]async comprehension (PEP 530)collect a small stream
async with cm__aenter__ / __aexit__clients, sessions, locks, transactions, task groups
@asynccontextmanagerasync generator with one yieldlifespan, test fixtures, transactions
contextlib.AsyncExitStackdynamic set of async CMsopen N clients in a lifespan
contextlib.aclosing(agen)closes the generator at block exitgenerators holding resources (3.10+)

Fix / how to use it:

py
"""Async generators, `async for`, `async with`, async comprehensions."""
from __future__ import annotations

import asyncio
from contextlib import asynccontextmanager
from typing import AsyncIterator


async def ticks(n: int, delay: float = 0.0) -> AsyncIterator[int]:
    """An async generator (PEP 525): `await` and `yield` in one function."""
    for i in range(n):
        await asyncio.sleep(delay)
        yield i


class Pool:
    """A fake connection pool with an explicit async context manager protocol."""

    def __init__(self) -> None:
        self.events: list[str] = []

    async def __aenter__(self) -> "Pool":
        await asyncio.sleep(0)
        self.events.append("open")
        return self

    async def __aexit__(self, *exc: object) -> None:
        await asyncio.sleep(0)
        self.events.append("close")


@asynccontextmanager
async def transaction(pool: Pool) -> AsyncIterator[str]:
    """The decorator form: code before `yield` = __aenter__, after = __aexit__."""
    pool.events.append("BEGIN")
    try:
        yield "tx"
        pool.events.append("COMMIT")
    except Exception:
        pool.events.append("ROLLBACK")
        raise


async def demo() -> tuple[list[int], list[str]]:
    squares = [i * i async for i in ticks(4) if i % 2 == 0]  # PEP 530 async comprehension
    async with Pool() as pool:
        async with transaction(pool):
            pass
        try:
            async with transaction(pool):
                raise ValueError("constraint violated")
        except ValueError:
            pass
    return squares, pool.events

contextvars across awaits, tasks and threads Important ​

In plain words: A ContextVar is a variable whose value belongs to the current task, like thread-local storage but per task. Set a request id at the start of a request and every function that request calls, through any number of awaits, sees that id, while a concurrent request sees its own.

Common misunderstanding: "threading.local() works for async code." All tasks on a loop share one thread, so a thread-local value set by request A is visible to request B the moment A awaits. And a second one: "a value set in a child task flows back to the parent". Each task runs in a copy of its creator's context; changes in the child stay in the child (real: child saw set-in-child, parent still -).

Definition: PEP 567 (3.7): "This concept is similar to thread-local storage (TLS), but, unlike TLS, it also allows correctly keeping track of values per asynchronous task, e.g. asyncio.Task." ContextVar(name, default=...), var.set(value) returns a Token, var.reset(token) restores the previous value, var.get(). contextvars.copy_context() and Context.run(fn) run code in a given context. asyncio copies the context when it creates a Task (create_task(..., context=) since 3.11 to pass another) and when it schedules callbacks; to_thread and anyio.to_thread.run_sync copy it into the worker thread; plain loop.run_in_executor and threading.Thread do not (in the free-threaded build threads inherit it by default).

     two concurrent requests (real, ctx.concurrent_requests)
1    task req-1: request_id.set("req-1"); log "start"          task req-2: request_id.set("req-2"); log "start"
2    task req-1: await sleep  (req-2 runs here, sets its own value in its own context)
3    task req-1: log "after await" -> [req-1]                  task req-2: log "after await" -> [req-2]
4    to_thread(blocking_lookup) -> worker thread sees [req-1]  ... sees [req-2]
5    finally: request_id.reset(token)  -> outside both: "-"

Real scenario: a request id or trace id in every log line (structlog, logging.Filter); the current tenant in a multi-tenant app; OpenTelemetry's current span (stored in a ContextVar); per-request database session lookup in some frameworks; a timeout budget passed implicitly to every outbound call.

MechanismPer threadPer taskCopied into to_threadCopied into run_in_executor
Global variablenonon/an/a
threading.local()yesno (shared by all tasks on the loop)nono
ContextVaryesyesyesno (use ctx.run)
Explicit parametern/ayesyesyes

Fix / how to use it:

py
"""contextvars across awaits, tasks and threads: per-request state without globals."""
from __future__ import annotations

import asyncio
import contextvars

request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")


def log(msg: str) -> str:
    # Deep in the call stack, no parameter threading needed.
    return f"[{request_id.get()}] {msg}"


def blocking_lookup() -> str:
    return log("in worker thread")


async def handle(rid: str) -> list[str]:
    token = request_id.set(rid)
    try:
        lines = [log("start")]
        await asyncio.sleep(0.01)  # other requests run here; our value is not overwritten
        lines.append(log("after await"))
        lines.append(await asyncio.to_thread(blocking_lookup))  # to_thread copies the context
        return lines
    finally:
        request_id.reset(token)


async def concurrent_requests() -> list[list[str]]:
    # Each task created by gather() runs in a COPY of the current context.
    return list(await asyncio.gather(handle("req-1"), handle("req-2")))


async def child_changes_do_not_leak() -> tuple[str, str]:
    """A task sets the variable in its own context copy; the parent does not see it."""

    async def child() -> str:
        request_id.set("set-in-child")
        return request_id.get()

    seen_in_child = await asyncio.create_task(child())
    return seen_in_child, request_id.get()
py
from __future__ import annotations

import pytest

from app import ctx, streams


@pytest.mark.asyncio
async def test_context_var_survives_awaits_and_threads() -> None:
    assert await ctx.concurrent_requests() == [
        ["[req-1] start", "[req-1] after await", "[req-1] in worker thread"],
        ["[req-2] start", "[req-2] after await", "[req-2] in worker thread"],
    ]
    assert ctx.request_id.get() == "-"


@pytest.mark.asyncio
async def test_task_context_is_a_copy() -> None:
    assert await ctx.child_changes_do_not_leak() == ("set-in-child", "-")


@pytest.mark.asyncio
async def test_async_generators_and_context_managers() -> None:
    squares, events = await streams.demo()
    assert squares == [0, 4]
    assert events == ["open", "BEGIN", "COMMIT", "BEGIN", "ROLLBACK", "close"]

Entry points: asyncio.run, loop.run_until_complete, Runner and nest_asyncio Good to know ​

In plain words: Something synchronous has to start the loop. In a script that is asyncio.run(main()); in a server it is Uvicorn; in a test it is the pytest plugin; in Jupyter the notebook already runs a loop for you.

Common misunderstanding: "I can call asyncio.run() from inside async code to run a coroutine synchronously." Real: RuntimeError: asyncio.run() cannot be called from a running event loop. Inside async code you await; from a thread you use asyncio.run_coroutine_threadsafe(coro, loop). nest_asyncio patches asyncio to allow nesting ("This module patches asyncio to allow nested use of asyncio.run and loop.run_until_complete"), but it changes loop internals, does not support uvloop ("Only event loops from asyncio can be patched"), and hides design problems; treat it as a notebook workaround.

Definition: asyncio.run(coro, *, debug=None) (3.7+; loop_factory 3.12+): creates a new loop, runs the coroutine, cancels remaining tasks, shuts down async generators and the default executor, closes the loop. asyncio.Runner (3.11+) exposes the same machinery for several calls on one loop. loop.run_until_complete(fut) is the older low-level call (still used when you manage the loop yourself, as the snippet's test server does in its thread); loop.run_forever() + loop.stop() for servers. asyncio.get_event_loop() has "rather complex behavior" and, since 3.14, "Raises a RuntimeError if there is no current event loop"; the docs prefer get_running_loop() in coroutines and callbacks.

     asyncio.run(main())
1    loop = new_event_loop(); set as current
2    task = loop.create_task(main()); loop.run_until_complete(task)
3    main returns
4    cancel all remaining tasks; run loop until they finish cancelling
5    loop.run_until_complete(loop.shutdown_asyncgens())
6    loop.run_until_complete(loop.shutdown_default_executor())   (3.9+)
7    loop.close()

Real scenario: a CLI command that calls three async APIs (asyncio.run); a Celery task (sync) that needs an async client (asyncio.run per task, or better a sync client); a Django management command calling an async library; a notebook where await works at top level but asyncio.run fails; a thread that hands work to the main loop (run_coroutine_threadsafe).

SituationUse
Script / CLI entry pointasyncio.run(main())
Several runs on one loop (3.11+)with asyncio.Runner() as r: r.run(a()); r.run(b())
Custom loop (uvloop)uvloop.run(main()) or asyncio.run(main(), loop_factory=uvloop.new_event_loop) (3.12+)
Inside a coroutineawait
From another thread to a running loopasyncio.run_coroutine_threadsafe(coro, loop).result()
A loop in a background threadloop.run_until_complete(...) / run_forever() in that thread
Jupyter / IPythontop-level await (the kernel runs a loop); nest_asyncio only as a last resort
Sync code that must call async code onceanyio.from_thread.run from a worker thread, or asyncio.run in a fresh thread

Debugging: PYTHONASYNCIODEBUG, debug mode, slow callbacks, "coroutine was never awaited" Must-know ​

In plain words: asyncio has a debug mode that checks for the classic mistakes: callbacks that hold the loop too long, coroutines nobody awaited (with the place they were created), non-thread-safe calls from other threads. Turn it on in development and in tests.

Common misunderstanding: "If nothing is logged, nothing blocks." The slow-callback warning exists only in debug mode; in production mode the snippet's 200 ms time.sleep inside a coroutine printed nothing about it (real: the default-mode stderr has no Executing line). And "coroutine was never awaited" is printed when the coroutine object is garbage collected, which may be far from the bug, unless debug mode records where it was created.

Definition: "There are several ways to enable asyncio debug mode: Setting the PYTHONASYNCIODEBUG environment variable to 1. Using the Python Development Mode. Passing debug=True to asyncio.run(). Calling loop.set_debug()." In debug mode, "Callbacks taking longer than 100 milliseconds are logged. The loop.slow_callback_duration attribute can be used to set the minimum execution duration in seconds that is considered "slow"", the selector's slow I/O is logged, and "Many non-threadsafe asyncio APIs (such as loop.call_soon() and loop.call_at() methods) raise an exception if they are called from a wrong thread". The docs also recommend logging.basicConfig(level=logging.DEBUG) and -W default for ResourceWarning. Flags like python -I or -E make the interpreter ignore PYTHON* variables, including PYTHONASYNCIODEBUG (found while building the snippet test). 3.14 adds python -m asyncio ps PID and pstree PID to inspect the tasks of a running process.

     the same script, two modes (real, tests/test_debug.py, CPython 3.9.6)
1    default:  <string>:8: RuntimeWarning: coroutine 'forgotten' was never awaited
2              Task exception was never retrieved / future: <Task finished name='Task-2' ... exception=ValueError('lost')>
3    PYTHONASYNCIODEBUG=1: the same two, plus
4              Coroutine created at (most recent call last) ... File "<string>", line 8, in main
5              Executing <Task pending name='Task-1' coro=<main() running at <string>:13> ...> took 0.213 seconds
6              source_traceback: Object created at (most recent call last) ...

Real scenario: a p99 spike that turns out to be a json.dumps of a 20 MB response inside an async def (found with debug mode in a load test); a background task that silently died weeks ago (Task exception was never retrieved in the logs nobody read); a missing await on session.commit() that made writes disappear; a test suite that runs with PYTHONASYNCIODEBUG=1 in CI to catch regressions.

SymptomLikely causeHow to find it
coroutine '...' was never awaitedmissing await, or a coroutine passed where a function was expecteddebug mode shows "Coroutine created at"
Task exception was never retrievedfire-and-forget task failedkeep references; done-callback that logs
Task was destroyed but it is pending!loop closed with live tasks; unreferenced task collectedcancel and await tasks on shutdown
Executing <Task ...> took 0.213 secondsblocking call or CPU on the loopthe task repr names the coroutine and line
All endpoints slow at onceloop blockeddebug mode, heartbeat lag, py-spy dump
... attached to a different loop (3.9 tasks.py)primitive, Future or client created on another loop (tests, import time)create inside the running loop
RuntimeError: Non-thread-safe operation invoked on an event loop other than the current onecall_soon from a thread in debug modecall_soon_threadsafe

Fix / how to use it: run tests and local servers with PYTHONASYNCIODEBUG=1 (or python -X dev), lower loop.slow_callback_duration to 0.05 in load tests, and treat every one of the messages above as a bug.

py
"""Debug mode and the warnings it prints, captured from a child interpreter."""
from __future__ import annotations

import os
import re
import subprocess
import sys
import textwrap

import pytest

SCRIPT = textwrap.dedent(
    """
    import asyncio, time

    async def forgotten():
        return 1

    async def main():
        forgotten()                 # missing await
        time.sleep(0.2)             # blocks the loop for 200 ms
        async def boom():
            raise ValueError("lost")
        t = asyncio.ensure_future(boom())
        await asyncio.sleep(0.01)
        del t                       # exception never retrieved

    asyncio.run(main())
    """
)


def run_child(env_extra: dict[str, str]) -> str:
    env = {**os.environ, "PYTHONDONTWRITEBYTECODE": "1", **env_extra}
    if "PYTHONASYNCIODEBUG" not in env_extra:
        env.pop("PYTHONASYNCIODEBUG", None)
    # No -I/-E here: those flags make the child ignore PYTHON* variables, debug mode included.
    proc = subprocess.run([sys.executable, "-c", SCRIPT], capture_output=True, text=True, env=env, timeout=30)
    return proc.stderr


def test_never_awaited_warning_without_debug() -> None:
    err = run_child({})
    print("\n--- default mode stderr ---\n" + err)
    assert "RuntimeWarning: coroutine 'forgotten' was never awaited" in err
    assert "Task exception was never retrieved" in err
    assert "Executing" not in err  # no slow-callback report outside debug mode


@pytest.mark.parametrize("env", [{"PYTHONASYNCIODEBUG": "1"}])
def test_debug_mode_reports_slow_callbacks(env: dict[str, str]) -> None:
    err = run_child(env)
    print("\n--- PYTHONASYNCIODEBUG=1 stderr ---\n" + err)
    assert re.search(r"Executing <Task .* took \d+\.\d+ seconds", err)  # slow callback (> 100 ms)
    assert "Coroutine created at" in err or "was never awaited" in err

Async HTTP clients: httpx AsyncClient and connection limits Must-know ​

In plain words: httpx.AsyncClient is the async version of httpx.Client: the same API with await. Create one per process and reuse it; it holds a connection pool, so requests to the same host reuse TCP and TLS connections.

Common misunderstanding: "async with httpx.AsyncClient() as c: inside every request is the normal pattern." It opens a new pool per request: new TCP and TLS handshakes every time and no limit across requests. The httpx docs: "If you do anything more than experimentation, one-off scripts, or prototypes, then you should use a Client instance", because "a Client instance uses HTTP connection pooling"; open it once in the lifespan as the After app does. A second one: "gather() over 10,000 URLs is fine because httpx limits connections." It limits connections (default 100), but you still create 10,000 tasks and wait in the pool's queue, where the pool timeout can fire; bound the number of tasks too.

Definition: httpx resource limits: "max_keepalive_connections, number of allowable keep-alive connections, or None to always allow. (Defaults 20) max_connections, maximum number of allowable connections, or None for no limits. (Default 100) keepalive_expiry … (Default 5)". Timeouts: "The default behavior is to raise a TimeoutException after 5 seconds of network inactivity", configurable per phase (connect, read, write, pool) with httpx.Timeout. httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) calls an ASGI app in-process (the tests use it). trust_env=False ignores proxy environment variables (httpx: "Environment variables are used by default. To ignore environment variables, trust_env has to be set False"; used in the snippets so a developer's proxy settings do not change the measurement). The Redis client's asyncio API is import redis.asyncio as redis (redis-py docs).

     20 x GET /delay/100 (real, app/fanout.py, the measurement in the Lab)
1    sync sequential (httpx.Client)           2.072 s   20 x 100 ms, one after another
2    sync + ThreadPoolExecutor(20)            0.133 s   20 threads, shared thread-safe Client
3    async gather (httpx.AsyncClient)         0.136 s   20 tasks, one thread
4    async gather + Semaphore(5)              0.439 s   4 waves of 5
5    sync client inside async def + gather    2.068 s   no await -> no overlap

Real scenario: a BFF (backend for frontend) that calls six internal services per page; a webhook dispatcher with thousands of subscribers; a price aggregator polling 50 suppliers; an LLM gateway streaming responses (client.stream(...) + aiter_bytes()). Retries, circuit breakers and caching for these calls are in Background Tasks, Caching & External APIs.

SettingDefaultChange when
Limits(max_connections=...)100upstream allows fewer; or several workers × 100 is too many
Limits(max_keepalive_connections=...)20steady high fan-out to one host
Limits(keepalive_expiry=...)5 sload balancer idle timeout is shorter
Timeout(5.0)5 s each phasealways set explicitly per upstream
Timeout(pool=...)5 smany tasks wait for a pooled connection
One client per processyour jobalways: create in lifespan, close on shutdown

Fix / how to use it: the lifespan of app/after.py is the template: one AsyncClient with explicit Limits and Timeout, stored on app.state, a Semaphore no larger than max_connections, and an asyncio-level deadline per call.

How FastAPI, Starlette and Uvicorn use the loop Must-know ​

In plain words: Uvicorn starts one event loop per worker process and runs every request of that worker as a coroutine on it. FastAPI awaits your async def route on that loop; it runs your def route in a worker thread so that blocking code there does not freeze the loop. Starlette and FastAPI do that through AnyIO.

Common misunderstanding: "def routes are the slow, old style." They are the correct choice for blocking libraries; the FastAPI docs say a def path operation "is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server)". The mistake is the opposite one: blocking code in async def. The first-contact measurement of this rule (5 × 200 ms: 1.05 s vs 0.21 s) is in FastAPI Fundamentals; this page's Before/After shows it for a fan-out route.

Definition: Uvicorn's --loop option: "Set the event loop implementation. The uvloop implementation provides greater performance, but is not compatible with Windows or PyPy … Options: 'auto', 'asyncio', 'uvloop' … Default: 'auto'" (the current docs also list a zuvloop option for CPython 3.14+, not in the pinned 0.39.0). Real with 0.39.0: --loop auto: uvloop.Loop tokens=40, --loop asyncio: asyncio.unix_events._UnixSelectorEventLoop tokens=40. Starlette: run_in_threadpool(func, *args) is await anyio.to_thread.run_sync(func); "The default thread pool size is only 40 tokens. This means that only 40 threads can run at the same time", adjustable via anyio.to_thread.current_default_thread_limiter().total_tokens. The same pool runs sync dependencies, sync yield dependencies and file responses.

     one Uvicorn worker, three requests (real thread names from test_before_after.py)
1    loop thread    GET /dashboard/ana (async def): awaits 5 upstream calls via AsyncClient
2    loop thread    GET /health (async def): answered while /dashboard waits -> 0.002 s
3    AnyIO worker   GET /report (def): time.sleep(0.05) in "AnyIO worker thread"
4    AnyIO worker   GET /legacy (async def) -> await run_in_threadpool(...) -> "AnyIO worker thread"
5    loop thread    /dashboard resumes, to_thread(render_chart) -> default executor -> returns

Real scenario: a mixed codebase with some sync SQLAlchemy routes (def) and some async httpx routes (async def); a service whose 41st concurrent def request waits because 40 tokens are busy on a slow database; a team that sets --loop asyncio to debug a uvloop-specific issue; a Windows developer machine without uvloop.

Route / callRuns onConcurrency limitBlocks the loop if it blocks?
async def routeevent loopnone built in (Uvicorn --limit-concurrency)yes
def routeAnyIO worker thread40 tokens (shared)no
async def dependencyevent loopn/ayes
def dependency (also with yield)AnyIO worker thread40 tokensno
await run_in_threadpool(f)AnyIO worker thread40 tokensno
await asyncio.to_thread(f)asyncio default executormin(32, cpu + 4)no
BackgroundTasks.add_task(def_fn)AnyIO worker thread after the response40 tokensno
StreamingResponse(sync_iterator)iterate_in_threadpool40 tokensno

Fix / how to use it: async def only when everything inside awaits; otherwise def; raise the AnyIO limiter in the lifespan only after measuring (each token is a possible thread and, usually, a database connection); worker processes, --limit-concurrency and graceful shutdown settings are in FastAPI in Production.

Testing async code: pytest-asyncio and the AnyIO pytest plugin Important ​

In plain words: pytest does not know how to run async def tests by itself. A plugin creates an event loop per test (or per module/session) and runs the coroutine on it.

Common misunderstanding: "pytest runs async def tests like any other." pytest alone cannot run them; pytest 8.4.2 with the plugins disabled fails such a test with async def functions are not natively supported. and "You need to install a suitable plugin for your async framework" (real, runs/pytest-no-plugin.txt). With pytest-asyncio in strict mode, an unmarked async test is not picked up by the plugin either. Mark every async test (strict mode) or configure auto mode, and assert something only the awaited code can produce.

Definition: pytest-asyncio "provides two modes for test discovery, strict and auto. … In strict mode pytest-asyncio will only run tests that have the asyncio marker"; asyncio_mode = "auto" treats every async def test as asyncio; @pytest.mark.asyncio(loop_scope="module") shares a loop between tests; asyncio_default_fixture_loop_scope sets it for async fixtures. Version used: 1.2.0, the last to admit Python 3.9 (1.3.0 requires ≥ 3.10). AnyIO ships its own plugin: @pytest.mark.anyio with an anyio_backend fixture ("asyncio" or "trio"). The AnyIO docs warn that its auto mode "does not work if pytest-asyncio is installed and configured to use its own auto mode, as it will conflict with the AnyIO plugin"; the snippet project therefore uses pytest-asyncio's strict mode and marks every test explicitly. FastAPI's "Async Tests" page uses @pytest.mark.anyio with httpx.AsyncClient(transport=ASGITransport(app=app)).

     tests/ in this chapter (real: 43 passed, 2 skipped in 10.17 s)
1    @pytest.mark.asyncio  -> pytest-asyncio creates a loop for the test, runs it, closes it
2    @pytest.mark.anyio    -> AnyIO plugin runs it on the backend from anyio_backend ("asyncio")
3    plain def tests       -> run sync; they call asyncio.run() themselves where needed
4    @needs_311            -> skipif(sys.version_info < (3, 11)): TaskGroup, asyncio.timeout
5    session fixture       -> the local upstream server in its own thread, shared by all tests

Real scenario: testing a FastAPI app's async routes with httpx.AsyncClient + ASGITransport (lifespan entered manually with app.router.lifespan_context(app), because ASGITransport does not run it); an async repository tested against SQLite with aiosqlite; a library tested on both asyncio and Trio with the AnyIO plugin; a flaky test caused by a module-level asyncio.Lock() bound to another loop.

ToolMarker / configLoop scopeNotes
pytest-asyncio (strict)@pytest.mark.asynciofunction default; loop_scope=default mode
pytest-asyncio (auto)asyncio_mode = "auto"sameconflicts with AnyIO auto mode
AnyIO plugin@pytest.mark.anyio, anyio_backend fixtureper testasyncio and Trio; used by FastAPI docs
TestClient (Starlette)sync testsits own loop in a thread (portal)runs lifespan in with
httpx.ASGITransportasync teststhe test's loopno lifespan; enter it yourself
unittest.IsolatedAsyncioTestCasestdlibper testno plugin needed

Fix / how to use it: the pyproject.toml and tests above are the template; testing FastAPI apps in depth (fixtures, overrides, databases) is in Testing FastAPI.

Graceful shutdown of tasks Important ​

In plain words: When the process is told to stop (SIGTERM from Kubernetes, Ctrl+C), in-flight requests should finish, background tasks should get a short grace period, and whatever is left should be cancelled and awaited so that their finally blocks close connections, before the process exits.

Common misunderstanding: "Uvicorn handles shutdown, my tasks are fine." Uvicorn stops accepting connections and waits for open requests (bounded by --timeout-graceful-shutdown), then runs the lifespan's shutdown part. Tasks you started yourself are your responsibility: if the lifespan does not cancel and await them, they are destroyed with the loop (Task was destroyed but it is pending!) and their cleanup never runs.

Definition: The pattern: keep every background task in an owner (a set, a TaskGroup, an AnyIO task group); in the lifespan after yield, wait up to a deadline (asyncio.wait(tasks, timeout=...)), cancel the pending ones, then await asyncio.gather(*pending, return_exceptions=True) so the cancellations complete. asyncio.run does a last-resort version (cancels all remaining tasks before closing the loop). 3.13's Queue.shutdown() stops producers and consumers of a queue cleanly.

     SIGTERM to a Uvicorn worker running app/after.py (lifespan shutdown, real in test_after_shutdown_drains_background_tasks)
1    Uvicorn stops accepting; waits for in-flight requests (--timeout-graceful-shutdown)
2    lifespan resumes after `yield`
3    background.drain(timeout=2.0): wait for audit tasks -> done within the deadline
4    pending tasks (if any) cancelled and awaited -> their finally blocks run
5    AsyncClient.__aexit__ closes pooled connections
6    process exits; app.state.cancelled_on_shutdown == 0, audit_log == ["bo"]

Real scenario: Kubernetes sends SIGTERM and waits terminationGracePeriodSeconds before SIGKILL; a consumer loop must stop taking new messages but finish the current one and ack it; a WebSocket server closes client connections with a "going away" code; a periodic cache refresher must stop without leaving a half-written key.

StepOwnerBound
Stop accepting new workUvicorn / your consumer loop (Event)immediate
Finish in-flight requestsUvicorn--timeout-graceful-shutdown
Drain background tasksyour lifespana few seconds
Cancel the rest and await themyour lifespanuntil finally blocks finish
Close clients and poolsasync with in the lifespanimmediate
Hard killthe orchestrator (SIGKILL)grace period

Fix / how to use it: BackgroundTasks.drain() in app/tasks.py and the lifespan in app/after.py; keep the total shorter than the orchestrator's grace period; deployment settings in FastAPI in Production.

Databases from async code: sync drivers, async drivers, one session per task Good to know ​

In plain words: A database call is network I/O, so in async code it should be awaited through an async driver. A sync driver in async def blocks the loop for every query; it is the most common way FastAPI apps lose their concurrency.

Common misunderstanding: "An async driver lets one session run queries in parallel." A connection (and a SQLAlchemy session) handles one statement at a time; concurrency comes from several connections. SQLAlchemy: "The AsyncSession is not safe for use in concurrent tasks." One session per request (or per task), a pool sized for the concurrency you allow.

Definition: Sync drivers: psycopg2, pymysql, sqlite3, sync SQLAlchemy Session. Async drivers: asyncpg, psycopg 3 (async mode), aiomysql/asyncmy, aiosqlite; SQLAlchemy 2's asyncio extension (create_async_engine, AsyncSession) runs on them and uses the greenlet library to drive the ORM internals; SQLModel and Alembic sit on top. With a sync driver, keep the route def (FastAPI threads) or call it via to_thread, and make the pool at least as large as the number of threads that can use it. The full ORM treatment is in SQLAlchemy 2 & SQLModel; migrations in Alembic Migrations.

     three concurrent requests, async driver, pool size 2
1    task A: acquire conn 1 -> await SELECT ...        (loop free)
2    task B: acquire conn 2 -> await SELECT ...        (loop free)
3    task C: await pool.acquire()  -> waits for a free connection (pool timeout applies)
4    A's result arrives -> A releases conn 1 -> C acquires it
     sync driver in async def instead: A's query holds the loop; B and C cannot even start

Real scenario: a FastAPI app built with async def routes and psycopg2 (every query blocks every request); a migration to asyncpg that also needs expire_on_commit=False and explicit eager loading (lazy loads in async code raise errors in SQLAlchemy); a script that uses asyncio.gather with one shared AsyncSession and fails with session-state errors; a pool of 5 connections behind 40 thread tokens.

StackRoute styleBlocks the loop?Where it is taught
SQLAlchemy Session + psycopg2 / sqlite3defno (thread pool)SQLAlchemy 2 & SQLModel
SQLAlchemy Session in async defasync defyes (bug)this page
AsyncSession + asyncpg / aiosqliteasync defnoSQLAlchemy 2 & SQLModel
asyncpg directlyasync defnoasyncpg docs
Motor / Beanie (MongoDB)async defnoMongoDB with FastAPI
redis.asyncioasync defnoBackground Tasks & Caching

Fix / how to use it: pick one style per route and keep it consistent end to end; the SQL above (query_orders) is what both styles send; only the waiting differs.

Mechanics ​

How a Task drives a coroutine Important ​

A coroutine is a generator-like object with send() and throw(). A Task calls coro.send(None); the coroutine runs until the innermost await reaches something not ready, which yields a Future all the way up; the Task attaches its wake-up method to that Future with add_done_callback and returns control to the loop. When the Future gets a result (a socket became readable, a timer fired, a thread finished), the callback schedules the Task's next step with call_soon, and send(None) resumes the coroutine where it stopped. Cancellation is coro.throw(CancelledError) at the next step. Nothing in this cycle is preemptive: the switch points are yields out of send(), which happen only when an await reaches a pending Future or a bare yield (what asyncio.sleep(0) does; tasks.py handles result is None by rescheduling the step). Awaiting a coroutine that returns without suspending, or a Future that is already done, continues in the same step with no switch (real, runs/probe_await_yield-output.txt: ['after await instant()', 'after await done Future', 'child', 'after await asyncio.sleep(0)']). A loop of such awaits starves every other task just like a CPU loop.

     Task.__step (CPython asyncio/tasks.py), one await of a socket read
1    result = coro.send(None)              # runs your code up to the next real suspension
2    result is a Future with _asyncio_future_blocking set   # e.g. the Future of a pending sock_recv
3    result.add_done_callback(self.__wakeup)
4    return                                # back to the loop; other handles run
5    ... selector: socket readable -> reader callback -> fut.set_result(data)
6    fut's done callbacks are scheduled: loop.call_soon(self.__wakeup, fut)
7    __wakeup -> __step -> coro.send(None) -> the await expression returns data
8    on task.cancel(): next __step does coro.throw(CancelledError) instead of send
EventWho actsAPI underneath
create_task(coro)looploop.call_soon(task.__step)
await asyncio.sleep(d)loop timer heaploop.call_later(d, futures._set_result_unless_cancelled, future, result)
await reader.read()selectorloop.add_reader(fd, callback)
await to_thread(f)executor threadloop.run_in_executor + call_soon_threadsafe
task.cancel()tasksets a flag; next step throws CancelledError
Task finishesFuture callbacksawaiting tasks are woken

Exact errors, warnings and log lines Must-know ​

Every line below was printed by the snippet run or the probes saved under pipeline/sources/async-python-asyncio/runs/ (CPython 3.9.6; anyio 4.12.1; Uvicorn 0.39.0; pytest 8.4.2).

TriggerOutput
Coroutine never awaitedRuntimeWarning: coroutine 'forgotten' was never awaited + RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Same in debug modeadds Coroutine created at (most recent call last) with the stack
Failed task never awaitedTask exception was never retrieved / future: <Task finished name='Task-2' coro=<main.<locals>.boom() done, ...> exception=ValueError('lost')>
Loop closed with a pending taskTask was destroyed but it is pending! / task: <Task pending name='Task-6' coro=<forever() done, ...> wait_for=<Future pending ...>>
Slow callback, debug modeExecuting <Task pending name='Task-1' coro=<main() running at <string>:13> ...> took 0.213 seconds
asyncio.run in a running loopRuntimeError: asyncio.run() cannot be called from a running event loop
Awaiting a coroutine twiceRuntimeError: cannot reuse already awaited coroutine
asyncio.TaskGroup on 3.9AttributeError: module 'asyncio' has no attribute 'TaskGroup'
Bare coroutine to wait() on 3.9DeprecationWarning: The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.
put_nowait on a full queueasyncio.QueueFull
asyncio.TimeoutError is TimeoutError on 3.9False (alias since 3.11)
CancelledError base class on 3.9BaseException
Default loop on macOS_UnixSelectorEventLoop, slow_callback_duration: 0.1
Uvicorn --loop auto / asyncio / uvloopuvloop.Loop / asyncio.unix_events._UnixSelectorEventLoop / uvloop.Loop, AnyIO tokens=40 each
def route / run_in_threadpool thread nameAnyIO worker thread
Default executor on 12 CPUsmax_workers=16
Unmarked async test, no plugin (pytest 8.4.2)async def functions are not natively supported.
AnyIO group with a failing childExceptionGroup (from the exceptiongroup backport on 3.9) with the child's ValueError

Version matrix: what you can use where Important ​

Feature3.93.103.113.123.133.143.15
asyncio.run, create_task, gather, wait_for, Queueyesyesyesyesyesyesyes
asyncio.to_threadyes (new)yesyesyesyesyesyes
loop= parameter on high-level APIsdeprecatedremovedremovedremovedremovedremovedremoved
TaskGroup, timeout(), Runner, Barrier, except*nonoyesyesyesyesyes (+ tg.cancel())
asyncio.TimeoutError is TimeoutErrornonoyesyesyesyesyes
Bare coroutines in wait()warningwarningerrorerrorerrorerrorerror
Eager task factory, run(loop_factory=)nononoyesyesyesyes
Queue.shutdown, async for over as_completednonononoyesyesyes
Free-threaded buildnonononoexperimentalsupported (optional)supported (optional)
python -m asyncio ps / pstreenononononoyesyes
Policy systemyesyesyesyesyesdeprecated (removal 3.16)deprecated (removal 3.16)
Default ThreadPoolExecutor sizemin(32, cpu_count + 4)samesamesameprocess_cpu_count + 4 (cap 32)samesame

Solving the classic problems ​

BugSymptomFixCost
Sync HTTP client in async routeevery endpoint slow during upstream latency; measured /health 0.554 shttpx.AsyncClient from the lifespan, or a def routesmall
time.sleep blocks the loop (in a coroutine)heartbeat gap 0.211 sawait asyncio.sleepnone
Sync DB driver in async defthroughput of one request at a timeasync driver, or def route + poolmedium
Unbounded gather over a big listsockets exhausted, upstream 429s, pool timeoutsSemaphore, or worker pool over a bounded Queuesmall
Fire-and-forget create_tasklost work, Task exception was never retrievedtracked set / TaskGroup; queue for durable worksmall
Swallowed CancelledErrorshutdown hangs, timeouts do not firere-raise after cleanupnone
No timeout on outbound callsrequests pile up during an outageclient Timeout + wait_for / timeout()none
gather fails fast, siblings keep runningwasted work, side effects after an errorTaskGroup / AnyIO task groupsmall
CPU work on the looplatency spikes, debug "took 0.4 seconds"ProcessPoolExecutor or a job queuemedium
Thread-local request statewrong request id in logsContextVarsmall
Lock-free read-await-writelost updates (50 → 1 measured)asyncio.Lock, or atomic SQLsmall
Client per requestnew TLS handshake per call, no global limitone client per processsmall
Primitives created at import"attached to a different loop" in testscreate in lifespan / fixturessmall
Tasks alive at shutdownTask was destroyed but it is pending!drain + cancel + await in the lifespansmall

Keeping the event loop free ​

The Before app shows the three ways a loop gets blocked (sync client, time.sleep, blocking render), and the After app removes each one: an async client, await asyncio.sleep where a delay is needed, and to_thread for the step that has no async version. Prove it with the two cheap probes from the snippets: a heartbeat task whose worst gap should stay near its interval, and a "fire /health while the slow route runs" test. In production, run a canary with debug mode or measure loop lag (the same heartbeat as a metric).

Bounded fan-out with timeouts ​

gather over a list is correct only for small, known lists. For anything sized by input, put a Semaphore around each call (the snippet's async_bounded and fetch_section), keep it at or below the client's max_connections, give each call a deadline and the whole operation a budget. Measured, 20 calls with Semaphore(5) took 0.439 s (four waves), which is the price of protecting the upstream; with TaskGroup on 3.11+ a failure also cancels the remaining calls.

Never losing a task ​

Every create_task result goes into an owner: a TaskGroup when the lifetime is a block, a tracked set (the snippet's BackgroundTasks) when the lifetime is the process, a job queue when the work must survive a crash. The owner logs failures and is drained in the lifespan.

Cancellation that works ​

Cleanup in finally or async with, re-raise CancelledError, shield only an inner operation you also hold a reference to, and add await asyncio.sleep(0) in long CPU loops that must be cancellable (or move them to a process). Test it: the snippet's test_cancel_runs_finally_and_propagates is the minimal contract.

Choosing ​

SituationUseExtra techniqueReason
Many concurrent network calls with async librariesasyncio tasksSemaphore + timeoutscheapest concurrency per wait
Need all results, fail fast, cancel the restTaskGroup (3.11+) / AnyIO task groupasyncio.timeout around itstructured concurrency
Partial failure acceptablegather(return_exceptions=True)log each failureone bad source must not fail the page
First answer winswait(FIRST_COMPLETED)cancel the losershedged requests
Stream results as they comeas_completedcancel on early exitlower time-to-first-result
Library only exists in sync formto_thread / def routededicated executor for slow depskeeps the loop free
CPU work 10 ms – secondsProcessPoolExecutor via run_in_executorSemaphore on submissionsuses cores, keeps the loop free
CPU work longer, or must survive restartsjob queue (Celery, arq, RQ, Dramatiq)idempotent jobsdurability, retries
Producer faster than consumerbounded Queuereject or drop policyback-pressure
Per-request state through the call stackContextVarreset in finallycorrect under concurrency
Code must run on asyncio and Trio, or on 3.9/3.10 with structured concurrencyAnyIO@pytest.mark.anyioone API, cancel scopes
Sync program needs one async callasyncio.runn/asimplest bridge
Notebooktop-level awaitnest_asyncio only if forcedloop already running

When asyncio vs threads vs processes vs Go ​

NeedasyncioThreads (default CPython)ProcessesGo
10,000 idle connections (WebSockets, SSE)bestexpensivevery expensivebest
Fan-out to 20 HTTP calls0.136 s measured0.133 s measuredoverkillgoroutines
Library ecosystemmust be asyncanyanyGo libraries
CPU parallelismnonenone for pure Python (GIL)yesyes
Blocking-call safetyone blocking call stalls allisolated per threadisolated per processblocking is normal
Shared statesafe between awaitslocks everywhereno sharing (IPC)channels / mutexes
CancellationCancelledError, scopescooperative flags onlykill the processcontext.Context
Debuggabilitydebug mode, task introspectionstack per threadper processrace detector, pprof

For 20 calls threads and asyncio measured the same; asyncio wins when the number of concurrent waits grows into the thousands (memory and thread limits) and when you want timeouts and cancellation that compose. The Go column is unpacked in The Go angle.

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One FastAPI app under one Uvicorn worker: one event loop, one httpx.AsyncClient, one async database pool, one AnyIO thread limiter, one tracked set of background tasks, all created in the lifespan. Every rule on this page applies inside that process: nothing blocking on the loop, bounded fan-out, timeouts on every call, tasks drained on shutdown. Example: a shop backend whose product page awaits price, stock and reviews concurrently (three queries on three pooled connections, ~1 round trip of latency instead of 3), whose invoice PDF runs in a process pool, and whose order-confirmation e-mail is a tracked background task.

Modular monolith and multiple databases ​

Still one loop per process, now shared by modules that do not know each other. The shared resources become the contention points: the default executor (16 threads measured here) is shared by every module's to_thread calls, the AnyIO limiter (40) by every def route and sync dependency, the HTTP client pool by every upstream. Give each slow dependency its own executor and client with its own limits, so the reporting module's slow sync SDK cannot starve checkout. Multiple databases (PostgreSQL, Redis, a search index) each get an async client with its own pool size; their sum times the number of workers must stay below each server's connection limit.

Microservices ​

Every network hop is an await that can be slow or fail, so the in-process tools become distributed-systems tools: per-call timeouts shorter than the caller's budget (deadline propagation, e.g. a header with the remaining budget), bounded concurrency per upstream, hedged requests with wait(FIRST_COMPLETED) for idempotent reads, cancellation of downstream work when the client disconnects. Example flow: GET /orders/42/summary → TaskGroup with GET orders/42 (300 ms), GET payments?order=42 (300 ms), GET shipping/42 (300 ms) inside asyncio.timeout(0.8) → one failure cancels the other two and maps to 502/504. What does not cross the hop: ContextVar values (send the request id as a header; OpenTelemetry does this), cancellation (a cancelled client call does not stop the server's work unless the server notices the disconnect), and in-process back-pressure (use a broker with consumer limits, or 429s with Retry-After). Retries and idempotency: API Idempotency.

Distributed data: replicas, caches, sharded databases, multi-region ​

asyncio makes it cheap to talk to many data nodes at once (scatter-gather over shards, parallel cache lookups, reading from the nearest replica) and just as cheap to overload them. Concurrency limits move from "per process" to "per fleet": 20 workers × Semaphore(10) is 200 concurrent queries against one shard. Locks and semaphores on this page are per process; cross-process coordination needs the database (row locks, advisory locks), Redis or a lease service. A cache stampede (many tasks missing the same key at once) is solved inside one process with a per-key asyncio.Lock or a shared Future ("single flight") and across processes with a Redis lock or request coalescing at the cache tier. Replica lag and caching patterns: Caching.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesAsync practice
1× (one process)defaults seem fineno blocking calls in async def; one client per process; timeouts; tracked tasks; debug mode in tests
10× (workers ≈ cores, several replicas)per-process limits multiply; deploys drop worksize pools × workers ≤ server limits; graceful shutdown with drain; ContextVar request ids; loop-lag metric; uvloop on Linux
100× (many services, high fan-out)tail latency, retry storms, thread-pool exhaustiondeadline propagation; bounded fan-out per upstream; load shedding (--limit-concurrency, 503s); CPU work out of the web tier into queues and process pools (Load Shedding)

Lab ​

All commands run from docs/snippets/python/async-python-asyncio/. Outputs marked "real" were produced on CPython 3.9.6 (macOS, 12 CPUs) with the pinned versions; on Python 3.12+ with current releases the outputs are the same apart from version numbers, the two 3.11-only tests that then run instead of skipping, and the message texts noted on this page.

1. Install and run the tests (real) ​

python3 -m venv ~/venvs/apa                       # keep the venv outside the repo (.venv/ and *.egg-info are not git-ignored)
~/venvs/apa/bin/pip install '.[test]'             # or: pip install -r requirements.lock
export PYTHONDONTWRITEBYTECODE=1                  # pyproject sets -p no:cacheprovider
~/venvs/apa/bin/python -m pytest -s -rs
# BEFORE: /dashboard 0.574s, /health during it 0.554s
# AFTER: /dashboard 0.158s, /health during it 0.002s
# queue maxsize=5, 40 items, 4 consumers x 10 ms: {'processed': 40, 'max_qsize': 5, 'producer_wait_s': 0.088, 'elapsed_s': 0.11}
# 20 x 100 ms: sequential 2.072s | threads 0.133s | gather 0.136s | Semaphore(5) 0.439s | sync client in async def 2.068s
# worst heartbeat gap: time.sleep 0.211s, to_thread 0.011s, asyncio.sleep 0.013s
# os.cpu_count()=12 default executor max_workers=16
# 4 x cpu_burn(2000000): inline 0.42s, threads 0.37s, processes 0.18s
# SKIPPED [1] tests/test_cancellation.py:46: asyncio.TaskGroup / asyncio.timeout() are 3.11+
# SKIPPED [1] tests/test_tasks.py:68: asyncio.TaskGroup / asyncio.timeout() are 3.11+
# 43 passed, 2 skipped in 10.17s

The full transcript, including the debug-mode stderr, is runs/pytest-fresh-install.txt (all numbers on this page come from it). A rerun after two test assertions were widened for shared machines (runs/pytest-final-code.txt) printed 43 passed, 2 skipped in 9.32s with the same picture (sequential 2.053 s, gather 0.125 s, Before /health 0.569 s, After 0.001 s). With uv on Python 3.12+: uv run --extra test pytest -s (expected, not run: uv is not installed on the build machine); the two skipped tests then run and are expected to pass.

20 GET requests x 100 ms upstream delay (real run, CPython 3.9.6, httpx 0.28.1)sync sequential (httpx.Client)2.07 ssync client inside async def2.07 sAsyncClient + Semaphore(5)0.44 s (4 waves of 5)AsyncClient + gather0.14 shttpx.Client + 20 threads0.13 s01 s2 sthreads match async for 20 calls; async wins on memory and at thousands of connections

2. The fan-out measurement on its own (real) ​

~/venvs/apa/bin/python -m app.fanout
# 20 GET requests, each answered after 100 ms by a local asyncio server
# sync sequential (httpx.Client)        2.082 s
# sync + ThreadPoolExecutor(20)         0.129 s
# async gather (httpx.AsyncClient)      0.142 s
# async gather + Semaphore(5)           0.439 s
# sync client inside async def          2.071 s

Change n and delay in app/fanout.py to see the scaling: sequential grows as n × delay, gather stays near one delay until the connection limit (httpx default 100) or the server's backlog is reached, the Semaphore version grows in steps of ceil(n / limit) × delay.

3. Watch the loop block (real) ​

~/venvs/apa/bin/python -m pytest -s tests/test_offload.py -k heartbeat   # test_heartbeat_time_sleep_blocks_the_loop_to_thread_does_not
# worst heartbeat gap: time.sleep 0.211s, to_thread 0.011s, asyncio.sleep 0.013s
PYTHONASYNCIODEBUG=1 ~/venvs/apa/bin/python -m pytest -s tests/test_debug.py
# ... Executing <Task pending name='Task-1' coro=<main() running at <string>:13> ...> took 0.213 seconds

4. Which loop does Uvicorn run (real) ​

cd ../../../../pipeline/sources/async-python-asyncio/runs   # from the snippet dir: the probe ASGI app lives with the run logs
~/venvs/apa/bin/python probe_uvicorn_loops.py ~/venvs/apa/bin
# --loop auto: uvloop.Loop tokens=40
# --loop asyncio: asyncio.unix_events._UnixSelectorEventLoop tokens=40
# --loop uvloop: uvloop.Loop tokens=40

5. TaskGroup and asyncio.timeout on 3.11+ (expected, not run) ​

python3.12 -m venv ~/venvs/apa312 && ~/venvs/apa312/bin/pip install '.[test]'
~/venvs/apa312/bin/python -m pytest -q -k "taskgroup or timeout_block"
# expected: 2 passed  (taskgroup_fail_fast -> (["a failed"], ["b", "c"]); timeout_block -> "done" / "timed out")

With current releases on 3.12+ the pins can move to the latest versions (PyPI JSON saved 2026-11-29: FastAPI 0.165.0 requires_python >=3.11, uploaded 2026-11-18; httpx 0.29.0 >=3.10, 2026-11-26; pytest-asyncio 1.5.0; anyio 4.16.0); expected, not run.

For PHP/Laravel developers ​

Under PHP-FPM each request runs in its own worker process from a clean state, and every call blocks that worker: there is no event loop to block and nothing to cancel, and concurrency is "more FPM workers". That is the thread-per-request column of Why it exists. The PHP world has the same three async models Python has, each as an add-on. Fibers (PHP 8.1) are the language primitive: "Fibers represent full-stack, interruptible functions. Fibers may be suspended from anywhere in the call-stack"; unlike Python coroutines they need no async/await colouring ("the direct caller of the function does not need to change how it invokes the function"), and they need a scheduler library to be useful. ReactPHP is the asyncio analogue: "ReactPHP is a low-level library for event-driven programming in PHP. At its core is an event loop", with promises in the role of Futures. Swoole / Open Swoole is an extension with "an event loop, coroutine scheduler, servers, clients, and protocol implementations"; with its runtime hooks, ordinary PHP I/O functions become coroutine-aware, which is closer to Go (or to gevent) than to asyncio. Laravel Octane "supercharges your application's performance by serving your application using high-powered application servers, including FrankenPHP, Open Swoole, Swoole, and RoadRunner. Octane boots your application once, keeps it in memory", which brings the long-lived-process rules of this page (no request state in singletons, resources opened once) to Laravel, and on Swoole adds Octane::concurrently, whose closures "utilize Swoole's "task workers", and execute within an entirely different process than the incoming request" (a process pool, not coroutines on one loop). For concurrent HTTP calls inside one request, Laravel's HTTP client has Http::pool, which dispatches "several requests … at the same time instead of issuing the requests sequentially".

php
<?php
// Laravel 13: the dashboard fan-out (compare app/after.py)
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
use Laravel\Octane\Facades\Octane;

// Concurrent HTTP from one request: the closest thing to AsyncClient + gather()
$responses = Http::pool(fn (Pool $pool) => [
    $pool->as('orders')->timeout(1)->get("$upstream/delay/100"),     // httpx.Timeout(1.0)
    $pool->as('invoices')->timeout(1)->get("$upstream/delay/100"),
    $pool->as('tickets')->timeout(1)->get("$upstream/delay/100"),
]);

// Octane on Swoole: closures run in Swoole task workers (another process),
// so this is closer to run_in_executor(process_pool, ...) than to gather()
[$users, $servers] = Octane::concurrently([
    fn () => User::all(),
    fn () => Server::all(),
]);

// Plain PHP 8.1 Fiber: the suspension primitive a scheduler builds on (no scheduler here)
$fiber = new Fiber(function (): string {
    $reply = Fiber::suspend('waiting for socket');   // like a coroutine yielding a Future
    return "got $reply";
});
$state = $fiber->start();                             // "waiting for socket"
$fiber->resume('data');                               // the "event loop" resumes it
echo $fiber->getReturn();                             // "got data"
PHP / LaravelPython asyncio
PHP-FPM worker per requestdef route in a thread / WSGI worker
Fibers (8.1)coroutines (but no async/await colouring)
ReactPHP event loop + promisesasyncio loop + Futures
Swoole coroutines + runtime hooksasyncio tasks (Python needs async libraries; hooks resemble gevent)
Swoole\Coroutine\Channelasyncio.Queue
Octane::concurrently([...]) (Swoole task workers, separate process)run_in_executor(process_pool, ...) + gather
Octane long-lived workersUvicorn workers with a lifespan
Http::timeout(1)httpx.Timeout(1.0)
Queued jobs (dispatch(new Job))job queue (Celery, arq), not create_task
sleep() in a Swoole coroutine with hooksawait asyncio.sleep()
Laravel Http::pool(fn (Pool $pool) => [...])AsyncClient + gather

The Go angle ​

Go makes the opposite design choice to asyncio: there is no async keyword and no event loop in your code; every function may block, and the runtime multiplexes goroutines over OS threads and the network poller. The tour: "A goroutine is a lightweight thread managed by the Go runtime." The consequences, point by point: a blocking call in Go blocks only its goroutine (no "blocking the loop" bug), CPU work runs in parallel on GOMAXPROCS threads (no GIL), and the colouring problem ("this function is async, so its caller must be") does not exist. What Go has to add by convention is what asyncio has built in: cancellation is a context.Context passed explicitly (see context), where asyncio injects CancelledError at the next await; a forgotten goroutine leaks silently, like a dropped task; and the structured-concurrency helper is errgroup.Group with WithContext, the counterpart of TaskGroup (Worker Pools & Pipelines). Channels play the role of asyncio.Queue, and Effective Go's rule "Do not communicate by sharing memory; instead, share memory by communicating" applies to both; the pipelines article describes a pipeline as "a series of stages connected by channels". Data races, which asyncio code mostly avoids by running on one thread, are a real concern in Go and have a detector (Race Conditions & Deadlocks); the asyncio lost-update example above has a Go twin in sync.Mutex.

go
// Go: the bounded dashboard fan-out (compare app/after.py fetch_section + Semaphore)
func dashboard(ctx context.Context, client *http.Client, upstream string) (map[string]json.RawMessage, error) {
	ctx, cancel := context.WithTimeout(ctx, time.Second) // asyncio.timeout(1.0)
	defer cancel()
	g, ctx := errgroup.WithContext(ctx) // TaskGroup: first error cancels ctx for the rest
	g.SetLimit(10)                      // Semaphore(10)
	sections := []string{"orders", "invoices", "tickets", "shipments", "reviews"}
	results := make([]json.RawMessage, len(sections))
	for i := range sections {
		g.Go(func() error { // a goroutine, not a coroutine: may block freely
			req, _ := http.NewRequestWithContext(ctx, http.MethodGet, upstream+"/delay/100", nil)
			resp, err := client.Do(req) // blocking call: fine in Go
			if err != nil {
				return err // cancellation arrives as ctx.Err(), not as an exception
			}
			defer resp.Body.Close()
			results[i], err = io.ReadAll(resp.Body)
			return err
		})
	}
	if err := g.Wait(); err != nil { // like leaving `async with TaskGroup()`
		return nil, err
	}
	out := make(map[string]json.RawMessage, len(sections))
	for i, s := range sections {
		out[s] = results[i]
	}
	return out, nil
}
ConcernPython asyncioGo
Unit of concurrencyTask (coroutine on one loop)goroutine (runtime-scheduled, many threads)
goroutines vs tasks: blocking callblocks every task on the loopblocks only that goroutine
CPU parallelismnone on the loop; processesyes, GOMAXPROCS
Function colouringasync def must be awaitednone
channels vs Queueasyncio.Queue(maxsize)make(chan T, n)
Fan-out with a limitSemaphore + gather / TaskGrouperrgroup + SetLimit
Cancellationtask.cancel() → CancelledError at next awaitcontext cancel → check ctx.Done() / ctx.Err()
Timeoutasyncio.timeout, wait_forcontext.WithTimeout
Leaked workunreferenced taskgoroutine leak
Per-request valuesContextVarcontext.WithValue (sparingly)
Select over several waitswait(FIRST_COMPLETED)select statement
Race detectionrare (single thread); none built ingo test -race

Common misconceptions ​

BeliefReality
async def makes code fasterIt lets waits overlap; blocking or CPU code inside it is as slow as before and also stalls every other task
asyncio runs coroutines in parallelOne loop is one thread; one coroutine runs at a time
Calling an async def function runs itIt returns a coroutine object; nothing runs until it is awaited or wrapped in a Task
await x() runs x in the backgroundIt runs x now and waits for it; concurrency needs Tasks
One thread means no race conditionsTasks interleave at every await that suspends; read-await-write lost 49 of 50 updates in the snippet
Every await lets other tasks runOnly an await that suspends does; awaiting a finished Future or a coroutine that returns at once does not switch (await asyncio.sleep(0) does)
gather cancels the others on the first errorIt does not; TaskGroup (3.11+) and AnyIO task groups do
create_task and forget is fineThe loop keeps only weak references; errors are lost; nothing cancels it on shutdown
task.cancel() stops the task immediatelyIt requests a CancelledError at the task's next await; CPU loops without await cannot be cancelled
Catching CancelledError and continuing is robustIt breaks TaskGroup, timeout() and shutdown; re-raise after cleanup
except TimeoutError catches wait_for timeouts everywhereOn 3.9/3.10 it raises asyncio.TimeoutError, a different class
wait(timeout=...) cancels unfinished tasksIt returns them in pending; you cancel them
to_thread makes CPU code parallelThe GIL serialises pure-Python bytecode: 0.37 s vs 0.42 s measured; processes took 0.18 s
The default thread pool is unboundedmin(32, cpu_count + 4) (16 here); FastAPI's def routes use AnyIO's 40 tokens instead
A sync client is fine inside async def if the call is quickEvery call holds the loop; 20 calls took 2.07 s under gather
asyncio.Lock protects data shared with threadsasyncio primitives are not thread-safe; use threading.Lock or call_soon_threadsafe
threading.local isolates requestsAll tasks share the loop thread; use ContextVar
An unbounded queue is saferIt turns a slow consumer into unbounded memory and latency; bound it and pick a policy
nest_asyncio is a fixIt is a notebook workaround that patches asyncio internals and does not support uvloop
The GIL is gone in Python 3.13Only in the separate free-threaded build (3.13t experimental, 3.14t supported); the default build keeps it
uvloop changes how I write codeSame asyncio API; it replaces the loop implementation only

Cheat sheet ​

TopicRemember
Runasyncio.run(main()); inside coroutines just await
Concurrentcreate_task, gather, TaskGroup (3.11+), AnyIO task group
Keep tasksstore every Task (set + done-callback, TaskGroup); drain on shutdown
gatherinput order; first error propagates, siblings keep running; return_exceptions=True collects
Race / streamwait(FIRST_COMPLETED) + cancel pending; as_completed
Canceltask.cancel() → CancelledError at next await; cleanup in finally; re-raise
Shieldawait shield(task) and keep task referenced
Timeoutswait_for(aw, t); async with asyncio.timeout(t) (3.11+); AnyIO fail_after/move_on_after; catch asyncio.TimeoutError on ≤ 3.10
LimitSemaphore(n) around each call; bounded Queue(maxsize) for pipelines
Blocking I/Oawait asyncio.to_thread(f, ...); FastAPI: def route or run_in_threadpool
Pool sizesdefault executor min(32, cpu + 4); AnyIO 40 tokens; httpx 100 connections / 20 keep-alive
CPUProcessPoolExecutor via run_in_executor; created once
Per-request stateContextVar; set → Token → reset in finally
DebugPYTHONASYNCIODEBUG=1 or asyncio.run(main(), debug=True); slow callback ≥ 100 ms logged
HTTPone httpx.AsyncClient per process, explicit Limits and Timeout
LoopUvicorn --loop auto = uvloop if installed; Windows: proactor
Tests@pytest.mark.asyncio (strict) or @pytest.mark.anyio; not both in auto mode
GILthreads for I/O, processes for CPU; free-threaded build is opt-in

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — What is the difference between concurrency and parallelism, and which one does asyncio give you? Must-know ​

Answer

Answer: Concurrency means several tasks are in progress and their steps interleave; parallelism means several execute at the same instant on different cores. asyncio gives concurrency on one thread: while one coroutine waits on I/O, another runs. CPU parallelism in default CPython needs processes (or C code that releases the GIL, or the free-threaded build). See Concurrency vs parallelism.

2 — An async def route calls requests.get (or httpx.Client.get). What happens to the other requests, and how do you fix it? Must-know ​

Answer

Answer: The call blocks the event loop thread for its whole duration, so every other request handled by that worker waits, even a trivial /health (measured: 0.554 s during a 0.574 s dashboard call). Fix it with an async client (httpx.AsyncClient opened once in the lifespan), or make the route def so FastAPI runs it in the AnyIO thread pool, or wrap the call in asyncio.to_thread. See Before / After.

3 — What does asyncio.create_task() do, and why must you keep its return value? Must-know ​

Answer

Answer: It wraps the coroutine in a Task and schedules it; the task starts at the creator's next await. The event loop keeps only weak references to tasks, so an unreferenced task can be garbage collected before it finishes, its exception is never seen ("Task exception was never retrieved") and nothing cancels it at shutdown. Keep tasks in a set with a done-callback, or use a TaskGroup. See Tasks.

4 — gather(a(), b()): a fails after 10 ms. What happens to b? How do return_exceptions=True and TaskGroup change that? Must-know ​

Answer

Answer: The exception from a propagates to the awaiting task immediately, and b keeps running (gather does not cancel it). With return_exceptions=True, nothing is raised and the result list contains the exception object in a's position. A TaskGroup (3.11+) cancels b, waits for it to finish cancelling and raises an ExceptionGroup. See gather and TaskGroup.

5 — How does cancellation work in asyncio, and what is wrong with except asyncio.CancelledError: pass? Must-know ​

Answer

Answer: task.cancel() only requests cancellation; CancelledError is raised inside the task at its next await, the stack unwinds through finally and async with, and the task becomes cancelled if the error propagates. Swallowing it makes the task finish "successfully", which breaks TaskGroup, asyncio.timeout() and graceful shutdown, all of which rely on cancellation. Clean up, then re-raise. See Cancellation.

6 — How do you put a timeout on one call and on a whole block, on Python 3.9 and on 3.12? Important ​

Answer

Answer: One call: await asyncio.wait_for(aw, timeout) on any version (it cancels the awaitable). A block: async with asyncio.timeout(t) on 3.11+, or AnyIO fail_after/move_on_after on older versions. On 3.9/3.10 catch asyncio.TimeoutError, which is not the builtin TimeoutError there; since 3.11 they are the same class. Add client-level timeouts (httpx.Timeout) as well. See Timeouts.

7 — Why can a coroutine-only program still have a race condition, and how do you fix it? Important ​

Answer

Answer: Tasks switch wherever an await actually suspends (an await on something already finished does not switch). If a task reads shared state, awaits something that suspends (a DB call, even sleep(0)), then writes, other tasks can read the same old value in between; the snippet lost 49 of 50 increments that way. Hold an asyncio.Lock across the read-await-write, or avoid the await between read and write (or do the update atomically in the database). See Synchronisation primitives.

8 — What is back-pressure and how does asyncio.Queue(maxsize=...) provide it? Important ​

Answer

Answer: Back-pressure is a slow consumer slowing down the producer instead of letting work pile up. With a bounded queue, await queue.put() waits while the queue is full, so the producer moves at the consumers' pace (measured: queue never above 5, producer waited 0.088 s). For producers that cannot wait, use put_nowait and reject (QueueFull → 429/503) or drop. See Queues.

9 — When do you use asyncio.to_thread, when a ProcessPoolExecutor, and how big is the default thread pool? Important ​

Answer

Answer: to_thread for blocking I/O that has no async version (sync SDKs, sqlite3, file reads): the loop stays free while a worker thread waits. A process pool for pure-Python CPU work, because threads share the GIL (measured: threads 0.37 s vs inline 0.42 s, processes 0.18 s). The default executor has min(32, os.cpu_count() + 4) workers (16 on 12 CPUs; process_cpu_count since 3.13); FastAPI's def routes use AnyIO's separate 40-token limiter. See Running blocking code.

10 — How do you test async code with pytest, and why does this project use strict mode? Important ​

Answer

Answer: With a plugin: pytest-asyncio (@pytest.mark.asyncio) or AnyIO's built-in plugin (@pytest.mark.anyio with an anyio_backend fixture); pytest alone fails async tests ("async def functions are not natively supported"). pytest-asyncio's auto mode conflicts with AnyIO's auto mode, so the project uses strict mode and marks each test, which lets both plugins run in one suite. FastAPI apps can be tested on the test's loop via httpx.ASGITransport (enter the lifespan yourself). See Testing async code.

11 — What does contextvars solve that threading.local cannot? Good to know ​

Answer

Answer: All tasks on a loop run in one thread, so a thread-local value set by one request is visible to every other request on that worker. A ContextVar is per task: each Task runs in a copy of its creator's context, values survive awaits, to_thread copies the context into the worker thread, and changes in a child task do not leak to the parent. Use it for request ids, tenants and tracing spans. See contextvars.

12 — What do the GIL and the free-threaded build change for asyncio code? Good to know ​

Answer

Answer: For code running on the event loop, nothing: it is one thread either way, and the GIL is released during I/O. The GIL matters for the thread pool: in the default build, CPU-bound work in threads does not run in parallel. The free-threaded build (3.13 experimental, 3.14 officially supported but optional) removes the GIL so threads can use several cores, at a single-thread cost of about 1–8% according to the HOWTO, and some C extensions re-enable the GIL. See The GIL.

Glossary ​

TermMeaning
Concurrency vs parallelismInterleaved progress of several tasks vs simultaneous execution on several cores
GILGlobal interpreter lock: one thread executes Python bytecode at a time in default CPython
Free-threaded PythonCPython build without the GIL (--disable-gil, python3.13t/3.14t; PEP 703, PEP 779)
PYTHON_GILEnvironment variable that re-enables the GIL in a free-threaded build
I/O-boundWork dominated by waiting for network, disk or databases
CPU-boundWork dominated by computation
Blocking callA call that holds the thread until done (time.sleep, requests, sync drivers)
Non-blocking I/OSockets in non-blocking mode plus readiness notification from a selector
Event loopasyncio's scheduler: timers, ready callbacks, selector; runs all tasks on one thread
SelectorOS readiness API wrapper (selectors: epoll, kqueue, poll, select)
ProactorCompletion-based loop on Windows (IOCP); default there since 3.8
uvloopDrop-in asyncio loop on libuv, written in Cython; Uvicorn's default when installed
Callback / handleA function scheduled with call_soon / call_later; what the loop actually runs
Coroutine functionA function defined with async def
CoroutineThe object a coroutine function returns; runs when awaited or wrapped in a Task
async defDefines a coroutine function (PEP 492, Python 3.5)
awaitSuspends the current coroutine until an awaitable completes
AwaitableCoroutine, Task, Future, or any object with __await__
FutureLow-level result placeholder with callbacks (asyncio.Future)
TaskA Future that drives a coroutine on the loop (asyncio.Task)
create_taskSchedule a coroutine as a Task and return it
Fire and forgetStarting a task without awaiting it; safe only with a kept reference and error handling
Task referenceA strong reference you keep to a Task; the loop holds only weak ones
Eager task factory3.12+ option that runs a new task synchronously until its first suspension
gatherRun awaitables concurrently, results in input order
return_exceptionsgather flag: return exceptions as values instead of raising the first
TaskGroup3.11+ async context manager that owns tasks, cancels siblings on failure, raises ExceptionGroup
ExceptionGroup / except*Several exceptions raised together and handled by type (PEP 654, 3.11)
as_completedIterate over awaitables in completion order
waitWait for a set until FIRST_COMPLETED, FIRST_EXCEPTION or ALL_COMPLETED; returns (done, pending)
FIRST_COMPLETEDwait returns as soon as any future finishes or is cancelled
CancellationRequesting a task to stop; delivered as CancelledError at its next await
CancelledErrorThe exception used for cancellation; a BaseException since 3.8
shieldProtect an inner awaitable from the outer task's cancellation
TimeoutA deadline after which work is cancelled and TimeoutError raised
wait_forTimeout on one awaitable; cancels it on expiry
asyncio.timeout3.11+ async context manager putting a deadline on a block
Structured concurrencyEvery task has a parent scope that waits for it and cancels it on failure
AnyIOLibrary with structured concurrency over asyncio and Trio; the base of Starlette and FastAPI
Cancel scopeAnyIO/Trio context manager that can be cancelled, nested, shielded or given a deadline
Level vs edge cancellationAnyIO re-delivers cancellation at every yield inside a cancelled scope; asyncio delivers it once
Lockasyncio mutex for tasks (not threads)
SemaphoreLets at most n tasks into a block; the standard concurrency limit
EventFlag that releases all waiters when set
ConditionLock plus a wait queue for predicates over shared state
Queueasyncio FIFO with optional maxsize; put/get/task_done/join
Producer consumerPattern where producer tasks feed a queue and consumer tasks drain it
Back-pressureA slow consumer slowing the producer (bounded queue, rejected requests)
to_thread3.9+ helper running a function in the default executor with the current context
run_in_executorRun a function in a given executor (or the default one) and await its Future
ThreadPoolExecutorconcurrent.futures thread pool; default executor of the loop
ProcessPoolExecutorconcurrent.futures process pool for CPU-bound work
Default executor sizemin(32, os.cpu_count() + 4) (3.8–3.12); process_cpu_count from 3.13
multiprocessingStandard library module for processes, pools, queues and shared memory
Async generatorasync def with yield; consumed with async for (PEP 525)
async forLoop whose next-item step can await (__aiter__/__anext__)
async withContext manager whose enter/exit can await (__aenter__/__aexit__)
Async context managerObject implementing __aenter__/__aexit__, or built with @asynccontextmanager
contextvars / ContextVarPer-task context variables (PEP 567, 3.7)
asyncio.runCreate a loop, run a coroutine, clean up tasks, generators and the default executor
loop.run_until_completeLow-level: run the loop until one Future is done
nest_asyncioThird-party patch allowing nested asyncio.run; notebook workaround
PYTHONASYNCIODEBUGEnvironment variable enabling asyncio debug mode
Debug modeasyncio mode that logs slow callbacks, never-awaited coroutine origins, wrong-thread calls
Slow callback durationloop.slow_callback_duration, default 0.1 s; threshold for the debug-mode warning
"coroutine was never awaited"RuntimeWarning when a coroutine object is collected without having run
httpx AsyncClientAsync HTTP client with a connection pool; one per process
Connection limitshttpx.Limits: max_connections 100, max_keepalive_connections 20, keepalive_expiry 5 s by default
Uvicorn loopUvicorn's --loop option (auto, asyncio, uvloop); one loop per worker
FastAPI threadpool for def routesdef path operations run via anyio.to_thread.run_sync (40 tokens)
Starlette run_in_threadpoolawait anyio.to_thread.run_sync(func); offload one call from async def
pytest-asynciopytest plugin running @pytest.mark.asyncio tests; strict and auto modes
AnyIO pytest pluginBuilt into AnyIO; @pytest.mark.anyio and the anyio_backend fixture
Graceful shutdownStop new work, drain, cancel and await remaining tasks, close clients
GoroutineGo's runtime-scheduled lightweight thread; may block freely
ChannelGo's typed pipe between goroutines; the counterpart of asyncio.Queue
PHP FibersPHP 8.1 full-stack suspendable functions
PHP Swoole / Open SwoolePHP extensions with an event loop, coroutines, servers and clients
Laravel OctaneLaravel package serving the app from long-lived workers (FrankenPHP, Swoole, Open Swoole, RoadRunner)
ReactPHPEvent-loop library for PHP
SQLAlchemy / SQLModel / AlembicORM (with an asyncio extension), Pydantic-flavoured ORM layer and migration tool
Uvicorn / Starlette / FastAPIASGI server, ASGI toolkit (built on AnyIO), API framework

References ​

Built by Morteza Negahi