Python · Chapter 21 of 21
Python asyncio: async, await, TaskGroup, timeouts and queues
15 min study · Examples checked with Python 3.14 and 3.15 ·
asyncio runs many tasks in a single thread by having them take turns. A task runs until it reaches an await on something that has to wait, such as a network response or a timer, and at that point the event loop switches to another task that is ready. With no threads to coordinate, a single process can handle thousands of open connections. It is how FastAPI serves requests and how the MCP servers in the FastMCP track talk to clients. This chapter covers coroutines, concurrent tasks, failures, limits, timeouts and cancellation, and the rule that matters most: never block the loop.
Coroutines and await
async def defines a coroutine function, such as async def fetch_lesson(lesson_id) in the next example. Calling it does not run it: fetch_lesson(1) returns a coroutine object, which runs only when something awaits it. await suspends the current coroutine until the awaited one finishes and hands back its result. asyncio.run(main()) starts the event loop, runs main to completion and shuts the loop down; call it once, at the top of a program.
A coroutine you forget to await never runs, and Python warns “coroutine … was never awaited”.
Run tasks concurrently with TaskGroup
Awaiting one coroutine after another is still sequential. To overlap them, turn them into tasks:
import asyncio
import time
async def fetch_lesson(lesson_id: int) -> str:
await asyncio.sleep(0.1)
return f"Lesson {lesson_id}"
async def main() -> None:
start = time.perf_counter()
one_by_one = [await fetch_lesson(i) for i in range(1, 4)]
print(f"sequential: {time.perf_counter() - start:.1f}s") # sequential: 0.3s
start = time.perf_counter()
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch_lesson(i)) for i in range(1, 4)]
print(f"concurrent: {time.perf_counter() - start:.1f}s") # concurrent: 0.1s
asyncio.run(main())
tg.create_task schedules a coroutine to run as soon as the current task yields, and the async with block waits until all tasks in the group have finished. That ownership is the point of a TaskGroup: no task outlives the block, and nothing is silently forgotten. asyncio.gather(*coros) is the older way to run several awaitables and collect results in order; you will see it in a lot of existing code.
When tasks fail
If a task in a TaskGroup raises, the group cancels the remaining tasks and raises an ExceptionGroup containing every failure. except* handles the exceptions in such a group by type:
import asyncio
async def fetch(lesson_id: int) -> str:
await asyncio.sleep(0.05 * lesson_id)
if lesson_id == 2:
raise LookupError(f"lesson {lesson_id} missing")
return f"Lesson {lesson_id}"
async def main() -> None:
try:
async with asyncio.TaskGroup() as tg:
for i in (1, 2, 3):
tg.create_task(fetch(i))
except* LookupError as group:
print("failed:", [str(e) for e in group.exceptions]) # failed: ['lesson 2 missing']
asyncio.run(main())
Task 3 never finishes: it is cancelled when task 2 fails, which is what you want when the tasks are parts of one job. When the tasks are independent and you want every result, await asyncio.gather(fetch(1), fetch(2), return_exceptions=True) returns ['Lesson 1', LookupError('lesson 2 missing')]: exceptions take the place of results instead of being raised.
Limit concurrency and set timeouts
Starting a thousand requests at once overloads servers and trips rate limits. A Semaphore caps how many tasks are inside a section at the same time, and asyncio.timeout puts a deadline on a block:
import asyncio
async def fetch(lesson_id: int, limit: asyncio.Semaphore) -> str:
async with limit: # at most 2 inside at once
await asyncio.sleep(0.1)
return f"Lesson {lesson_id}"
async def main() -> None:
limit = asyncio.Semaphore(2)
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(i, limit)) for i in range(1, 7)]
print(len(tasks), "fetched in pairs") # 6 fetched in pairs (about 0.3s)
try:
async with asyncio.timeout(0.05):
await fetch(99, limit)
except TimeoutError:
print("gave up after 0.05s") # gave up after 0.05s
asyncio.run(main())
When the deadline passes, the code inside the timeout block is cancelled and a TimeoutError appears at the block boundary. Real HTTP clients such as httpx also take their own timeouts; use both, since a semaphore slot held by a hung request is lost capacity. For a very large number of items, create a fixed number of worker tasks that read from an asyncio.Queue instead of one task per item.
Cancellation and cleanup
Any task can be cancelled. Cancellation raises CancelledError inside the task at its current await, so cleanup belongs in finally or an async with block:
import asyncio
async def heartbeat() -> None:
try:
while True:
await asyncio.sleep(0.02)
finally:
print("heartbeat stopped cleanly")
async def main() -> None:
task = asyncio.create_task(heartbeat())
await asyncio.sleep(0.05)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("cancelled:", task.cancelled()) # cancelled: True
asyncio.run(main())
If you catch CancelledError yourself, re-raise it after cleaning up; swallowing it breaks timeouts and task groups. A task created with asyncio.create_task outside a group must be kept in a variable and awaited or cancelled eventually, since the loop only holds a weak reference and an unowned task can disappear. Cancellation only takes effect at an await, so a long calculation with no awaits cannot be interrupted.
Don’t block the event loop
All tasks share one thread, so any call that blocks freezes every task: time.sleep, requests.get, a synchronous database driver, a big calculation. Use async libraries (httpx or aiohttp for HTTP, asyncpg or an async ORM for databases), and move unavoidable blocking calls to a thread:
import asyncio
import time
def slow_report() -> str:
time.sleep(0.2) # a blocking library call
return "report ready"
async def ticker() -> None:
for _ in range(3):
print("tick")
await asyncio.sleep(0.05)
async def main() -> None:
report, _ = await asyncio.gather(asyncio.to_thread(slow_report), ticker())
print(report) # three ticks print while the report is built
asyncio.run(main())
asyncio.to_thread runs the function in a worker thread and lets the loop keep serving other tasks. CPU-heavy work belongs in a process pool (chapter 20), reached with loop.run_in_executor. Run your program with PYTHONASYNCIODEBUG=1 and asyncio reports callbacks that hold the loop too long; since Python 3.14, python -m asyncio ps <pid> lists the tasks of a running program.
Practice
Simulate fetching 10 lessons, each taking 0.1 seconds, with at most 3 in flight, and lesson 4 raising LookupError. Collect every successful result and every failure without cancelling the others, and put a 1-second timeout on the whole job. Then replace asyncio.sleep with time.sleep inside the fetch and compare the run time.
Answer check: with gather(..., return_exceptions=True) and a semaphore of 3, the job takes about 0.4 seconds and returns nine titles and one LookupError. With time.sleep, nothing overlaps and the job takes about 1 second, because each blocking call holds the whole loop; for the same reason, a timeout cannot fire until a blocking call returns.
Summary
Coroutines run only when awaited, and asyncio.run starts the loop. Use TaskGroup to run related tasks concurrently and handle the resulting ExceptionGroup with except*, or gather(..., return_exceptions=True) for independent results. Limit concurrency with a semaphore, put deadlines on waits, clean up in finally and re-raise cancellation, and keep blocking calls off the event loop.