Skip to content

Lesson 22 of 59Async and background work

Asyncio in Depth

Tasks, gather, TaskGroup, timeouts, cancellation and semaphores, plus how to mix sync and async code without freezing your FastAPI server.

18 min read0/4 questions

You already know that async def routes run on an event loop and must not block. That is enough to write a route that awaits one database query. Real services do more: call three APIs at once, give up on a slow one after two seconds, cap how many requests hit a partner's API at the same time, and clean up properly when a client disconnects. This lesson covers the asyncio tools for all of that, and the mistakes that show up in code review again and again.

The event loop, recapped

This is a quick recap of Async and Await in the Python course. An event loop runs on one thread and juggles many coroutines. A coroutine runs until it reaches an await on something that is not ready (a socket with no data yet, a timer), then hands control back to the loop, which resumes another coroutine that is ready. Nothing runs in parallel. The trick is that a web server spends most of its time waiting, and the loop fills that waiting time with other work.

Two consequences follow from that design. First, anything that blocks without awaiting (a time.sleep, a sync HTTP call, a heavy loop) stops every coroutine on that loop. Second, concurrency only happens where you ask for it. await on its own does not run things at the same time; it waits.

Coroutines and tasks

Calling an async def function does not run it. It returns a coroutine object, a paused computation. Something has to drive it:

  • await coro runs it now, inside the current coroutine, and waits for its result.
  • asyncio.create_task(coro) wraps it in a Task and schedules it on the loop to start soon. You get the task back immediately and can await it later.
tasks.py
import asyncio
 
 
async def fetch_user(user_id: int) -> dict:
    await asyncio.sleep(0.1)            # stands in for an HTTP call
    return {"id": user_id}
 
 
async def main() -> None:
    coro = fetch_user(1)                # nothing has run yet
    user = await coro                   # runs now, waits 0.1 s
 
    task = asyncio.create_task(fetch_user(2))   # starts in the background
    ...                                         # do other work meanwhile
    other = await task                          # collect the result
 
 
asyncio.run(main())

Keep a reference to every task you create. The loop only holds a weak reference, so a fire-and-forget task with nothing pointing at it can be garbage collected before it finishes. Forgetting await entirely gives the warning coroutine 'fetch_user' was never awaited, and the code silently never ran.

gather: sequential vs concurrent

Three awaits in a row take the sum of their times. asyncio.gather turns each coroutine into a task, starts them all, and waits for all of them, so the total is roughly the longest one. Real asyncio.run does not work inside this page's runner, so here is a tiny event loop built on the same idea: coroutines that await an object, and a loop that decides who runs next. It uses a fake clock so the output is exact.

Pythonmini_asyncio.py
import heapq class Sleep: """Like asyncio.sleep: an awaitable that tells the loop how long to wait.""" def __init__(self, ms): self.ms = ms def __await__(self): yield ("sleep", self.ms) class Task: def __init__(self, coro): self.coro, self.done, self.result, self.waiters = coro, False, None, [] def __await__(self): if not self.done: yield ("wait", self) return self.result class Loop: def __init__(self): self.now, self.queue, self.seq = 0, [], 0 def schedule(self, task, delay=0): self.seq += 1 heapq.heappush(self.queue, (self.now + delay, self.seq, task)) def create_task(self, coro): task = Task(coro) self.schedule(task) return task def run(self, coro): self.now = 0 main = self.create_task(coro) while self.queue: self.now, _, task = heapq.heappop(self.queue) try: kind, arg = task.coro.send(None) # run until the next await except StopIteration as stop: task.done, task.result = True, stop.value for waiter in task.waiters: self.schedule(waiter) continue if kind == "sleep": self.schedule(task, arg) elif arg.done: self.schedule(task) else: arg.waiters.append(task) return main.result loop = Loop() async def gather(*coros): tasks = [loop.create_task(c) for c in coros] # all start now return [await t for t in tasks] async def fetch(name, ms): print(f"t={loop.now:>3}ms start {name}") await Sleep(ms) # waiting on the network print(f"t={loop.now:>3}ms done {name}") return name async def sequential(): return [await fetch("users", 100), await fetch("orders", 150), await fetch("prices", 50)] async def concurrent(): return await gather(fetch("users", 100), fetch("orders", 150), fetch("prices", 50)) print("Sequential:", loop.run(sequential()), f"in {loop.now}ms")print()print("gather:", loop.run(concurrent()), f"in {loop.now}ms")
Output
Press Run (⌘ Enter) to see what happens.

Sequentially, orders cannot even start until users has finished, so the waits add up to 300 ms. With gather, all three requests are in flight at t=0 and the whole thing takes as long as the slowest, 150 ms. Notice that results still come back in the order you passed them, not the order they finished. Real asyncio works the same way, with a real clock and real sockets underneath.

Quick check
Using the mini loop above, you run gather(fetch("a", 200), fetch("b", 200), fetch("c", 50)). Which finishes first, and what is loop.now at the end?
Need a nudge? A hint rules out a wrong answer.

By default, if one coroutine in gather raises, the exception propagates to you, but the others keep running in the background, unwatched. gather(..., return_exceptions=True) instead returns exceptions in the results list so you can handle each one.

TaskGroup: structured concurrency

asyncio.TaskGroup (Python 3.11+) is the safer modern choice. Tasks belong to the group, the async with block does not exit until all of them are done, and if one fails, the group cancels the rest and raises an ExceptionGroup.

app/services/dashboard.py
async def load_dashboard(user_id: int) -> Dashboard:
    async with asyncio.TaskGroup() as tg:
        profile = tg.create_task(get_profile(user_id))
        orders = tg.create_task(get_orders(user_id))
        alerts = tg.create_task(get_alerts(user_id))
    # all three finished successfully here
    return Dashboard(profile=profile.result(), orders=orders.result(), alerts=alerts.result())
One task fails inside a TaskGroup
load_dashboardTaskGroupget_ordersget_profilecreate three tasksstartstartraises HTTPErrorcancel()CancelledError, stoppedExceptionGroup

Inside the async with block, three tasks are created. They all start running concurrently.

1/7

You catch the failure with except* httpx.HTTPError as group:, which matches errors of that type inside the group. Use gather when you want partial results, and TaskGroup when the work is all-or-nothing, which is most of the time.

Timeouts

Every network call needs a timeout. A partner API that hangs forever will otherwise hold your coroutine, its database connection and its memory until the process dies. Wrap any block of awaits in asyncio.timeout:

try:
    async with asyncio.timeout(2):
        rates = await get_exchange_rates()
except TimeoutError:
    rates = DEFAULT_RATES        # degrade instead of failing the whole request

When the deadline passes, asyncio cancels the work inside the block and raises TimeoutError at the async with. Older code uses asyncio.wait_for(coro, timeout=2), which does the same for a single awaitable. Client libraries have their own timeouts too (httpx.AsyncClient(timeout=5)); set both, the library one per call and asyncio.timeout for the whole operation.

Cancellation

Cancellation is how asyncio stops work: task.cancel() makes a CancelledError appear at the await where the task is paused. Timeouts, TaskGroups and server shutdown all use it, and so does Uvicorn when a client disconnects from a streaming response.

async def stream_report(conn):
    try:
        while True:
            await conn.send(await next_chunk())
    except asyncio.CancelledError:
        logger.info("client went away")
        raise                     # always re-raise
    finally:
        await conn.close()        # cleanup runs either way

The rule: never swallow CancelledError. Clean up in finally, log if you like, then let it propagate. A coroutine that catches it and carries on breaks timeouts and TaskGroups, and can make shutdown hang. Note that a bare except Exception: does not catch it, because CancelledError inherits from BaseException.

Quick check
A coroutine catches asyncio.CancelledError, logs it, and returns normally. What is the problem?
Need a nudge? A hint rules out a wrong answer.

Limiting concurrency with a semaphore

gather over 10,000 URLs opens 10,000 connections at once. The partner API rate-limits you, your database pool runs dry, and you run out of file descriptors. An asyncio.Semaphore caps how many coroutines can be inside a block at the same time:

sem = asyncio.Semaphore(20)
 
 
async def fetch_one(client: httpx.AsyncClient, url: str) -> int:
    async with sem:                         # at most 20 inside at once
        response = await client.get(url)
        return response.status_code
 
 
async def fetch_all(urls: list[str]) -> list[int]:
    async with httpx.AsyncClient(timeout=10) as client:
        return await asyncio.gather(*(fetch_one(client, u) for u in urls))

The other 9,980 coroutines wait cheaply at async with sem until a slot frees up. Note the single shared AsyncClient: creating one client per request throws away connection reuse.

Mixing sync and async

Sooner or later you need a library that only has a blocking API: an old SDK, a sync database driver, a PDF generator. From async code, push the call to a thread so the loop stays free:

pdf_bytes = await asyncio.to_thread(render_pdf, invoice)

FastAPI also exports Starlette's helper, from fastapi.concurrency import run_in_threadpool, which does the same job. Threads help with blocking I/O. For CPU-heavy work (image processing, big calculations), threads do not run Python code in parallel in the default build, so use a process pool or move it to a task queue.

Going the other way, from sync code into async, asyncio.run(main()) is for the top of a script or CLI. Never call it inside a running loop, such as in an async def route: it raises RuntimeError.

Match the pairs0/5 matched

Match each need to the asyncio tool.

Choose an item, then its match on the other side.

Common mistakes

These come up in almost every async codebase:

  • Blocking calls in async def: requests.get, time.sleep, sync SQLAlchemy sessions, large file reads. One of these stalls every request on the worker. Use the async library, to_thread, or a plain def route.
  • Forgetting await: user = get_user(id) gives you a coroutine, not a user. Type checkers catch this, which is one more reason to run mypy or pyright.
  • Accidental serial code: a for loop with await inside runs one at a time. Fine when each step depends on the last, slow when they do not.
  • Unbounded concurrency: gather over an unknown-size list without a semaphore.
  • Lost tasks: create_task with no reference and no error handling, so its exception is only logged at garbage collection, if at all.
  • New clients per call: creating an httpx.AsyncClient or a Redis client per request instead of once in the lifespan.
Quick check
This route takes 3 seconds. Each get_price call takes about 1 second and they are independent. What is the best fix?
@app.get("/prices")
async def prices():
  result = []
  for symbol in ["AAPL", "MSFT", "GOOG"]:
      result.append(await get_price(symbol))
  return result
Need a nudge? A hint rules out a wrong answer.
Key terms
coroutine object
What calling an async def function returns: paused work that runs only when awaited or wrapped in a task.
Task
A coroutine scheduled on the event loop to run concurrently. Created with create_task or a TaskGroup.
asyncio.gather
Runs awaitables concurrently and returns their results in the order given.
TaskGroup
Structured concurrency: waits for all its tasks and cancels the rest if one fails.
CancelledError
Raised inside a task at its current await when it is cancelled. Clean up, then re-raise.
Semaphore
A counter that limits how many coroutines can be inside a block at once.
asyncio.to_thread
Runs a blocking function in a worker thread so the event loop keeps serving others.