0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Synchronization
Concurrency Patterns
Python Asyncio in Practice
Python asyncio is the standard library framework for single threaded concurrent I/O. It powers FastAPI, aiohttp, many database drivers and a large share of modern Python network code. This section covers the core pieces you use every day: running a program, coroutines and tasks, gathering results and the TaskGroup introduced in Python 3.11.
Running a program
An asyncio program starts with asyncio.run, which creates a new event loop, runs the given coroutine until it completes, then cancels any remaining tasks, shuts down asynchronous generators and the default executor, and closes the loop. Everything asynchronous happens inside that coroutine, conventionally called main. There should be one asyncio.run call per program, at the top level; calling it from inside a running loop raises an error, since a thread can run only one loop at a time. Older code used get_event_loop and run_until_complete directly, which is now discouraged outside framework internals because it leaves loop lifecycle and cleanup to the caller. Frameworks such as FastAPI under Uvicorn create and run the loop themselves, so application code inside them only writes async functions and never calls asyncio.run.
Coroutines and tasks
Calling an async def function returns a coroutine object and runs none of its code. A coroutine runs only when awaited by another coroutine, in which case it runs as part of the caller, sequentially, or when wrapped in a task. asyncio.create_task schedules a coroutine to run concurrently as an independent task on the loop, starting on the next loop iteration, and returns a Task object, which is a future that completes with the coroutine result. The distinction is the key to concurrency in asyncio: awaiting three coroutines in a row runs them one after another, while creating three tasks and then awaiting them runs them concurrently, with their waits overlapping. A task keeps running even if nobody awaits it, but the loop holds only a weak reference to it, so a program must keep its own reference, or the task may be garbage collected while still pending, a documented pitfall.
Gather
asyncio.gather takes several awaitables, wraps any coroutines in tasks, runs them concurrently and returns a list of their results in the order the awaitables were passed, regardless of completion order. Its error handling is the part people get wrong. By default, if one awaitable raises, gather immediately propagates that exception to its caller, but the other tasks keep running in the background, unobserved, and their later exceptions are lost. With return_exceptions set to True, gather waits for everything and returns exceptions as values in the result list, so the caller can inspect each outcome. If the gather itself is cancelled, it cancels all of its children. Because of the background tasks left running on failure, gather is a poor fit for operations where one failure should stop the rest.
TaskGroup
Python 3.11 added asyncio.TaskGroup, an asynchronous context manager that brings structured concurrency to asyncio. Tasks are created with the create_task method of the group inside an async with block, and the block does not exit until every task in the group has finished. If any task raises an exception other than cancellation, the group cancels all remaining tasks, waits for them to finish, and then raises an ExceptionGroup containing every exception that occurred, which can be handled with the except star syntax also added in 3.11. This guarantees that no task outlives the block that created it, that failures are never silently lost, and that one failure promptly stops sibling work. For most new code, TaskGroup should replace both gather and loose create_task calls.
Waiting on several tasks
Other tools fit other needs. asyncio.wait takes a set of tasks and returns done and pending sets according to return_when, which can be FIRST_COMPLETED, FIRST_EXCEPTION or ALL_COMPLETED, without raising exceptions itself and without cancelling anything, leaving the caller in full control. asyncio.as_completed yields awaitables in the order their results become available, useful for processing results as soon as each arrives, for example rendering search results from several backends as they come in. asyncio.wait_for awaits a single awaitable with a timeout and cancels it if the timeout expires. Each of these leaves responsibility for cancelling and awaiting leftover tasks with the caller, which is exactly the bookkeeping TaskGroup does automatically, so they are best used inside a TaskGroup or with careful cleanup in a finally block.
Never awaited coroutines
The most common asyncio bug is forgetting an await. Writing fetch_user(42) instead of await fetch_user(42) creates a coroutine object, discards it, and moves on, so the fetch never happens and the variable that should hold a user holds a coroutine instead. Python emits a RuntimeWarning saying the coroutine was never awaited when the object is garbage collected, but the warning is easy to miss in production logs and the failure often appears later as a confusing attribute error on the coroutine object. Type checkers such as mypy and pyright catch most of these mistakes statically, since the return type of an async function is a coroutine rather than the value, and linters flag unused coroutine expressions. Enabling asyncio debug mode in tests also reports the exact line that created each unawaited coroutine, which turns a silent logic error into a clear failure during development rather than a mystery in production.
Results, exceptions and task state
A task moves through a small set of states: pending while its coroutine is still running or suspended, then done once it has returned a value, raised an exception or been cancelled. The result method returns the value of a finished task, raises the exception the coroutine raised, or raises CancelledError if it was cancelled, and calling it on a pending task raises InvalidStateError. The exception method returns the stored exception without raising it. Awaiting a task is usually the right way to get its outcome, since it suspends until the task finishes and then either returns the value or raises. add_done_callback registers a plain function that runs on the loop when the task finishes, which is how libraries attach logging, metrics or cleanup to tasks they do not await directly. A task that finishes with an exception nobody retrieves triggers an error log when it is destroyed, the last line of defence against silently failing background work, and a strong hint that something should own that task.
Thinking in await points
A useful mental model for asyncio code is to read each function as a series of segments separated by awaits. Inside a segment, the code runs to completion without interruption, exactly like ordinary synchronous Python. At each await, the task may pause and any other ready task may run, changing shared state, before this one resumes. Reviewing async code therefore means asking, at every await, what could have changed while this task was suspended, and whether the code after the await still holds the assumptions it made before it. Functions with few awaits are easy to reason about; functions that interleave reads of shared state with awaits deserve the same care as multithreaded code, though with the advantage that the interleaving points are visible in the source rather than possible at every instruction.
Coroutines do nothing until awaited or wrapped in a task, and only tasks run concurrently. Gather returns results in input order but leaves siblings running after a failure. TaskGroup waits for every child, cancels the rest when one fails and raises an ExceptionGroup, so prefer it for new code, and keep references to any task you create outside a group.