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 for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why one thread can serve 10,000 connections | Why it exists |
Generators, Tulip, async/await, TaskGroup, free threading | Where it comes from |
| A dashboard endpoint before and after, with timings | Python |
| Concurrency is not parallelism | Concurrency vs parallelism |
GIL, python3.13t, PYTHON_GIL | The GIL and free-threaded Python |
| Which calls block | I/O-bound, CPU-bound, blocking calls |
selectors, epoll, kqueue, uvloop | The event loop |
async def, await, coroutine, awaitable, Future | Coroutines 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, shield | Cancellation |
wait_for, asyncio.timeout, TimeoutError | Timeouts |
AnyIO task groups, move_on_after, cancel scopes | Structured concurrency and AnyIO |
Lock, Semaphore, Event, Condition | Synchronisation primitives |
asyncio.Queue, maxsize, task_done, join | Queues, producer/consumer, back-pressure |
to_thread, run_in_executor, default executor size | Running blocking code |
ProcessPoolExecutor, multiprocessing | CPU-bound work |
async for, async with, @asynccontextmanager | Async generators and context managers |
| Request id in every log line | contextvars |
asyncio.run, run_until_complete, nest_asyncio | Entry points and nested loops |
PYTHONASYNCIODEBUG, slow callbacks, "never awaited" | Debugging |
httpx.AsyncClient, Limits, timeouts | Async HTTP clients |
Uvicorn's loop, def routes, run_in_threadpool | How FastAPI, Starlette and Uvicorn use the loop |
@pytest.mark.asyncio, @pytest.mark.anyio | Testing async code |
| Stopping tasks on SIGTERM | Graceful shutdown |
| Async database access, sync drivers | Databases from async code |
| How a Task drives a coroutine, exact error texts, version matrix | Mechanics |
| The classic bugs and their fixes | Solving the classic problems |
| asyncio vs threads vs processes vs Go | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce every number on your machine | Lab |
| Swoole, Octane, ReactPHP, Fibers | For PHP/Laravel developers |
| Goroutines vs tasks, channels vs Queue | The Go angle |
Everything in one minute
The vocabulary in one table. Each row is unpacked in the concept catalogue.
| Term | What it is | Plain words | Python API |
|---|---|---|---|
| Coroutine function | A function defined with async def | "A recipe that can pause" | async def fetch(): ... |
| Coroutine | What calling it returns; runs only when awaited or wrapped in a Task | "The paused recipe, not started" | fetch() |
await | Suspend this coroutine until the awaitable is done | "Wait here, let others run" | await fetch() |
| Awaitable | Anything await accepts: coroutine, Task, Future, objects with __await__ | "Something you can wait on" | inspect.isawaitable |
| Future | Low-level placeholder for a result set later | "An empty box someone will fill" | loop.create_future() |
| Task | A Future that drives a coroutine on the loop | "A recipe the kitchen is cooking" | asyncio.create_task(coro) |
| Event loop | The scheduler: timers, ready callbacks, selector | "The single waiter" | asyncio.get_running_loop() |
| Selector | OS readiness API used by SelectorEventLoop: epoll, kqueue, poll, select | "Which tables raised a hand?" | selectors.DefaultSelector |
| Proactor | Completion-based loop on Windows (IOCP): the OS reports finished operations, not ready sockets | "Tell me when the dish is done" | asyncio.ProactorEventLoop |
| Blocking call | A call that holds the thread until it returns | "The waiter stuck at one table" | time.sleep, requests.get |
| Thread pool | Worker threads for blocking calls | "Kitchen helpers" | asyncio.to_thread, run_in_executor |
| Process pool | Worker processes for CPU work | "Another kitchen" | ProcessPoolExecutor |
| GIL | One 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).
| Work | Example | Right tool | What goes wrong otherwise | Measured |
|---|---|---|---|---|
| Network I/O with an async library | httpx.AsyncClient, asyncpg, redis.asyncio | await + gather/TaskGroup | nothing; this is the sweet spot | 20 × 100 ms in 0.14 s |
| Network I/O with a sync library | requests, httpx.Client, boto3, sync DB driver | asyncio.to_thread or a def route | inside async def: serial and blocks the loop | 2.07 s, /health waited 0.55 s |
| A sleep or backoff | retry delay | await asyncio.sleep | time.sleep freezes every task | heartbeat gap 0.211 s vs 0.013 s |
File I/O, sqlite3 | read a report, local DB | to_thread | blocks the loop | (see Running blocking code) |
| Pure-Python CPU | parsing, pricing, image work in Python | ProcessPoolExecutor | threads give no speed-up (GIL) | 4 jobs: inline 0.42 s, threads 0.37 s, processes 0.18 s |
| C extension that releases the GIL | hashlib, zlib, NumPy | thread pool | nothing; threads run in parallel | not measured |
| Too many concurrent calls | 10,000 URLs | Semaphore or bounded Queue | sockets, memory, upstream overload | Semaphore(5): 0.44 s in 4 waves |
Combinators. What each one returns and who cancels what.
| API | Returns | On first error | On timeout | Cancels the others? | Since |
|---|---|---|---|---|---|
await gather(*aws) | list, input order | raises it; the rest keep running | n/a | no (only if gather itself is cancelled) | 3.4 |
gather(*aws, return_exceptions=True) | list with exceptions as values | nothing raised | n/a | no | 3.4 |
async with TaskGroup() | (tasks hold results) | cancels siblings, raises ExceptionGroup | combine with timeout() | yes | 3.11 |
as_completed(aws) | iterator in completion order | raised when you await that item | TimeoutError | no | 3.4 (async iteration 3.13) |
wait(aws, return_when=...) | (done, pending) sets | FIRST_EXCEPTION returns early | returns, no error | no | 3.4 |
wait_for(aw, t) | the result | raises it | TimeoutError, inner cancelled | yes, the inner awaitable | 3.4 |
async with timeout(t) | (block) | raises it | TimeoutError, block cancelled | yes, the current task's work | 3.11 |
shield(aw) | the result | raises it | n/a | protects the inner from outer cancel | 3.4 |
What prints when something is wrong. Real output from the snippet run.
| Mistake | What you see | Where |
|---|---|---|
Called a coroutine function without await | RuntimeWarning: coroutine 'forgotten' was never awaited | stderr, always |
| Task failed, nobody read the result | Task exception was never retrieved | logger asyncio, at garbage collection |
| Loop closed with a task still pending | Task was destroyed but it is pending! | logger asyncio |
| A callback held the loop > 100 ms | Executing <Task pending name='Task-1' ...> took 0.213 seconds | logger asyncio, debug mode only |
asyncio.run() inside a running loop | RuntimeError: asyncio.run() cannot be called from a running event loop | exception |
asyncio.TaskGroup on 3.9/3.10 | AttributeError: 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 thread | A blocking call blocks every task on the loop |
| Memory per waiting request: a thread stack | Memory per waiting request: a coroutine frame and a Task |
| Shared state needs locks everywhere | Shared state is safe between two awaits; locks only around awaits |
| Any library works | Libraries 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 allows | CPU 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
- "
async defmakes 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 insideasync defcoroutines undergather()took 2.07 s too, because nothing awaited. - "Calling a coroutine function starts it." It builds a coroutine object and nothing else. Without
await(orcreate_task) it never runs, and Python printscoroutine '...' was never awaitedwhen the object is garbage collected. - "
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 exitPython
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.
"""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 appAfter
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.
"""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 appThe tracked-task helper used by after.py (strong references, error collection, drain with timeout) lives with the task examples:
"""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.
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:
"""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")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 callsThe project file pins the stack; asyncio_mode = "strict" lets pytest-asyncio and the AnyIO plugin share the suite:
[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"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 baseThe 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
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 usedReal 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).
| Model | Python API | Switches when | Parallel CPU? | Memory per job | Typical use |
|---|---|---|---|---|---|
| Cooperative tasks | asyncio, AnyIO, Trio | at await | no | KBs (frame + Task) | many network waits |
| Preemptive threads | threading, ThreadPoolExecutor | any bytecode boundary / I/O | only where the GIL is released (or free-threaded build) | a thread stack | blocking libraries |
| Processes | multiprocessing, ProcessPoolExecutor | OS scheduler | yes | a whole interpreter | CPU-bound work |
| Free-threaded threads | python3.13t / 3.14t | OS scheduler | yes | a thread stack | CPU work in threads, if extensions support it |
| Go goroutines | runtime | blocking points, preemption | yes (GOMAXPROCS) | ~KBs, growable | both |
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 / version | GIL | How to check | Status |
|---|---|---|---|
| CPython 3.12 and earlier (default) | always on | n/a | the standard build |
| CPython 3.13 default build | on | sys._is_gil_enabled() → True | standard |
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.14t | off | same | "officially supported but still optional" (PEP 779, phase II) |
| PyPy | has a GIL | n/a | alternative 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.
| Call | Blocks the loop? | Async alternative | Or offload with |
|---|---|---|---|
time.sleep(s) | yes | await asyncio.sleep(s) | n/a |
requests.get, httpx.Client.get, urllib.request | yes | await httpx.AsyncClient().get / aiohttp | to_thread |
psycopg2, pymysql, sqlite3 | yes | asyncpg, psycopg 3 async, aiomysql, aiosqlite, SQLAlchemy AsyncSession | to_thread / def route |
redis.Redis | yes | redis.asyncio.Redis | to_thread |
open().read(), pathlib.read_text | yes (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.run | yes | asyncio.create_subprocess_exec | to_thread |
| boto3 | yes | aiobotocore (README: an async client for AWS services built on botocore and aiohttp/asyncio) / aioboto3 | to_thread |
json.loads of 50 MB, Pydantic on huge payloads | yes (CPU) | n/a | ProcessPoolExecutor 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 1Real 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).
| Loop | Platform | Backend | How you get it | Notes |
|---|---|---|---|---|
SelectorEventLoop | Unix default; Windows optional | selectors.DefaultSelector (epoll / kqueue / poll / select) | asyncio.run | real on macOS: _UnixSelectorEventLoop |
ProactorEventLoop | Windows default since 3.8 | IOCP | asyncio.run on Windows | subprocess and pipes supported |
uvloop Loop | Linux, macOS (no Windows) | libuv, Cython | uvloop.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 auto | any | uvloop if importable, else asyncio | uvicorn[standard] installs uvloop | Uvicorn docs: "not compatible with Windows or PyPy" |
| Trio / AnyIO trio backend | any | Trio's own loop | anyio.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.
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 upReal 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.
| Kind | Created by | Runs when | Awaitable twice? | Cancel |
|---|---|---|---|---|
| Coroutine | calling an async def | when awaited or wrapped in a Task | no (RuntimeError: cannot reuse already awaited coroutine) | close() |
| Task | create_task, ensure_future, gather, TaskGroup.create_task | scheduled at once; starts at the creator's next await | yes (returns the same result) | task.cancel() |
| Future | loop.create_future(), run_in_executor | when someone sets its result | yes | fut.cancel() |
concurrent.futures.Future | thread/process pools | in a worker | no (wrap: asyncio.wrap_future) | cancel() before it starts |
| Async generator | async def with yield | per async for step | n/a | aclose() |
Fix / how to use it:
"""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())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.
| Pattern | Keeps reference | Sees errors | Cancelled on shutdown | Verdict |
|---|---|---|---|---|
asyncio.create_task(x()) and drop it | no | no | no | bug |
tasks.add(t); t.add_done_callback(tasks.discard) (docs pattern) | yes | only if you read them | if you cancel the set | minimal |
BackgroundTasks class in the snippet (set + done-callback that logs each failure with its traceback + drain(timeout)) | yes | yes, logged by the owner and counted in /health | yes, after a grace period | good default; retrieving the exception silences asyncio's own report, so the owner must log it |
async with TaskGroup() / AnyIO task group | yes | yes (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 BackgroundTasks | yes (runs after the response, same request) | logged | runs to completion | small post-response work (chapter) |
| A job queue (Celery, arq, RQ, Dramatiq) | durable | yes, with retries | survives restarts | anything 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 orderReal 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.
| Need | Use | Why |
|---|---|---|
| All results, fail fast, siblings may keep running | gather() | simple; know that siblings are not cancelled |
| All results, partial failure allowed | gather(..., return_exceptions=True) | inspect each item with isinstance(r, Exception) |
| Fail fast AND cancel siblings | TaskGroup (3.11+) or AnyIO task group | structured concurrency |
| Results as they arrive | as_completed | stream partial results |
| A bound on concurrency | Semaphore around each call, or a worker Queue | protects the upstream and your pool |
| Very large fan-out | worker pool over a Queue | constant 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.
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 propagatingReal 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 error | keep running | keep running | cancelled | cancelled |
| What you get | first exception | list with exceptions | ExceptionGroup | ExceptionGroup (backport on ≤ 3.10) |
| Can a child outlive the block? | yes (if not awaited) | yes | no | no |
| Add tasks later | no | no | yes (tg.create_task while open) | yes (tg.start_soon) |
| Python versions | all | all | 3.11+ | 3.9+ (AnyIO 4.12.1 on 3.9) |
| Results | return value | return value | task.result() after the block | via 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 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.
| Want | Call | Then |
|---|---|---|
| Fastest of N, cancel the rest | wait(..., return_when=FIRST_COMPLETED) | cancel pending, await them |
| Each result as it arrives | for aw in as_completed(aws): r = await aw (3.13+: async for) | cancel the rest on early exit |
| Stop on first error, inspect the rest | wait(..., return_when=FIRST_EXCEPTION) | done has the failed task |
| Deadline without cancelling | wait(..., timeout=t) | decide what to do with pending |
| Deadline with cancelling | wait_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.
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.
| Situation | What happens | Right code |
|---|---|---|
| Need cleanup on cancel | CancelledError unwinds the stack | try/finally or async with |
| Need to log the cancel | catch, log, re-raise | except CancelledError: log(); raise |
| Want the task to "survive" a cancel | swallowing breaks TaskGroup/timeout | do not; use shield for an inner operation |
| Critical inner operation | caller cancelled, inner continues | await asyncio.shield(task) + keep task |
| CPU loop with no await | cancel cannot interrupt | await asyncio.sleep(0) every N iterations, or move to a process |
except Exception: around an await | does not catch CancelledError (3.8+) | correct as is |
except BaseException: / bare except: | catches it | re-raise |
Fix / how to use it:
"""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)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: ...).
| API | Scope | On timeout | Version | Note |
|---|---|---|---|---|
asyncio.wait_for(aw, t) | one awaitable | cancels it, TimeoutError | all (alias of builtin since 3.11) | wraps a coroutine in a Task before 3.12 |
async with asyncio.timeout(t) | a block | cancels the block, TimeoutError | 3.11+ | reschedule(), timeout_at() |
asyncio.wait(aws, timeout=t) | a set | returns (done, pending), nothing cancelled | all | no exception |
anyio.fail_after(t) | a block (cancel scope) | TimeoutError | AnyIO 3+ | works on 3.9 |
anyio.move_on_after(t) | a block | exits quietly, scope.cancelled_caught | AnyIO 3+ | "best effort" fallbacks |
httpx.Timeout(t, connect=...) | one HTTP request phase | httpx.TimeoutException subclasses | httpx | default "5 seconds of network inactivity" |
Uvicorn --timeout-graceful-shutdown | server shutdown | forces exit | Uvicorn | see 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).
| Concept | asyncio (3.11+) | AnyIO 4 (3.9+) |
|---|---|---|
| Task group | asyncio.TaskGroup, tg.create_task(coro) | anyio.create_task_group(), tg.start_soon(fn, *args) |
| Wait for a child to be ready | manual Event | await tg.start(fn) + task_status.started() |
| Timeout block | asyncio.timeout(t) | fail_after(t) / move_on_after(t) |
| Shield | asyncio.shield(aw) (protects one awaitable) | CancelScope(shield=True) (protects a block) |
| Cancellation semantics | edge | level, inside scopes |
| Cancel exception | asyncio.CancelledError | anyio.get_cancelled_exc_class() (backend's own) |
| Threads | asyncio.to_thread (default executor) | anyio.to_thread.run_sync (CapacityLimiter, 40 tokens) |
| Testing | pytest-asyncio | built-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 -> 50Real 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.
| Primitive | Holds | Typical use | Thread-safe? | Since |
|---|---|---|---|---|
asyncio.Lock | 1 task | critical section that awaits inside | no | 3.4 |
asyncio.Semaphore(n) | n tasks | concurrency limit, connection budget | no | 3.4 |
asyncio.BoundedSemaphore(n) | n, error on extra release | same, catches bugs | no | 3.4 |
asyncio.Event | flag | one-to-many signal | no | 3.4 |
asyncio.Condition | lock + wait queue | wait for a predicate over shared state | no | 3.4 |
asyncio.Barrier(n) | n arrivals | phase synchronisation | no | 3.11 |
threading.Lock | 1 thread | state shared with worker threads | yes | n/a |
anyio.Lock, anyio.Semaphore, CapacityLimiter | as above | backend-neutral code | no | AnyIO |
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 full | How | Use when |
|---|---|---|
| Producer waits (back-pressure) | await q.put(x) | producer can slow down (internal pipeline) |
| Reject the request | q.put_nowait(x) → QueueFull → 503 / 429 | producer is a client that can retry |
| Drop newest / oldest | put_nowait in try, or get_nowait() then put | metrics, telemetry, live prices |
| Disconnect the slow consumer | per-client queue full → close | WebSockets, SSE fan-out |
| Persist instead | Redis Streams, RabbitMQ, Kafka, SQS | must survive restarts (messaging) |
Fix / how to use it:
"""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),
}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' paceRunning 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).
| Call | Pool | Size by default | Context copied? | Use for |
|---|---|---|---|---|
await asyncio.to_thread(f, *a) | loop's default ThreadPoolExecutor | min(32, cpu + 4) | yes | blocking I/O in asyncio code |
await loop.run_in_executor(None, f, *a) | same | same | no (wrap with ctx.run yourself) | pre-3.9 code, keyword args via partial |
await loop.run_in_executor(my_pool, f) | your executor | your choice | no | isolate a slow dependency |
await anyio.to_thread.run_sync(f) | AnyIO worker threads | 40 tokens (CapacityLimiter) | yes | AnyIO / Starlette code |
await starlette.concurrency.run_in_threadpool(f, *a) | AnyIO worker threads | 40 tokens | yes | inside async def routes (real: thread AnyIO worker thread) |
FastAPI def route / sync dependency | AnyIO worker threads | 40 tokens | yes | whole route is sync |
loop.run_in_executor(ProcessPoolExecutor(), f) | processes | os.process_cpu_count() (3.13+) | no (pickled) | CPU-bound work |
Fix / how to use it:
"""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() - startfrom __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 GILsThe 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:
-- 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.
| Option | Parallel CPU | Start cost | Data passing | Good for |
|---|---|---|---|---|
Inline in async def | no, and blocks the loop | none | none | microseconds of work only |
to_thread / thread pool | no (GIL), unless C code releases it | low | shared memory | C extensions that release the GIL |
ProcessPoolExecutor via run_in_executor | yes | high (once per worker) | pickling | CPU jobs of 10 ms to seconds |
multiprocessing.Pool / Process | yes | high | pickling, shared memory, pipes | scripts and batch jobs |
| Job queue workers | yes | n/a (long-lived) | broker messages | anything slow, retried or scheduled |
| Free-threaded 3.14t + threads | yes | low | shared memory | if 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).
| Construct | Protocol | Typical library use |
|---|---|---|
async for x in it | __aiter__ / __anext__ (raises StopAsyncIteration) | DB cursors, message consumers, response.aiter_bytes() |
| Async generator | async 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 |
@asynccontextmanager | async generator with one yield | lifespan, test fixtures, transactions |
contextlib.AsyncExitStack | dynamic set of async CMs | open N clients in a lifespan |
contextlib.aclosing(agen) | closes the generator at block exit | generators holding resources (3.10+) |
Fix / how to use it:
"""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.eventscontextvars 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.
| Mechanism | Per thread | Per task | Copied into to_thread | Copied into run_in_executor |
|---|---|---|---|---|
| Global variable | no | no | n/a | n/a |
threading.local() | yes | no (shared by all tasks on the loop) | no | no |
ContextVar | yes | yes | yes | no (use ctx.run) |
| Explicit parameter | n/a | yes | yes | yes |
Fix / how to use it:
"""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()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).
| Situation | Use |
|---|---|
| Script / CLI entry point | asyncio.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 coroutine | await |
| From another thread to a running loop | asyncio.run_coroutine_threadsafe(coro, loop).result() |
| A loop in a background thread | loop.run_until_complete(...) / run_forever() in that thread |
| Jupyter / IPython | top-level await (the kernel runs a loop); nest_asyncio only as a last resort |
| Sync code that must call async code once | anyio.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.
| Symptom | Likely cause | How to find it |
|---|---|---|
coroutine '...' was never awaited | missing await, or a coroutine passed where a function was expected | debug mode shows "Coroutine created at" |
Task exception was never retrieved | fire-and-forget task failed | keep references; done-callback that logs |
Task was destroyed but it is pending! | loop closed with live tasks; unreferenced task collected | cancel and await tasks on shutdown |
Executing <Task ...> took 0.213 seconds | blocking call or CPU on the loop | the task repr names the coroutine and line |
| All endpoints slow at once | loop blocked | debug 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 one | call_soon from a thread in debug mode | call_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.
"""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 errAsync 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 overlapReal 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.
| Setting | Default | Change when |
|---|---|---|
Limits(max_connections=...) | 100 | upstream allows fewer; or several workers × 100 is too many |
Limits(max_keepalive_connections=...) | 20 | steady high fan-out to one host |
Limits(keepalive_expiry=...) | 5 s | load balancer idle timeout is shorter |
Timeout(5.0) | 5 s each phase | always set explicitly per upstream |
Timeout(pool=...) | 5 s | many tasks wait for a pooled connection |
| One client per process | your job | always: 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 -> returnsReal 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 / call | Runs on | Concurrency limit | Blocks the loop if it blocks? |
|---|---|---|---|
async def route | event loop | none built in (Uvicorn --limit-concurrency) | yes |
def route | AnyIO worker thread | 40 tokens (shared) | no |
async def dependency | event loop | n/a | yes |
def dependency (also with yield) | AnyIO worker thread | 40 tokens | no |
await run_in_threadpool(f) | AnyIO worker thread | 40 tokens | no |
await asyncio.to_thread(f) | asyncio default executor | min(32, cpu + 4) | no |
BackgroundTasks.add_task(def_fn) | AnyIO worker thread after the response | 40 tokens | no |
StreamingResponse(sync_iterator) | iterate_in_threadpool | 40 tokens | no |
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 testsReal 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.
| Tool | Marker / config | Loop scope | Notes |
|---|---|---|---|
| pytest-asyncio (strict) | @pytest.mark.asyncio | function default; loop_scope= | default mode |
| pytest-asyncio (auto) | asyncio_mode = "auto" | same | conflicts with AnyIO auto mode |
| AnyIO plugin | @pytest.mark.anyio, anyio_backend fixture | per test | asyncio and Trio; used by FastAPI docs |
TestClient (Starlette) | sync tests | its own loop in a thread (portal) | runs lifespan in with |
httpx.ASGITransport | async tests | the test's loop | no lifespan; enter it yourself |
unittest.IsolatedAsyncioTestCase | stdlib | per test | no 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.
| Step | Owner | Bound |
|---|---|---|
| Stop accepting new work | Uvicorn / your consumer loop (Event) | immediate |
| Finish in-flight requests | Uvicorn | --timeout-graceful-shutdown |
| Drain background tasks | your lifespan | a few seconds |
| Cancel the rest and await them | your lifespan | until finally blocks finish |
| Close clients and pools | async with in the lifespan | immediate |
| Hard kill | the 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 startReal 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.
| Stack | Route style | Blocks the loop? | Where it is taught |
|---|---|---|---|
SQLAlchemy Session + psycopg2 / sqlite3 | def | no (thread pool) | SQLAlchemy 2 & SQLModel |
SQLAlchemy Session in async def | async def | yes (bug) | this page |
AsyncSession + asyncpg / aiosqlite | async def | no | SQLAlchemy 2 & SQLModel |
| asyncpg directly | async def | no | asyncpg docs |
| Motor / Beanie (MongoDB) | async def | no | MongoDB with FastAPI |
redis.asyncio | async def | no | Background 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| Event | Who acts | API underneath |
|---|---|---|
create_task(coro) | loop | loop.call_soon(task.__step) |
await asyncio.sleep(d) | loop timer heap | loop.call_later(d, futures._set_result_unless_cancelled, future, result) |
await reader.read() | selector | loop.add_reader(fd, callback) |
await to_thread(f) | executor thread | loop.run_in_executor + call_soon_threadsafe |
task.cancel() | task | sets a flag; next step throws CancelledError |
| Task finishes | Future callbacks | awaiting 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).
| Trigger | Output |
|---|---|
| Coroutine never awaited | RuntimeWarning: coroutine 'forgotten' was never awaited + RuntimeWarning: Enable tracemalloc to get the object allocation traceback |
| Same in debug mode | adds Coroutine created at (most recent call last) with the stack |
| Failed task never awaited | Task exception was never retrieved / future: <Task finished name='Task-2' coro=<main.<locals>.boom() done, ...> exception=ValueError('lost')> |
| Loop closed with a pending task | Task was destroyed but it is pending! / task: <Task pending name='Task-6' coro=<forever() done, ...> wait_for=<Future pending ...>> |
| Slow callback, debug mode | Executing <Task pending name='Task-1' coro=<main() running at <string>:13> ...> took 0.213 seconds |
asyncio.run in a running loop | RuntimeError: asyncio.run() cannot be called from a running event loop |
| Awaiting a coroutine twice | RuntimeError: cannot reuse already awaited coroutine |
asyncio.TaskGroup on 3.9 | AttributeError: module 'asyncio' has no attribute 'TaskGroup' |
Bare coroutine to wait() on 3.9 | DeprecationWarning: 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 queue | asyncio.QueueFull |
asyncio.TimeoutError is TimeoutError on 3.9 | False (alias since 3.11) |
CancelledError base class on 3.9 | BaseException |
| Default loop on macOS | _UnixSelectorEventLoop, slow_callback_duration: 0.1 |
Uvicorn --loop auto / asyncio / uvloop | uvloop.Loop / asyncio.unix_events._UnixSelectorEventLoop / uvloop.Loop, AnyIO tokens=40 each |
def route / run_in_threadpool thread name | AnyIO worker thread |
| Default executor on 12 CPUs | max_workers=16 |
| Unmarked async test, no plugin (pytest 8.4.2) | async def functions are not natively supported. |
| AnyIO group with a failing child | ExceptionGroup (from the exceptiongroup backport on 3.9) with the child's ValueError |
Version matrix: what you can use where Important
| Feature | 3.9 | 3.10 | 3.11 | 3.12 | 3.13 | 3.14 | 3.15 |
|---|---|---|---|---|---|---|---|
asyncio.run, create_task, gather, wait_for, Queue | yes | yes | yes | yes | yes | yes | yes |
asyncio.to_thread | yes (new) | yes | yes | yes | yes | yes | yes |
loop= parameter on high-level APIs | deprecated | removed | removed | removed | removed | removed | removed |
TaskGroup, timeout(), Runner, Barrier, except* | no | no | yes | yes | yes | yes | yes (+ tg.cancel()) |
asyncio.TimeoutError is TimeoutError | no | no | yes | yes | yes | yes | yes |
Bare coroutines in wait() | warning | warning | error | error | error | error | error |
Eager task factory, run(loop_factory=) | no | no | no | yes | yes | yes | yes |
Queue.shutdown, async for over as_completed | no | no | no | no | yes | yes | yes |
| Free-threaded build | no | no | no | no | experimental | supported (optional) | supported (optional) |
python -m asyncio ps / pstree | no | no | no | no | no | yes | yes |
| Policy system | yes | yes | yes | yes | yes | deprecated (removal 3.16) | deprecated (removal 3.16) |
Default ThreadPoolExecutor size | min(32, cpu_count + 4) | same | same | same | process_cpu_count + 4 (cap 32) | same | same |
Solving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
| Sync HTTP client in async route | every endpoint slow during upstream latency; measured /health 0.554 s | httpx.AsyncClient from the lifespan, or a def route | small |
| time.sleep blocks the loop (in a coroutine) | heartbeat gap 0.211 s | await asyncio.sleep | none |
Sync DB driver in async def | throughput of one request at a time | async driver, or def route + pool | medium |
Unbounded gather over a big list | sockets exhausted, upstream 429s, pool timeouts | Semaphore, or worker pool over a bounded Queue | small |
Fire-and-forget create_task | lost work, Task exception was never retrieved | tracked set / TaskGroup; queue for durable work | small |
Swallowed CancelledError | shutdown hangs, timeouts do not fire | re-raise after cleanup | none |
| No timeout on outbound calls | requests pile up during an outage | client Timeout + wait_for / timeout() | none |
| gather fails fast, siblings keep running | wasted work, side effects after an error | TaskGroup / AnyIO task group | small |
| CPU work on the loop | latency spikes, debug "took 0.4 seconds" | ProcessPoolExecutor or a job queue | medium |
| Thread-local request state | wrong request id in logs | ContextVar | small |
| Lock-free read-await-write | lost updates (50 → 1 measured) | asyncio.Lock, or atomic SQL | small |
| Client per request | new TLS handshake per call, no global limit | one client per process | small |
| Primitives created at import | "attached to a different loop" in tests | create in lifespan / fixtures | small |
| Tasks alive at shutdown | Task was destroyed but it is pending! | drain + cancel + await in the lifespan | small |
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
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Many concurrent network calls with async libraries | asyncio tasks | Semaphore + timeouts | cheapest concurrency per wait |
| Need all results, fail fast, cancel the rest | TaskGroup (3.11+) / AnyIO task group | asyncio.timeout around it | structured concurrency |
| Partial failure acceptable | gather(return_exceptions=True) | log each failure | one bad source must not fail the page |
| First answer wins | wait(FIRST_COMPLETED) | cancel the losers | hedged requests |
| Stream results as they come | as_completed | cancel on early exit | lower time-to-first-result |
| Library only exists in sync form | to_thread / def route | dedicated executor for slow deps | keeps the loop free |
| CPU work 10 ms – seconds | ProcessPoolExecutor via run_in_executor | Semaphore on submissions | uses cores, keeps the loop free |
| CPU work longer, or must survive restarts | job queue (Celery, arq, RQ, Dramatiq) | idempotent jobs | durability, retries |
| Producer faster than consumer | bounded Queue | reject or drop policy | back-pressure |
| Per-request state through the call stack | ContextVar | reset in finally | correct under concurrency |
| Code must run on asyncio and Trio, or on 3.9/3.10 with structured concurrency | AnyIO | @pytest.mark.anyio | one API, cancel scopes |
| Sync program needs one async call | asyncio.run | n/a | simplest bridge |
| Notebook | top-level await | nest_asyncio only if forced | loop already running |
When asyncio vs threads vs processes vs Go
| Need | asyncio | Threads (default CPython) | Processes | Go |
|---|---|---|---|---|
| 10,000 idle connections (WebSockets, SSE) | best | expensive | very expensive | best |
| Fan-out to 20 HTTP calls | 0.136 s measured | 0.133 s measured | overkill | goroutines |
| Library ecosystem | must be async | any | any | Go libraries |
| CPU parallelism | none | none for pure Python (GIL) | yes | yes |
| Blocking-call safety | one blocking call stalls all | isolated per thread | isolated per process | blocking is normal |
| Shared state | safe between awaits | locks everywhere | no sharing (IPC) | channels / mutexes |
| Cancellation | CancelledError, scopes | cooperative flags only | kill the process | context.Context |
| Debuggability | debug mode, task introspection | stack per thread | per process | race 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×
| Load | What changes | Async practice |
|---|---|---|
| 1× (one process) | defaults seem fine | no 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 work | size 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 exhaustion | deadline 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.17sThe 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.
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 sChange 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 seconds4. 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=405. 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
// 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 / Laravel | Python asyncio |
|---|---|
| PHP-FPM worker per request | def route in a thread / WSGI worker |
| Fibers (8.1) | coroutines (but no async/await colouring) |
| ReactPHP event loop + promises | asyncio loop + Futures |
| Swoole coroutines + runtime hooks | asyncio tasks (Python needs async libraries; hooks resemble gevent) |
Swoole\Coroutine\Channel | asyncio.Queue |
Octane::concurrently([...]) (Swoole task workers, separate process) | run_in_executor(process_pool, ...) + gather |
| Octane long-lived workers | Uvicorn 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 hooks | await 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: 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
}| Concern | Python asyncio | Go |
|---|---|---|
| Unit of concurrency | Task (coroutine on one loop) | goroutine (runtime-scheduled, many threads) |
| goroutines vs tasks: blocking call | blocks every task on the loop | blocks only that goroutine |
| CPU parallelism | none on the loop; processes | yes, GOMAXPROCS |
| Function colouring | async def must be awaited | none |
| channels vs Queue | asyncio.Queue(maxsize) | make(chan T, n) |
| Fan-out with a limit | Semaphore + gather / TaskGroup | errgroup + SetLimit |
| Cancellation | task.cancel() → CancelledError at next await | context cancel → check ctx.Done() / ctx.Err() |
| Timeout | asyncio.timeout, wait_for | context.WithTimeout |
| Leaked work | unreferenced task | goroutine leak |
| Per-request values | ContextVar | context.WithValue (sparingly) |
| Select over several waits | wait(FIRST_COMPLETED) | select statement |
| Race detection | rare (single thread); none built in | go test -race |
Common misconceptions
| Belief | Reality |
|---|---|
async def makes code faster | It lets waits overlap; blocking or CPU code inside it is as slow as before and also stalls every other task |
| asyncio runs coroutines in parallel | One loop is one thread; one coroutine runs at a time |
Calling an async def function runs it | It returns a coroutine object; nothing runs until it is awaited or wrapped in a Task |
await x() runs x in the background | It runs x now and waits for it; concurrency needs Tasks |
| One thread means no race conditions | Tasks interleave at every await that suspends; read-await-write lost 49 of 50 updates in the snippet |
Every await lets other tasks run | Only 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 error | It does not; TaskGroup (3.11+) and AnyIO task groups do |
create_task and forget is fine | The loop keeps only weak references; errors are lost; nothing cancels it on shutdown |
task.cancel() stops the task immediately | It requests a CancelledError at the task's next await; CPU loops without await cannot be cancelled |
Catching CancelledError and continuing is robust | It breaks TaskGroup, timeout() and shutdown; re-raise after cleanup |
except TimeoutError catches wait_for timeouts everywhere | On 3.9/3.10 it raises asyncio.TimeoutError, a different class |
wait(timeout=...) cancels unfinished tasks | It returns them in pending; you cancel them |
to_thread makes CPU code parallel | The GIL serialises pure-Python bytecode: 0.37 s vs 0.42 s measured; processes took 0.18 s |
| The default thread pool is unbounded | min(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 quick | Every call holds the loop; 20 calls took 2.07 s under gather |
asyncio.Lock protects data shared with threads | asyncio primitives are not thread-safe; use threading.Lock or call_soon_threadsafe |
threading.local isolates requests | All tasks share the loop thread; use ContextVar |
| An unbounded queue is safer | It turns a slow consumer into unbounded memory and latency; bound it and pick a policy |
nest_asyncio is a fix | It is a notebook workaround that patches asyncio internals and does not support uvloop |
| The GIL is gone in Python 3.13 | Only in the separate free-threaded build (3.13t experimental, 3.14t supported); the default build keeps it |
| uvloop changes how I write code | Same asyncio API; it replaces the loop implementation only |
Cheat sheet
| Topic | Remember |
|---|---|
| Run | asyncio.run(main()); inside coroutines just await |
| Concurrent | create_task, gather, TaskGroup (3.11+), AnyIO task group |
| Keep tasks | store every Task (set + done-callback, TaskGroup); drain on shutdown |
| gather | input order; first error propagates, siblings keep running; return_exceptions=True collects |
| Race / stream | wait(FIRST_COMPLETED) + cancel pending; as_completed |
| Cancel | task.cancel() → CancelledError at next await; cleanup in finally; re-raise |
| Shield | await shield(task) and keep task referenced |
| Timeouts | wait_for(aw, t); async with asyncio.timeout(t) (3.11+); AnyIO fail_after/move_on_after; catch asyncio.TimeoutError on ≤ 3.10 |
| Limit | Semaphore(n) around each call; bounded Queue(maxsize) for pipelines |
| Blocking I/O | await asyncio.to_thread(f, ...); FastAPI: def route or run_in_threadpool |
| Pool sizes | default executor min(32, cpu + 4); AnyIO 40 tokens; httpx 100 connections / 20 keep-alive |
| CPU | ProcessPoolExecutor via run_in_executor; created once |
| Per-request state | ContextVar; set → Token → reset in finally |
| Debug | PYTHONASYNCIODEBUG=1 or asyncio.run(main(), debug=True); slow callback ≥ 100 ms logged |
| HTTP | one httpx.AsyncClient per process, explicit Limits and Timeout |
| Loop | Uvicorn --loop auto = uvloop if installed; Windows: proactor |
| Tests | @pytest.mark.asyncio (strict) or @pytest.mark.anyio; not both in auto mode |
| GIL | threads for I/O, processes for CPU; free-threaded build is opt-in |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Concurrency vs parallelism | Interleaved progress of several tasks vs simultaneous execution on several cores |
| GIL | Global interpreter lock: one thread executes Python bytecode at a time in default CPython |
| Free-threaded Python | CPython build without the GIL (--disable-gil, python3.13t/3.14t; PEP 703, PEP 779) |
PYTHON_GIL | Environment variable that re-enables the GIL in a free-threaded build |
| I/O-bound | Work dominated by waiting for network, disk or databases |
| CPU-bound | Work dominated by computation |
| Blocking call | A call that holds the thread until done (time.sleep, requests, sync drivers) |
| Non-blocking I/O | Sockets in non-blocking mode plus readiness notification from a selector |
| Event loop | asyncio's scheduler: timers, ready callbacks, selector; runs all tasks on one thread |
| Selector | OS readiness API wrapper (selectors: epoll, kqueue, poll, select) |
| Proactor | Completion-based loop on Windows (IOCP); default there since 3.8 |
| uvloop | Drop-in asyncio loop on libuv, written in Cython; Uvicorn's default when installed |
| Callback / handle | A function scheduled with call_soon / call_later; what the loop actually runs |
| Coroutine function | A function defined with async def |
| Coroutine | The object a coroutine function returns; runs when awaited or wrapped in a Task |
async def | Defines a coroutine function (PEP 492, Python 3.5) |
await | Suspends the current coroutine until an awaitable completes |
| Awaitable | Coroutine, Task, Future, or any object with __await__ |
| Future | Low-level result placeholder with callbacks (asyncio.Future) |
| Task | A Future that drives a coroutine on the loop (asyncio.Task) |
create_task | Schedule a coroutine as a Task and return it |
| Fire and forget | Starting a task without awaiting it; safe only with a kept reference and error handling |
| Task reference | A strong reference you keep to a Task; the loop holds only weak ones |
| Eager task factory | 3.12+ option that runs a new task synchronously until its first suspension |
gather | Run awaitables concurrently, results in input order |
return_exceptions | gather flag: return exceptions as values instead of raising the first |
TaskGroup | 3.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_completed | Iterate over awaitables in completion order |
wait | Wait for a set until FIRST_COMPLETED, FIRST_EXCEPTION or ALL_COMPLETED; returns (done, pending) |
FIRST_COMPLETED | wait returns as soon as any future finishes or is cancelled |
| Cancellation | Requesting a task to stop; delivered as CancelledError at its next await |
CancelledError | The exception used for cancellation; a BaseException since 3.8 |
shield | Protect an inner awaitable from the outer task's cancellation |
| Timeout | A deadline after which work is cancelled and TimeoutError raised |
wait_for | Timeout on one awaitable; cancels it on expiry |
asyncio.timeout | 3.11+ async context manager putting a deadline on a block |
| Structured concurrency | Every task has a parent scope that waits for it and cancels it on failure |
| AnyIO | Library with structured concurrency over asyncio and Trio; the base of Starlette and FastAPI |
| Cancel scope | AnyIO/Trio context manager that can be cancelled, nested, shielded or given a deadline |
| Level vs edge cancellation | AnyIO re-delivers cancellation at every yield inside a cancelled scope; asyncio delivers it once |
Lock | asyncio mutex for tasks (not threads) |
Semaphore | Lets at most n tasks into a block; the standard concurrency limit |
Event | Flag that releases all waiters when set |
Condition | Lock plus a wait queue for predicates over shared state |
Queue | asyncio FIFO with optional maxsize; put/get/task_done/join |
| Producer consumer | Pattern where producer tasks feed a queue and consumer tasks drain it |
| Back-pressure | A slow consumer slowing the producer (bounded queue, rejected requests) |
to_thread | 3.9+ helper running a function in the default executor with the current context |
run_in_executor | Run a function in a given executor (or the default one) and await its Future |
ThreadPoolExecutor | concurrent.futures thread pool; default executor of the loop |
ProcessPoolExecutor | concurrent.futures process pool for CPU-bound work |
| Default executor size | min(32, os.cpu_count() + 4) (3.8–3.12); process_cpu_count from 3.13 |
multiprocessing | Standard library module for processes, pools, queues and shared memory |
| Async generator | async def with yield; consumed with async for (PEP 525) |
async for | Loop whose next-item step can await (__aiter__/__anext__) |
async with | Context manager whose enter/exit can await (__aenter__/__aexit__) |
| Async context manager | Object implementing __aenter__/__aexit__, or built with @asynccontextmanager |
contextvars / ContextVar | Per-task context variables (PEP 567, 3.7) |
asyncio.run | Create a loop, run a coroutine, clean up tasks, generators and the default executor |
loop.run_until_complete | Low-level: run the loop until one Future is done |
nest_asyncio | Third-party patch allowing nested asyncio.run; notebook workaround |
PYTHONASYNCIODEBUG | Environment variable enabling asyncio debug mode |
| Debug mode | asyncio mode that logs slow callbacks, never-awaited coroutine origins, wrong-thread calls |
| Slow callback duration | loop.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 AsyncClient | Async HTTP client with a connection pool; one per process |
| Connection limits | httpx.Limits: max_connections 100, max_keepalive_connections 20, keepalive_expiry 5 s by default |
| Uvicorn loop | Uvicorn's --loop option (auto, asyncio, uvloop); one loop per worker |
| FastAPI threadpool for def routes | def path operations run via anyio.to_thread.run_sync (40 tokens) |
| Starlette run_in_threadpool | await anyio.to_thread.run_sync(func); offload one call from async def |
| pytest-asyncio | pytest plugin running @pytest.mark.asyncio tests; strict and auto modes |
| AnyIO pytest plugin | Built into AnyIO; @pytest.mark.anyio and the anyio_backend fixture |
| Graceful shutdown | Stop new work, drain, cancel and await remaining tasks, close clients |
| Goroutine | Go's runtime-scheduled lightweight thread; may block freely |
| Channel | Go's typed pipe between goroutines; the counterpart of asyncio.Queue |
| PHP Fibers | PHP 8.1 full-stack suspendable functions |
| PHP Swoole / Open Swoole | PHP extensions with an event loop, coroutines, servers and clients |
| Laravel Octane | Laravel package serving the app from long-lived workers (FrankenPHP, Swoole, Open Swoole, RoadRunner) |
| ReactPHP | Event-loop library for PHP |
| SQLAlchemy / SQLModel / Alembic | ORM (with an asyncio extension), Pydantic-flavoured ORM layer and migration tool |
| Uvicorn / Starlette / FastAPI | ASGI server, ASGI toolkit (built on AnyIO), API framework |
References
- Python docs, "asyncio — Asynchronous I/O": https://docs.python.org/3/library/asyncio.html
- Python docs, "Coroutines and Tasks": https://docs.python.org/3/library/asyncio-task.html
- Python docs, "Event Loop": https://docs.python.org/3/library/asyncio-eventloop.html
- Python docs, "Futures": https://docs.python.org/3/library/asyncio-future.html
- Python docs, "Queues": https://docs.python.org/3/library/asyncio-queue.html
- Python docs, "Synchronization Primitives": https://docs.python.org/3/library/asyncio-sync.html
- Python docs, "Streams": https://docs.python.org/3/library/asyncio-stream.html
- Python docs, "Subprocesses": https://docs.python.org/3/library/asyncio-subprocess.html
- Python docs, "Developing with asyncio": https://docs.python.org/3/library/asyncio-dev.html
- Python docs, "Exceptions" (asyncio): https://docs.python.org/3/library/asyncio-exceptions.html
- Python docs, "Runners": https://docs.python.org/3/library/asyncio-runner.html
- Python docs, "Platform Support": https://docs.python.org/3/library/asyncio-platforms.html
- Python docs, "Policies": https://docs.python.org/3/library/asyncio-policy.html
- Python docs, "Call Graph Introspection": https://docs.python.org/3/library/asyncio-graph.html
- Python docs, "concurrent.futures": https://docs.python.org/3/library/concurrent.futures.html
- Python docs, "contextvars": https://docs.python.org/3/library/contextvars.html
- Python docs, "contextlib": https://docs.python.org/3/library/contextlib.html
- Python docs, "threading": https://docs.python.org/3/library/threading.html
- Python docs, "multiprocessing": https://docs.python.org/3/library/multiprocessing.html
- Python docs, "selectors": https://docs.python.org/3/library/selectors.html
- Python docs, Glossary ("global interpreter lock"): https://docs.python.org/3/glossary.html
- Python docs, "Python support for free threading": https://docs.python.org/3/howto/free-threading-python.html
- Python docs, "Compound statements" (
async def,async for,async with): https://docs.python.org/3/reference/compound_stmts.html - Python 3.9 docs, "Coroutines and Tasks": https://docs.python.org/3.9/library/asyncio-task.html
- Python 3.9 docs, "Event Loop": https://docs.python.org/3.9/library/asyncio-eventloop.html
- What's New in Python 3.4: https://docs.python.org/3/whatsnew/3.4.html
- What's New in Python 3.5: https://docs.python.org/3/whatsnew/3.5.html
- What's New in Python 3.7: https://docs.python.org/3/whatsnew/3.7.html
- What's New in Python 3.8: https://docs.python.org/3/whatsnew/3.8.html
- What's New in Python 3.9: https://docs.python.org/3/whatsnew/3.9.html
- What's New in Python 3.11: https://docs.python.org/3/whatsnew/3.11.html
- What's New in Python 3.12: https://docs.python.org/3/whatsnew/3.12.html
- What's New in Python 3.13: https://docs.python.org/3/whatsnew/3.13.html
- What's New in Python 3.14: https://docs.python.org/3/whatsnew/3.14.html
- What's New in Python 3.15: https://docs.python.org/3/whatsnew/3.15.html
- PEP 342, "Coroutines via Enhanced Generators": https://peps.python.org/pep-0342/
- PEP 380, "Syntax for Delegating to a Subgenerator": https://peps.python.org/pep-0380/
- PEP 3156, "Asynchronous IO Support Rebooted: the asyncio Module": https://peps.python.org/pep-3156/
- PEP 492, "Coroutines with async and await syntax": https://peps.python.org/pep-0492/
- PEP 525, "Asynchronous Generators": https://peps.python.org/pep-0525/
- PEP 530, "Asynchronous Comprehensions": https://peps.python.org/pep-0530/
- PEP 567, "Context Variables": https://peps.python.org/pep-0567/
- PEP 654, "Exception Groups and except*": https://peps.python.org/pep-0654/
- PEP 703, "Making the Global Interpreter Lock Optional in CPython": https://peps.python.org/pep-0703/
- PEP 779, "Criteria for supported status for free-threaded Python": https://peps.python.org/pep-0779/
- PEP 537 / 569 / 596 / 664 / 745 / 790 (3.7 / 3.8 / 3.9 / 3.11 / 3.14 / 3.15 release schedules): https://peps.python.org/pep-0537/, https://peps.python.org/pep-0569/, https://peps.python.org/pep-0596/, https://peps.python.org/pep-0664/, https://peps.python.org/pep-0745/, https://peps.python.org/pep-0790/
- CPython 3.9 source,
Lib/asyncio/base_events.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/base_events.py - CPython 3.9 source,
Lib/asyncio/tasks.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/tasks.py - CPython 3.9 source,
Lib/asyncio/threads.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/threads.py - CPython 3.9 source,
Lib/asyncio/locks.py: https://raw.githubusercontent.com/python/cpython/3.9/Lib/asyncio/locks.py - CPython source,
Lib/concurrent/futures/thread.py(3.9 and main): https://raw.githubusercontent.com/python/cpython/3.9/Lib/concurrent/futures/thread.py, https://raw.githubusercontent.com/python/cpython/main/Lib/concurrent/futures/thread.py - AnyIO, "Creating and managing tasks": https://anyio.readthedocs.io/en/stable/tasks.html
- AnyIO, "Cancellation and timeouts": https://anyio.readthedocs.io/en/stable/cancellation.html
- AnyIO, "Using synchronization primitives": https://anyio.readthedocs.io/en/stable/synchronization.html
- AnyIO, "Working with threads": https://anyio.readthedocs.io/en/stable/threads.html
- AnyIO, "Testing with AnyIO": https://anyio.readthedocs.io/en/stable/testing.html
- AnyIO, "Why you should be using AnyIO APIs instead of asyncio APIs": https://anyio.readthedocs.io/en/stable/why.html
- uvloop README: https://raw.githubusercontent.com/MagicStack/uvloop/master/README.rst
- httpx, "Async Support": https://www.python-httpx.org/async/
- httpx, "Resource Limits": https://www.python-httpx.org/advanced/resource-limits/
- httpx, "Timeouts": https://www.python-httpx.org/advanced/timeouts/
- httpx, "Clients": https://www.python-httpx.org/advanced/clients/
- FastAPI, "Concurrency and async / await": https://fastapi.tiangolo.com/async/
- FastAPI, "Lifespan Events": https://fastapi.tiangolo.com/advanced/events/
- FastAPI, "Async Tests": https://fastapi.tiangolo.com/advanced/async-tests/
- FastAPI, "Dependencies with yield": https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/
- Starlette, "Thread Pool": https://www.starlette.dev/threadpool/
- Starlette source,
starlette/concurrency.py: https://raw.githubusercontent.com/encode/starlette/master/starlette/concurrency.py - Uvicorn, "Settings": https://www.uvicorn.dev/settings/
- pytest-asyncio documentation: https://pytest-asyncio.readthedocs.io/en/latest/
- pytest-asyncio, "Concepts": https://pytest-asyncio.readthedocs.io/en/latest/concepts.html
- pytest-asyncio, "Configuration": https://pytest-asyncio.readthedocs.io/en/latest/reference/configuration.html
- SQLAlchemy 2.0, "Asynchronous I/O (asyncio)": https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html
- nest_asyncio README: https://raw.githubusercontent.com/erdewit/nest_asyncio/master/README.rst
- PyPI JSON for pins (pytest-asyncio, anyio, uvloop): https://pypi.org/pypi/pytest-asyncio/json, https://pypi.org/pypi/anyio/json, https://pypi.org/pypi/uvloop/json
- A Tour of Go, "Concurrency" (source): https://raw.githubusercontent.com/golang/website/master/_content/tour/concurrency.article
- Go blog, "Go Concurrency Patterns: Pipelines and cancellation" (source): https://raw.githubusercontent.com/golang/website/master/_content/blog/pipelines.md
- Effective Go: https://go.dev/doc/effective_go
- The Go Memory Model: https://go.dev/ref/mem
- PHP manual, "Fibers": https://www.php.net/manual/en/language.fibers.php
- ReactPHP: https://reactphp.org/
- Swoole README: https://raw.githubusercontent.com/swoole/swoole-src/master/README.md
- Open Swoole, "Coroutine": https://openswoole.com/docs/modules/swoole-coroutine
- Laravel 13, "Octane": https://laravel.com/docs/13.x/octane
- Laravel 13, "HTTP Client" (concurrent requests,
Http::pool): https://laravel.com/docs/13.x/http-client