My account

Async Python with asyncio

With asyncio, one thread runs many tasks. A task runs until it reaches an await on something that is not ready, and then the event loop runs another task. This makes thousands of network calls cheap. But it only works if every task gives control back often. One blocking call stops every task. Learn to run calls together with TaskGroup, to add timeouts, and to handle cancellation correctly.

Not reviewedWritten with AI helpReading time: 17 minOnline shop examplePython 3.14 code

Author: bezzad

Contents

The problem: a slow checkout

When a customer presses “Pay” in our online shop, the checkout service calls three other services:

  1. The payment service: about 300 ms.
  2. The stock service: about 300 ms.
  3. The shipping service: about 300 ms.

The first version of the code waits for each call before it starts the next one. The customer waits about 900 ms. But the three calls do not depend on each other. If they run at the same time, the customer waits about 300 ms. This is what asyncio is good at.

The event loop

The event loop is the center of asyncio. It runs in one thread and manages many tasks.

  1. A task runs until it reaches an await on something that is not ready yet, for example a network answer.
  2. At that point the task pauses, and gives control back to the loop.
  3. The loop runs another task that is ready.
  4. When the network answer arrives, the loop wakes up the paused task, and it continues after the await.

This is called cooperative multitasking. Tasks are never stopped in the middle by force. They give control back only at an await. This is both the strength and the weak point of asyncio.

Coroutines and await

A function defined with async def is a coroutine function. Calling it does not run it. It only makes a coroutine object.

import asyncio

async def charge_card(order_id: int) -> str:
    await asyncio.sleep(0.3)        # stands for a network call
    return f"paid {order_id}"

async def main() -> None:
    # Bad: nothing runs. Python warns "never awaited"
    charge_card(7)
    # Good: runs and waits for the result
    result = await charge_card(7)
    print(result)

asyncio.run(main())
  1. The await keyword runs the coroutine and waits for its result. While it waits, other tasks can run.
  2. The asyncio.run function starts the event loop, runs main, and closes the loop at the end. Call it once, at the start of the program.
  3. You can use await only inside async def. A normal function cannot wait for a coroutine.

Running calls together: TaskGroup

Three await lines one after another still run one after another. To run them at the same time, make them tasks. Since Python 3.11, TaskGroup is the recommended way:

import asyncio

async def call_service(name: str, order_id: int) -> str:
    await asyncio.sleep(0.3)        # stands for an HTTP call
    return f"{name} ok for {order_id}"

async def checkout(order_id: int) -> list[str]:
    async with asyncio.TaskGroup() as group:
        payment = group.create_task(call_service("payment", order_id))
        stock = group.create_task(call_service("stock", order_id))
        shipping = group.create_task(
            call_service("shipping", order_id))
    # here all three tasks are finished
    return [payment.result(), stock.result(), shipping.result()]

print(asyncio.run(checkout(7)))   # takes about 0.3 s, not 0.9 s
await, then await, then awaitpaymentstockshippingabout 900 msThree tasks in one TaskGrouppaymentstockshippingabout 300 ms
One await after another adds up the waiting times. Tasks in a TaskGroup wait at the same time, so the total is about as long as the slowest call.

Why TaskGroup and not only gather?

  1. The async with block waits for all tasks before it exits. No task is forgotten.
  2. If one task fails, the group cancels the other tasks. You do not keep paying for work whose result you will throw away.
  3. The errors come together in an ExceptionGroup. You can handle them with the except star syntax.

The older asyncio.gather function is still fine for simple cases. But know one difference: by default, if one call fails, gather gives you that error, and the other calls keep running in the background. With the option return_exceptions set to True, it returns errors as values in the result list.

Keep a reference to your tasks

The create_task function of asyncio starts a task “in the background”. The event loop keeps only a weak reference to it. If your code keeps no reference, the task can be removed by the garbage collector before it finishes.

background_tasks: set[asyncio.Task] = set()

def send_receipt_later(order_id: int) -> None:
    task = asyncio.create_task(send_receipt(order_id))
    background_tasks.add(task)                        # keep it alive
    # forget it when done
    task.add_done_callback(background_tasks.discard)

Also, errors in a task that nobody awaits are only logged at the end. Inside a request, prefer a TaskGroup. For real background work that must not be lost, use a job queue.

The biggest trap: blocking calls

The event loop has only one thread. If a task does something slow without await, nothing else can run. Not other tasks, not other users’ requests.

import time
import requests  # a blocking (sync) HTTP library

async def get_price(sku: str) -> float:
    # Bad: blocks the loop
    time.sleep(1)
    # Bad: requests blocks the loop too
    response = requests.get(f"https://prices.example/{sku}")
    return response.json()["price"]
  1. The time.sleep function stops the whole thread. The asyncio.sleep function only pauses this task.
  2. A sync HTTP or database library waits on the network inside the thread. The loop cannot switch to another task.
  3. A long CPU loop (for example, building a big report) also blocks, because there is no await inside it.
  4. The result: in a web server, one slow request makes every other request on that worker slow too.
One thread, one blocking callTask ATask BTask Ctime.sleep(1)Ready, but cannot runReady, but cannot runThe event loop is stuckWith asyncio.sleep, Task A would pause and let B and C run at once.
While one task runs a blocking call, the event loop is stuck. Other tasks are ready, but they cannot run until the blocking call ends.

The fixes:

  1. Use async libraries: for example httpx with its AsyncClient for HTTP, and an async driver for your database.
  2. For a blocking call you cannot change, move it to a thread with asyncio.to_thread. The loop stays free while the thread waits.
  3. For heavy CPU work, use a process pool (see the lesson on concurrency in Python).
import asyncio
import httpx

async def get_price(client: httpx.AsyncClient, sku: str) -> float:
    response = await client.get(f"https://prices.example/{sku}")
    return response.json()["price"]

async def build_invoice_pdf(order_id: int) -> bytes:
    # render_pdf_sync comes from an old sync library
    return await asyncio.to_thread(render_pdf_sync, order_id)

Since Python 3.14, you can see what a running asyncio program is doing with the command “python -m asyncio ps” and the process id. It shows the tasks and where each one is waiting.

Timeouts

A network call without a timeout can wait forever. Since Python 3.11, use the asyncio.timeout context manager:

async def checkout_with_limit(order_id: int) -> list[str]:
    try:
        async with asyncio.timeout(2):       # seconds
            return await checkout(order_id)
    except TimeoutError:
        raise PaymentUnavailable(order_id)
  1. When the time is up, the work inside the block is cancelled.
  2. Then it raises TimeoutError (the built-in one) when the block exits.
  3. The older asyncio.wait_for function still works, and does the same for one awaitable.

Cancellation

When a task is cancelled (by a timeout, by a TaskGroup, or by a client that closes the connection), asyncio raises CancelledError inside the task, at the await where it is waiting.

async def reserve_and_charge(order_id: int) -> None:
    reservation = await stock_api.reserve(order_id)
    charged = False
    try:
        await payment_api.charge(order_id)
        charged = True
    finally:
        if not charged:
            # on an error AND on cancel
            await stock_api.release(reservation)
  1. CancelledError is a BaseException, not an Exception (since Python 3.8). So an except Exception block does not catch it. This is on purpose: normal error handling must not stop a cancel.
  2. Do not swallow CancelledError. If you catch it to clean up, raise it again. Otherwise the task looks finished, and timeouts and TaskGroups stop working correctly.
  3. Put cleanup in finally, or in async with blocks. They run on cancellation too. In the code above, the stock is released if the payment fails or if the task is cancelled during the charge call. With only an except Exception block, a cancel would leave the stock reserved.

Limit how much runs at once

Starting 10,000 tasks at once is easy. But the other service may not accept 10,000 connections. A Semaphore lets only N tasks into a block at the same time:

limit = asyncio.Semaphore(20)

async def get_price_limited(
    client: httpx.AsyncClient, sku: str,
) -> float:
    # at most 20 calls at the same time
    async with limit:
        return await get_price(client, sku)

Common mistakes

Mistake Result Better way
Calling a coroutine without await Nothing runs. A “never awaited” warning. Await it, or make it a task.
await, await, await for calls that do not depend on each other The waits add up. A TaskGroup.
time.sleep or a sync HTTP or database library in async def Every task and request stops. Async libraries, or asyncio.to_thread.
create_task without keeping a reference The task can disappear, and its errors are lost. Keep it in a set, or use a TaskGroup.
No timeout on a network call Requests that never end. The asyncio.timeout block.
Catching CancelledError and not raising it again Timeouts and cancellation break. Clean up in finally, then let it go up.
10,000 calls started at once The other service is overloaded. A Semaphore.

Summary in 7 lines

  1. The event loop runs many tasks in one thread. A task gives control back only at an await.
  2. Calling a coroutine function only makes a coroutine. Await it, or make it a task.
  3. Calls that do not depend on each other should run together in a TaskGroup.
  4. If one task in a TaskGroup fails, the others are cancelled, and the errors come in an ExceptionGroup.
  5. A blocking call inside async code stops every task. Use async libraries or asyncio.to_thread.
  6. Put a timeout on every network call with asyncio.timeout.
  7. Never swallow CancelledError. Clean up in finally and let it go up.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.