Tutorials / Python: Intermediate to Advanced / async and await with asyncio

async and await with asyncio

15 min read python
Course contents (15 lessons)
  1. Iteration the Python way
  2. List, dict and set comprehensions
  3. Iterators and generators
  4. Functions as building blocks
  5. Closures and decorators
  6. Context managers and the with statement
  7. Object-oriented Python in depth
  8. Classes and dataclasses
  9. Properties and special (dunder) methods
  10. Inheritance versus composition
  11. Quality: types, packaging and tests
  12. Type hints and mypy
  13. Packaging a project with pyproject.toml
  14. Testing with pytest
  15. Async code and web APIs
  16. async and await with asyncio
  17. Working with HTTP APIs and JSON
  18. Performance, concurrency and a final project
  19. Performance and profiling
  20. Concurrency: threads versus processes
  21. Final project: a price tracker command-line tool

The problem async solves

Most programs spend most of their time waiting: for a web server to answer, for a database, for a disk. While one request waits, the CPU sits idle. If you must fetch 50 pages one after another and each takes half a second, you wait 25 seconds. If you could send all 50 and wait for them together, it would take about half a second.

asyncio does that inside a single thread. Your code says "I am waiting, run something else", and an event loop switches between tasks at those points. This is called cooperative multitasking.

Coroutines

A function defined with async def is a coroutine function. Calling it does not run it. It returns a coroutine object. You run it by awaiting it inside another coroutine, or by handing it to asyncio.run().

import asyncio

async def greet():
    await asyncio.sleep(1)       # pretend to wait for a network
    return "hello"

print(asyncio.run(greet()))

The await keyword means: pause here until the result is ready, and let other tasks run in the meantime. You can only use it inside an async def.

Running things at the same time

import asyncio
import time


async def fetch_price(sku: str, delay: float) -> tuple[str, float]:
    await asyncio.sleep(delay)            # stands in for a slow API call
    if sku == "BAD":
        raise ValueError("unknown sku")
    return sku, delay * 100


async def main() -> None:
    started = time.perf_counter()

    # 1. gather: run together, results come back in order
    results = await asyncio.gather(
        fetch_price("T1", 1.0),
        fetch_price("S1", 1.5),
        fetch_price("R1", 0.5),
    )
    print(results)
    print(f"gather took about {time.perf_counter() - started:.1f}s")

    # 2. TaskGroup (Python 3.11+): if one fails, the rest are cancelled
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(fetch_price("T1", 0.2))
            tg.create_task(fetch_price("BAD", 0.1))
    except* ValueError as group:
        print("failed:", [str(e) for e in group.exceptions])

    # 3. timeout (Python 3.11+)
    try:
        async with asyncio.timeout(0.3):
            await fetch_price("SLOW", 5)
    except TimeoutError:
        print("too slow, gave up")

    # 4. limit how many run at once
    gate = asyncio.Semaphore(2)

    async def limited(sku: str) -> str:
        async with gate:
            await fetch_price(sku, 0.2)
            return sku

    print(await asyncio.gather(*(limited(f"P{i}") for i in range(6))))


asyncio.run(main())

Output (the time may vary slightly):

[('T1', 100.0), ('S1', 150.0), ('R1', 50.0)]
gather took about 1.5s
failed: ['unknown sku']
too slow, gave up
['P0', 'P1', 'P2', 'P3', 'P4', 'P5']

What this shows

The three calls in the first step take 1.0, 1.5 and 0.5 seconds. Run one after another that would be three seconds. With gather the total is about 1.5, the length of the slowest one. Results come back in the same order you passed the calls, not the order they finished.

The TaskGroup is the modern and safer way to run tasks as a team. When one task fails, the group cancels the others and raises an ExceptionGroup. The except* syntax catches errors inside such a group. The timeout context manager cancels what is inside it after the time runs out. The semaphore ensures that at most two of the six tasks run the guarded part at the same time, which is important when an API limits how many requests you may send at once.

The mistakes everyone makes

  • Forgetting await. fetch_price("T1", 1) without await creates a coroutine and never runs it. Python warns "coroutine was never awaited". Treat that warning as an error.
  • Blocking the event loop. If you call time.sleep(5) or a blocking library like requests.get inside a coroutine, everything freezes, because the loop cannot switch while your code holds it. Use asyncio.sleep, an async library such as httpx or aiohttp, or push blocking work to a thread with await asyncio.to_thread(func, args).
  • Using async for CPU-heavy work. Computing something for ten seconds does not wait for anything, so there is nothing to switch away from. Use processes for that, which we cover later in this course.
  • Creating tasks and losing them. If you call asyncio.create_task(...) and keep no reference, the task can be garbage-collected before it finishes. Keep references, or use a TaskGroup.
  • Calling asyncio.run() inside a running loop, which happens in notebooks and some frameworks. There, just await directly.

Async everywhere is contagious

A normal function cannot await. Once one function in a call chain is async, the callers up the chain must be too, until you reach asyncio.run(). That is why frameworks like FastAPI are async from the top. Do not rewrite a simple script in async form for no reason. If you have only a few slow calls, a thread pool is often simpler. Async pays off when you have many waiting operations at once, such as hundreds of connections.

Async iteration and context managers

You will also see async for and async with. They work like their normal versions but can await at each step. A typical example is streaming a large response line by line. Async generators use async def with yield.

Try it yourself

Write an async function check_site(name, delay) that sleeps and then returns a string such as "name: ok". Run ten of them with gather and compare the total time against running them in a normal loop. Then limit concurrency to three with a semaphore, and add a one-second timeout so that slow ones are reported as failed rather than hanging the whole program.

python
import asyncio
import time


async def fetch_price(sku: str, delay: float) -> tuple[str, float]:
    await asyncio.sleep(delay)            # stands in for a slow API call
    if sku == "BAD":
        raise ValueError("unknown sku")
    return sku, delay * 100


async def main() -> None:
    started = time.perf_counter()

    # 1. gather: run together, results come back in order
    results = await asyncio.gather(
        fetch_price("T1", 1.0),
        fetch_price("S1", 1.5),
        fetch_price("R1", 0.5),
    )
    print(results)
    print(f"gather took about {time.perf_counter() - started:.1f}s")

    # 2. TaskGroup (Python 3.11+): if one fails, the rest are cancelled
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(fetch_price("T1", 0.2))
            tg.create_task(fetch_price("BAD", 0.1))
    except* ValueError as group:
        print("failed:", [str(e) for e in group.exceptions])

    # 3. timeout (Python 3.11+)
    try:
        async with asyncio.timeout(0.3):
            await fetch_price("SLOW", 5)
    except TimeoutError:
        print("too slow, gave up")

    # 4. limit how many run at once
    gate = asyncio.Semaphore(2)

    async def limited(sku: str) -> str:
        async with gate:
            await fetch_price(sku, 0.2)
            return sku

    print(await asyncio.gather(*(limited(f"P{i}") for i in range(6))))


asyncio.run(main())

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account