Python Concurrency · Lesson 142 of 149

Python asyncio

What you will learn

  • Coroutines: async def and await
  • The event loop and asyncio.run
  • Running things together: gather, create_task, TaskGroup
  • Timeouts, cancelling, limiting with Semaphore
  • Queues between coroutines
  • Never blocking the loop: to_thread
  • When to choose asyncio

1. A different kind of concurrency

Threads (lesson 20.2) are switched by the system at any moment, which is why shared data needs locks. asyncio takes another route, cooperative multitasking: everything runs in one thread, and a task runs until it reaches a point where it must wait (for the network, a timer). At that point it hands control back by writing await, and the event loop runs another task. Tasks switch only at those marked points, so there are far fewer surprises, and one thread can look after thousands of waiting tasks cheaply.

It is the natural tool for programs that spend their time waiting for many network connections (web servers, chat services, crawlers, API clients). Many modern libraries are built on it.

import asyncio

2. Coroutines and await

A function defined with async def is a coroutine function. Calling it does not run it; it returns a coroutine object, a paused recipe. To run it, you await it inside another coroutine, or hand it to the event loop with asyncio.run:

async def fetch(name, seconds):
    await asyncio.sleep(seconds)          # a non-blocking wait
    return f"{name} done"


async def main():
    print("coroutine object:", type(fetch("x", 0.1)).__name__)
    a = await fetch("a", 0.3)
    b = await fetch("b", 0.3)
    print(a, b)


asyncio.run(main())
coroutine object: coroutine
a done b done

(The check run also printed a RuntimeWarning: coroutine 'fetch' was never awaited for the first line, because that call created a coroutine and never ran it. That warning is the classic sign of a forgotten await.)

Key points:

  • await can be used only inside an async def function.
  • asyncio.run(main()) starts the event loop, runs main until it finishes, and closes the loop. Call it once, at the top level.
  • asyncio.sleep(s) waits without blocking other tasks; time.sleep(s) would block everything (section 6).
  • Awaiting two coroutines one after another takes the sum of their waits: the two 0.3 s waits above took 0.60 s.
Quick check: what does calling an `async def` function without `await` give you?

A coroutine object that has not run yet (and a warning if it is never awaited).

3. Running things together

gather

asyncio.gather(*coroutines) runs them concurrently and returns their results in order:

results = await asyncio.gather(fetch("a", 0.3), fetch("b", 0.3), fetch("c", 0.3))
print(results)
['a done', 'b done', 'c done']

Three waits of 0.3 s took 0.30 s in total (check run) instead of 0.9 s. If one coroutine raises an exception, gather re-raises the first one, and you can ask it to collect errors as results instead:

async def broken():
    await asyncio.sleep(0.1)
    raise ValueError("boom")


res = await asyncio.gather(fetch("ok", 0.1), broken(), return_exceptions=True)
print(res)
try:
    await asyncio.gather(fetch("ok", 0.1), broken())
except ValueError as e:
    print("gather raised:", e)
['ok done', ValueError('boom')]
gather raised: boom

create_task

asyncio.create_task(coro) schedules a coroutine to start running right away in the background and returns a Task. You can do other things and await the task later:

task1 = asyncio.create_task(fetch("t1", 0.3))
task2 = asyncio.create_task(fetch("t2", 0.3))
print("tasks started, doing other work...")
r1, r2 = await task1, await task2
print(r1, r2)
tasks started, doing other work...
t1 done t2 done

Both ran together (0.31 s overall). Keep a reference to every task you create, or Python may discard it before it finishes.

TaskGroup (Python 3.11+)

asyncio.TaskGroup is the modern, safer way: it waits for all its tasks when the async with block ends, and if one fails it cancels the others and raises an exception group (lesson 14.7):

async with asyncio.TaskGroup() as tg:
    t_a = tg.create_task(fetch("g1", 0.2))
    t_b = tg.create_task(fetch("g2", 0.1))
print("TaskGroup:", t_a.result(), "|", t_b.result())

try:
    async with asyncio.TaskGroup() as tg:
        tg.create_task(fetch("fine", 0.3))
        tg.create_task(broken())
except* ValueError as eg:
    print("TaskGroup error group:", [str(e) for e in eg.exceptions])
TaskGroup: g1 done | g2 done
TaskGroup error group: ['boom']

4. Timeouts, cancelling and limits

Timeout: asyncio.wait_for(coro, timeout) raises TimeoutError (and cancels the coroutine) when time runs out:

try:
    await asyncio.wait_for(fetch("slow", 1.0), timeout=0.2)
except TimeoutError:
    print("wait_for timed out")
wait_for timed out

(Python 3.11 also has async with asyncio.timeout(0.2):, which covers a whole block.)

Cancelling: task.cancel() asks a task to stop; it receives a CancelledError at its next await:

task = asyncio.create_task(fetch("cancel me", 5))
await asyncio.sleep(0.1)
task.cancel()
try:
    await task
except asyncio.CancelledError:
    print("task cancelled:", task.cancelled())
task cancelled: True

Limiting concurrency: starting 10,000 requests at once would flood a server. An asyncio.Semaphore(n) lets at most n tasks into a section at the same time:

sem = asyncio.Semaphore(2)
active, peak = 0, 0


async def limited(i):
    global active, peak
    async with sem:
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.1)
        active -= 1
        return i


out = await asyncio.gather(*(limited(i) for i in range(6)))
semaphore(2) with 6 jobs: 0.33 s, peak at once: 2 [0, 1, 2, 3, 4, 5]

Six jobs of 0.1 s, two at a time, took three rounds (0.33 s), and the peak never exceeded 2. (The check used nonlocal inside main; at module level global does the same.)

Queues: asyncio.Queue passes items between coroutines, like queue.Queue between threads:

q = asyncio.Queue()
got = []


async def producer():
    for i in range(4):
        await q.put(i)
        await asyncio.sleep(0.05)
    await q.put(None)


async def consumer():
    while (item := await q.get()) is not None:
        got.append(item * 10)


await asyncio.gather(producer(), consumer())
print("queue:", got)
queue: [0, 10, 20, 30]

5. Async code and ordinary code

Only awaitable operations let other tasks run. Ordinary blocking functions (time.sleep, requests.get, reading a big file, heavy calculation) freeze the entire loop:

async def blocker():
    time.sleep(0.3)            # BAD: blocks the whole event loop


await asyncio.gather(blocker(), blocker(), blocker())
three time.sleep(0.3) inside coroutines: 0.90 s

Three "concurrent" calls took 0.90 s, the sum, because each time.sleep held the loop. The cures:

  1. Use an async-aware library (asyncio.sleep, aiohttp or httpx for HTTP, async database drivers).
  2. Run the blocking function in a thread with asyncio.to_thread:
await asyncio.gather(asyncio.to_thread(time.sleep, 0.3), asyncio.to_thread(time.sleep, 0.3))
two blocking sleeps via to_thread: 0.31 s
  1. For heavy computing, use a process pool (loop.run_in_executor with a ProcessPoolExecutor, lesson 20.4).

async is contagious: a function that awaits must itself be async, and so on up to asyncio.run. Mixing sync and async code in one program takes care, and the standard library's urllib (lesson 17.11) is blocking, so real async programs use async libraries.

6. asyncio, threads or processes?

Threads asyncio Processes
good for a moderate number of waits, blocking libraries very many waits (thousands), async libraries CPU-bound work
switching by the system, any time only at await by the system
shared data needs locks far fewer races (single thread) not shared
cost per task a thread (memory) tiny a whole process
learning curve medium steeper (async everywhere) medium

Rule of thumb: start with concurrent.futures (lesson 20.4). Choose asyncio for network servers and clients that handle very many connections, or when the libraries you need are async.

Worked example: an API client with a limit, a timeout and a retry

Twenty "API calls" (simulated with random waits) run at most five at a time. One item fails once and is retried; one hangs for 2 seconds and is given up on after a 1-second timeout. Errors are returned instead of crashing the whole batch.

import asyncio
import random
import time

attempts = {}


async def call_api(item):
    """Pretend network call: random delay, and item 7 fails the first time."""
    rng = random.Random(item)
    await asyncio.sleep(rng.uniform(0.1, 0.4))
    attempts[item] = attempts.get(item, 0) + 1
    if item == 7 and attempts[item] == 1:
        raise ConnectionError("temporary failure")
    if item == 13:
        await asyncio.sleep(2)                  # this one hangs
    return item * item


async def fetch_one(item, limit, retries=2, timeout=1.0):
    async with limit:                           # at most N calls at once
        for attempt in range(1, retries + 1):
            try:
                return await asyncio.wait_for(call_api(item), timeout)
            except ConnectionError:
                if attempt == retries:
                    raise
            except TimeoutError:
                return None                     # give up on a hanging call


async def main():
    limit = asyncio.Semaphore(5)
    start = time.perf_counter()
    results = await asyncio.gather(*(fetch_one(i, limit) for i in range(1, 21)),
                                   return_exceptions=True)
    elapsed = time.perf_counter() - start
    good = [r for r in results if isinstance(r, int)]
    print(f"20 calls, 5 at a time: {elapsed:.2f} s")
    print("answers:", len(good), "| timed out:", results.count(None),
          "| errors:", [r for r in results if isinstance(r, Exception)])
    print("item 7 needed", attempts[7], "attempts; results[6] =", results[6])
    print("sum of delays if one by one would be about",
          round(sum(random.Random(i).uniform(0.1, 0.4) for i in range(1, 21)), 1), "s")


asyncio.run(main())
20 calls, 5 at a time: 1.54 s
answers: 19 | timed out: 1 | errors: []
item 7 needed 2 attempts; results[6] = 49
sum of delays if one by one would be about 4.8 s
Part Idea
Semaphore(5) never more than five calls in flight
wait_for(..., timeout) the hanging item 13 is cut off after 1 s, so one slow call cannot stall the batch
the retry loop item 7 failed once, succeeded on attempt 2 (results[6] is 49)
return_exceptions=True one failure could not hide the other results
1.54 s against about 4.8 s the waits overlapped; the hang plus the limit set the total

Everything is simulated: no network was used. The random delays are seeded by item number, so the run is repeatable apart from small timing differences.

Common mistakes

  • Forgetting await (the coroutine never runs; a RuntimeWarning appears).
  • Calling blocking functions (time.sleep, requests) inside coroutines.
  • Calling asyncio.run inside a running loop (for example in Jupyter, which has its own loop: use await directly).
  • Creating tasks and losing the reference.
  • Starting unlimited tasks instead of using a Semaphore.
  • Heavy computing inside a coroutine, freezing every other task.
  • Ignoring exceptions in background tasks.
  • Mixing threads and the event loop without to_thread or call_soon_threadsafe.

Key takeaways

  • async def defines a coroutine; await pauses it until something is ready, letting other tasks run; asyncio.run(main()) starts the event loop.
  • gather, create_task and TaskGroup run coroutines concurrently in a single thread; wait_for / timeout add time limits, and Semaphore limits concurrency.
  • Blocking calls freeze the entire loop: use async libraries, asyncio.to_thread, or a process pool.
  • asyncio shines with thousands of waiting connections; for moderate I/O or CPU work, concurrent.futures is usually simpler.

Practice

1. What happens when you call fetch("a", 1) without await or create_task?

Show answer

Nothing runs; you get a coroutine object, and Python warns that it was never awaited.

2. Why did three time.sleep(0.3) calls in coroutines take 0.9 s under gather?

Show answer

time.sleep blocks the single thread running the event loop, so no other task can run; use await asyncio.sleep instead.

3. What does asyncio.gather(a(), b()) return?

Show answer

A list with the results of a() and b(), in that order, after both finish.

4. How do you stop 1,000 coroutines from all hitting a server together?

Show answer

Wrap the call in async with asyncio.Semaphore(n): so only n run at once.

5. How can you run a blocking function without freezing the event loop?

Show answer

await asyncio.to_thread(function, *args) (or run it in an executor).

6. When would you choose asyncio over threads?

Show answer

When handling very many simultaneous waiting connections, or when your libraries are async; for a modest number of blocking calls, threads are simpler.