01C.2 Synchronous vs Asynchronous Programming and the asyncio Event Loop

FoundationsLesson 2 of 718,734 words10 parts
Module 01C · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7

01B.3 taught you how to use async and await: write the coroutines, fan them out, time them out, cancel them. This lesson opens the box. We ask what a synchronous program and an asynchronous program really are as programming models, what a coroutine is underneath (a generator in disguise), what an asyncio event loop does on every single iteration, and what Future, Task and Handle objects are for. To prove we understand it, we write a working event loop of about seventy lines that runs real async def coroutines, and then we compare it with the real one in the standard library. Along the way we cover cancellation and timeouts at the level of mechanism, crossing the thread boundary, contextvars, debug mode, the new introspection tools in Python 3.14, and an honest account of when async is not worth it. Everything runs on the standard library alone: no API key, no packages, no network. Every Output: block in this lesson comes from a script shown in the lesson, run for real.

What you'll learn

  • Sync vs async as programming models: a blocked call stack versus a suspended one, and why callbacks, promises and async/await are three spellings of the same idea
  • Why a coroutine is a generator: send(), StopIteration.value, yield from, await desugaring, __await__, and what a suspended await chain looks like from the inside
  • The three objects the loop schedules: Handle (a callback), Future (a promise of a result) and Task (a coroutine driver), and the exact order in which they run
  • One iteration of the event loop: the ready queue, the timer heap, the selector, and the three phases of _run_once
  • A hand-written mini event loop (timers, sockets, tasks) that runs real coroutines, and what the real loop adds on top
  • Awaitables and the async protocols: __await__, __aiter__/__anext__, async with, async generators and their finalization
  • How asyncio.run and asyncio.Runner start and stop a loop; the event-loop-policy deprecation in Python 3.14
  • Cancellation and timeouts as mechanism: CancelledError, cancelling()/uncancel(), how asyncio.timeout is built
  • Crossing the thread boundary: call_soon_threadsafe, run_coroutine_threadsafe, to_thread, bridging callback APIs, and how contextvars travel
  • Debug mode, eager tasks (3.12), asyncio call-graph introspection (3.14), and a gallery of loop-level bugs with their real messages
  • Sync vs async in web frameworks (WSGI vs ASGI) and a decision table: when async is the right tool and when it is not
  • uvloop, trio and anyio: what they change and what they do not

What you don't need

  • Mastery of the asyncio API. This lesson assumes you have met async def, await, create_task and gather; if not, read 01B.3 first (or alongside). We link to its sections instead of repeating them.
  • The definitions of concurrency, parallelism, I/O-bound and CPU-bound work, blocking calls and context switching. 01C.1 owns those.
  • Threads, locks and the GIL in depth: 01C.3 and 01C.5 own them.
  • An API key, a provider SDK, or any installed package.

Setup

You need Python 3.11 or newer (3.13 or 3.14 recommended). Check your version:

bash
python3 --version
powershell
py --version

Save each snippet as a .py file and run it with python3 file.py (Windows: py file.py). No API key needed. Every Output: block below came from Python 3.14.6 on macOS (a GIL-enabled build); the examples avoid timings, so you should see the same lines on 3.11 or newer. Where a feature needs a newer Python (eager tasks need 3.12, the call-graph tools need 3.14), the text says so. The version map near the end of Part 5 lists what each release changed for this topic (as of November 2026, Python 3.15 is current). Values that depend on your machine (such as the name of the selector in use) are labelled illustrative.


What you must be able to do after this lesson#

  • Explain sync and async as programming models
  • Explain why a coroutine is a generator in disguise
  • Tell apart Handle, Future and Task
  • Describe what one event loop iteration does
  • Cancel a task and apply a timeout correctly
  • Call into the event loop from another thread safely
  • Decide when async is the right tool and when it is not

Why this matters for an AI engineer#

An AI service is a loop around slow network calls: embed, retrieve, generate, call a tool, stream tokens back. Almost every bug that appears only under load (a frozen server, a lost background task, a request that cannot be cancelled, a timeout that never fires) comes from a wrong mental model of what the event loop is doing. You will hear:

You'll hear... You'll understand it after...
"Async is just a faster threading" Part 1 and 10.4
"A coroutine is a generator" Part 2
"create_task schedules it, it doesn't run it" 3.3 and 3.5
"The event loop is single-threaded, so there are no race conditions" 4.2 and 9.3
"One blocking call freezes every request" 4.5 and 9.2
"Don't call loop.call_soon from another thread" Part 7
"wait_for / timeout cancels the task" Part 6
"Set a ContextVar for the request ID" 7.4
"Use uvloop / trio / anyio" 10.5
"Why does FastAPI use ASGI?" 10.2

Part 1: Sync and async as programming models#

1.1 A blocked call stack versus a suspended one#

Both models solve the same problem: your program has to wait for something slow (a model's reply, a database row, a webhook) and you would like to do other useful work in the meantime. The difference is what happens to the function that is waiting.

In a synchronous program, a function that calls something slow simply does not return until it is done. The call stack of the thread is frozen on that line. The thread cannot do anything else; the operating system parks it, and it has to be woken again when the answer arrives. If you want to wait for two things at once, you need two threads, each with its own frozen stack.

In an asynchronous program, a function that has to wait gives up the thread instead of freezing it. It records where it was, returns control to a scheduler, and asks to be resumed when the answer is ready. The thread stays free. The scheduler can resume a different function in the meantime, so many functions can be "waiting" while a single thread runs.

An analogy. A synchronous waiter takes your order, walks to the kitchen, stands at the pass until your dish is ready, and carries it back; only then does he talk to the next table. An asynchronous waiter takes your order, hangs the ticket on the kitchen rail, and goes to the next table; when the kitchen rings the bell she picks up whichever dish is ready. Same restaurant, same kitchen speed, very different number of customers served per waiter. (A third option, hiring more waiters, is threads: it works, but each waiter has a salary: see 01C.1 for what a thread costs.)

The asynchronous waiter has a rule that the synchronous one does not: she must never stand and wait herself. If she decides to chat with one customer for ten minutes (a CPU-heavy loop, a blocking call), every other table is stranded. That rule, "never block the scheduler", is the price of the model, and most of the bugs in this lesson are violations of it.

1.2 One job, three models#

Here is the same job written the three ways Python offers for waiting concurrently: fetch the summaries of four support tickets, where each fetch is a slow call (faked with a sleep, so the example needs no network).

python
# e01_three_styles.py: the same job (summarise 4 support tickets) written three ways.
import asyncio
import threading
import time

TICKETS = {"T-1": 0.04, "T-2": 0.01, "T-3": 0.03, "T-4": 0.02}  # fake latency in seconds


def summarise_sync(ticket: str) -> str:
    time.sleep(TICKETS[ticket])  # blocks the whole thread
    return f"{ticket}: summary"


def run_sync() -> list[str]:
    return [summarise_sync(t) for t in TICKETS]


def run_threads() -> list[str]:
    results: dict[str, str] = {}

    def worker(ticket: str) -> None:
        results[ticket] = summarise_sync(ticket)  # each thread blocks alone

    threads = [threading.Thread(target=worker, args=(t,)) for t in TICKETS]
    for th in threads:
        th.start()
    for th in threads:
        th.join()
    return [results[t] for t in TICKETS]


async def summarise_async(ticket: str) -> str:
    await asyncio.sleep(TICKETS[ticket])  # suspends only this coroutine
    return f"{ticket}: summary"


async def run_async() -> list[str]:
    return list(await asyncio.gather(*(summarise_async(t) for t in TICKETS)))


if __name__ == "__main__":
    for name, fn in [("sync", run_sync), ("threads", run_threads), ("async", lambda: asyncio.run(run_async()))]:
        start = time.perf_counter()
        out = fn()
        elapsed = time.perf_counter() - start
        # Sequential would take ~0.10 s; concurrent ~0.04 s. Print only a coarse verdict.
        verdict = "about the sum of the waits" if elapsed > 0.085 else "about the longest wait"
        print(f"{name:8} {out} -> {verdict}")
Output3 lines
sync     ['T-1: summary', 'T-2: summary', 'T-3: summary', 'T-4: summary'] -> about the sum of the waits
threads  ['T-1: summary', 'T-2: summary', 'T-3: summary', 'T-4: summary'] -> about the longest wait
async    ['T-1: summary', 'T-2: summary', 'T-3: summary', 'T-4: summary'] -> about the longest wait

Read what each version does with the waiting:

Model Who waits What a "pending call" is How many can be pending
Sequential (sync) the one thread, blocked a frozen call-stack frame one
Threads (sync, concurrent) each OS thread, blocked one frozen thread (stack plus kernel object) as many as you can afford threads
asyncio (async) nobody: the coroutine is suspended a small heap object (a coroutine frame) as many as you have memory for

The threaded and async versions finish in about the time of the slowest ticket, not the sum. But the price differs. A thread is a unit of the operating system: it has its own stack, it is scheduled by the kernel, and switching between threads goes through the kernel. A suspended coroutine is an ordinary Python object on the heap, and resuming it is an ordinary function call. That is the entire reason one async thread can hold ten thousand pending calls (4.4 shows ten thousand tasks completing on one thread).

The cost of that cheapness is the cooperative rule from 1.1. Threads are preemptive: the OS can pause a thread at almost any instruction and run another. Coroutines are cooperative: a coroutine is only paused where it writes await. You gain predictability (nothing interrupts you between two awaits, see 9.3) and you lose protection (nothing interrupts a coroutine that refuses to await).

1.3 How we got here: callbacks, promises, async/await#

Asynchronous programming did not start with async def. The history is worth knowing because each stage is still inside what you run today, and the vocabulary (callback, future, promise, coroutine) comes from different stages.

Stage 1: callbacks. You hand the framework a function and say "call this when the data is ready". Control flow is inverted: you no longer call the next step, the framework does. Our two-step flow (fetch a user, then fetch that user's orders) in callback style:

python
# e02_callbacks_vs_await.py: the same three-step flow as callbacks and as await.
import asyncio


def fetch_user(loop: asyncio.AbstractEventLoop, then) -> None:
    loop.call_later(0.01, then, {"id": 7, "name": "Asha"})


def fetch_orders(loop: asyncio.AbstractEventLoop, user: dict, then) -> None:
    loop.call_later(0.01, then, [101, 102])


def callback_style(loop: asyncio.AbstractEventLoop, done: asyncio.Future) -> None:
    def on_user(user: dict) -> None:
        def on_orders(orders: list[int]) -> None:
            done.set_result(f"{user['name']} has orders {orders}")  # the "pyramid"
        fetch_orders(loop, user, on_orders)
    fetch_user(loop, on_user)


async def fetch_user_async() -> dict:
    await asyncio.sleep(0.01)
    return {"id": 7, "name": "Asha"}


async def fetch_orders_async(user: dict) -> list[int]:
    await asyncio.sleep(0.01)
    return [101, 102]


async def await_style() -> str:
    user = await fetch_user_async()
    orders = await fetch_orders_async(user)
    return f"{user['name']} has orders {orders}"


async def main() -> None:
    loop = asyncio.get_running_loop()
    done = loop.create_future()
    callback_style(loop, done)
    print("callbacks:", await done)
    print("await    :", await await_style())


asyncio.run(main())
Output2 lines
callbacks: Asha has orders [101, 102]
await    : Asha has orders [101, 102]

Look at callback_style: each dependent step nests one level deeper (the "pyramid of doom"), error handling has to be threaded through every callback, a try/except around the call does nothing because the function has already returned by the time the callback fires, and a loop ("fetch all orders, one at a time") needs recursion or manual state machines.

Stage 2: futures and promises. Instead of passing a callback in, the call returns an object that stands for the eventual result, which you can pass around, combine, chain and attach callbacks to (add_done_callback). This is asyncio.Future, JavaScript's Promise, Java's CompletableFuture. It flattens the pyramid but code still reads as a chain of .then(...) calls.

Stage 3: coroutines, async/await. The function is written as ordinary straight-line code. The keyword await marks the lines where it may be suspended, and the compiler turns the function into a state machine (a generator, Part 2) that the loop resumes when the Future it awaits completes. await_style above is the same flow, with ordinary try/except, ordinary loops and ordinary variables.

The important sentence: async/await did not add a new execution model to Python; it is syntax that lets you write the callback-and-future model as straight-line code. Under every await there is still a Future and a callback that resumes the coroutine. Part 3 shows those objects, and Part 4 shows the loop that fires the callbacks.

1.4 What "synchronous" really costs, and what "asynchronous" really costs#

Before the internals, set honest expectations. Neither model is free.

Aspect Synchronous (thread per task) Asynchronous (asyncio)
Readability the plainest; stack traces are whole straight-line with await, but stack traces are loop-shaped and "colour" splits your code (01B.3, 6.3)
Memory per pending task an OS thread: reserved stack, kernel structures (typically hundreds of KB to MB of address space) a coroutine frame and a Task object: typically a few KB
Maximum concurrent waits hundreds to a few thousand, before scheduling and memory hurt tens of thousands or more on one thread
CPU-bound work threads do not help in standard CPython (GIL: 01C.5); processes do blocks the loop completely; must be moved off (Part 7)
Interruption preemptive: the OS can switch between any two bytecodes, so shared data needs locks (01C.3) cooperative: switches only at await, so many races vanish, but not all (9.3)
Libraries the whole synchronous ecosystem works as is needs async-aware libraries; one sync call inside blocks everyone
Debugging any debugger and profiler works, with extra tooling (Part 8)

Magnitudes such as "KB per task" are typical orders of magnitude that depend on the platform and Python version; measure your own with tracemalloc before you plan around them. The decision of which to use is in 10.4.


Part 2: Coroutines are generators in disguise#

Deep-dive

2.1 What happens when you call an async def function#

01B.3, 2.1 showed that calling an async def function does not run its body: it returns a coroutine object. Now we find out what that object is and how anything ever runs it.

A coroutine object is a frame that can be paused and resumed: the function's local variables, its position in the code, and a few methods: send(value), throw(exc) and close(). Those are exactly the methods a generator has. They are the same machinery in the interpreter: async def compiles to a variant of generator code with a different flag, and await compiles to a variant of yield from. If you read the generators lesson (01A.5, Part 3) you already know the mechanics.

To prove it, here is a coroutine driven by hand, with no event loop at all.

python
# e03_coroutine_by_hand.py: drive a real coroutine with send(), no event loop at all.
import types


@types.coroutine
def pause(label: str):
    # A bare generator-based awaitable: yielding hands control to whoever drives us.
    reply = yield label
    return f"resumed with {reply!r}"


async def worker() -> str:
    first = await pause("waiting for the network")
    second = await pause("waiting for the disk")
    return f"{first} / {second}"


coro = worker()
print("type:", type(coro).__name__)
print("step 1 yielded:", coro.send(None))   # runs until the first yield
print("step 2 yielded:", coro.send("A"))    # resumes the first await
try:
    coro.send("B")                          # finishes the coroutine
except StopIteration as stop:
    print("StopIteration.value:", stop.value)
Output4 lines
type: coroutine
step 1 yielded: waiting for the network
step 2 yielded: waiting for the disk
StopIteration.value: resumed with 'A' / resumed with 'B'

Walk through it:

  1. worker() returns a coroutine; nothing has run.
  2. coro.send(None) starts it. (The first send must be None, exactly as with a generator.) It runs until it reaches the first real suspension, here the yield label inside pause, and that value comes out of send() as its return value.
  3. coro.send("A") resumes the coroutine at the yield, and "A" becomes the value of the yield expression (the reply).
  4. When the coroutine returns, send raises StopIteration and the function's return value is in stop.value. That is how a generator-based coroutine hands back its result.

@types.coroutine is the small stdlib decorator that lets a plain generator function be awaited. Real libraries almost never write it, but it exposes the key point: the only thing that makes a coroutine suspend is a yield at the bottom of an await chain. The event loop is a program that calls send() over and over. Everything else (Tasks, Futures, the ready queue) is bookkeeping around that one call.

2.2 await is yield from with a type check#

When coroutine outer does await inner(), the interpreter does what yield from inner() would: it drives inner itself, and anything inner yields is passed straight through outer up to whoever called send() on outer. When inner returns, its return value becomes the value of the await expression. This is why a whole chain of awaits (a request handler awaiting a client awaiting a transport awaiting a socket) is a single resumable unit from the loop's point of view: one send() at the top resumes the innermost suspended frame directly.

What can you await? Anything with an __await__ method that returns an iterator. The standard library recognises three kinds: coroutine objects, objects that define __await__ (this includes Future and Task), and generator-based coroutines (a generator function decorated with types.coroutine, the legacy spelling that our hand-made examples below use). Let us inspect a suspended chain and write our own awaitable.

python
# e04_await_desugar.py: await is yield from over __await__; inspect a suspended chain.
import inspect


class Ticker:
    """A custom awaitable: __await__ must return an iterator."""
    def __init__(self, n: int) -> None:
        self.n = n

    def __await__(self):
        for i in range(self.n):
            yield f"tick {i}"           # suspends the whole await chain
        return "ticker done"


async def inner() -> str:
    return await Ticker(2)


async def outer() -> str:
    return await inner()


c = outer()
print(inspect.getcoroutinestate(c))                 # CORO_CREATED
print(c.send(None), "|", inspect.getcoroutinestate(c))   # CORO_SUSPENDED
# The await chain is visible through cr_await:
print("outer awaits:", c.cr_await.cr_code.co_name)
print("inner awaits:", type(c.cr_await.cr_await).__name__)
print(c.send(None))
try:
    c.send(None)
except StopIteration as stop:
    print("result:", stop.value, "|", inspect.getcoroutinestate(c))
Output6 lines
CORO_CREATED
tick 0 | CORO_SUSPENDED
outer awaits: inner
inner awaits: generator
tick 1
result: ticker done | CORO_CLOSED

Three observations:

  • inspect.getcoroutinestate reports the lifecycle: CORO_CREATED (not started), CORO_SUSPENDED (paused at an await), CORO_RUNNING, CORO_CLOSED.
  • cr_await shows what a suspended coroutine is currently waiting on. Follow it down and you get the async call stack: outer waits on inner, which waits on the Ticker iterator. This is exactly the data that Python 3.14's asyncio introspection tools read (Part 8), and it is what a debugger shows you under "awaiting".
  • Ticker.__await__ is a generator, so each yield suspends the entire chain, however deep it is, and the return becomes the result. A custom awaitable like this is the low-level way to build primitives.

2.3 Why the chain is cheap#

The cost model follows directly:

  • A suspension is a yield. It does not copy a stack or enter the kernel. It returns a value up a chain of frames that are already linked.
  • A resumption is a send. One Python-level call at the top, which delegates down the await chain one level at a time to the innermost frame. Each level is a cheap interpreter-internal hop, but the cost does grow with the depth of the chain, so very deep await stacks are not free.
  • A pending coroutine is a heap object holding its locals and its place in the code.

So the switching cost of async is that of a handful of function calls (microseconds at most, usually far less), against a thread switch that goes through the kernel scheduler (01C.1 puts numbers on both). Mind what is not free: each awaited chain still has to be resumed by the loop, and every wake-up goes through the ready queue and a few Python-level (or C-level) steps. Async switches are cheaper than threads in memory and kernel objects, and rarely involve a thread wake-up; per hand-off through the event loop they cost a few microseconds of Python work, comparable to a thread hand-off (measured in 01C.1). Neither is as cheap as a plain function call.

2.4 What this means for an AI engineer#

  • The mental picture "a chain of coroutines is one resumable unit" explains streaming: an async for over a provider's token stream is a loop that suspends at each network read and resumes when a chunk arrives (5.2, 03.3 Part 10).
  • It explains why forgetting an await produces no error but a reply that is a coroutine object instead of text: you printed the frame, not the result.
  • It tells you where profilers and tracing see "awaiting": at the cr_await chain, not on a thread stack (11A.1 covers tracing; the instrumentation rides on the same contextvars machinery as 7.4).

Part 3: Handle, Future and Task: the loop's vocabulary#

The loop schedules three kinds of things. Knowing which is which removes most of the mystery from asyncio documentation.

Object What it is Created by Runs when
Handle / TimerHandle one scheduled callback (a function plus arguments plus a context) loop.call_soon, call_later, call_at when the loop pops it from the ready queue
Future a promise: a slot that will hold a result or an exception, plus a list of callbacks to fire when it is filled loop.create_future(); also returned by run_in_executor it does not run; it completes
Task a Future that drives a coroutine: it calls send() on it, step by step asyncio.create_task, TaskGroup.create_task, gather on bare coroutines each step is a Handle on the ready queue

3.1 Handle: one scheduled callback#

The lowest level of the loop is not coroutines but callbacks. loop.call_soon(fn, *args) appends fn(*args) to the ready queue and returns a Handle; loop.call_later(delay, fn, *args) and loop.call_at(when, fn, *args) put it on a timer heap and return a TimerHandle. The official guarantees, from the event-loop documentation: callbacks run in the order they were registered, each exactly once; if two timers are due at exactly the same time, their order is undefined; loop.time() uses a monotonic clock, so call_at takes loop time, not wall-clock time; and call_soon is not thread-safe (Part 7).

A Handle has cancel() and cancelled(): a cancelled handle stays in its queue but is skipped when its turn comes. It also carries a contextvars.Context (by default a copy-on-schedule of the current context; see 7.4).

Here is the order in which things run, on the real loop:

python
# e05_handle_ordering.py: what order do ready callbacks, timers and Future callbacks run in?
import asyncio


async def main() -> None:
    loop = asyncio.get_running_loop()
    log: list[str] = []

    h = loop.call_soon(log.append, "soon-A")
    loop.call_soon(log.append, "soon-B")
    cancelled = loop.call_soon(log.append, "soon-CANCELLED")
    cancelled.cancel()
    loop.call_later(0, log.append, "later-0")   # due now, but queued behind callbacks already in the ready queue
    loop.call_at(loop.time() + 0.02, log.append, "at-20ms")
    loop.call_later(0.01, log.append, "later-10ms")

    fut = loop.create_future()
    fut.add_done_callback(lambda f: log.append("future-callback"))
    fut.set_result(1)            # does NOT run the callback now: it is queued with call_soon
    log.append("after-set_result")

    print(type(h).__name__, "| cancelled handle:", cancelled.cancelled())
    await asyncio.sleep(0.05)
    print(log)


asyncio.run(main())
Output2 lines
Handle | cancelled handle: True
['after-set_result', 'soon-A', 'soon-B', 'future-callback', 'later-0', 'later-10ms', 'at-20ms']

Four facts are visible in that one line:

  1. call_soon never runs the callback now. 'after-set_result' (an ordinary line of the coroutine) comes first, because the coroutine is currently running: nothing else, not even a callback that is already ready, can run until it reaches an await.
  2. Ready callbacks run in FIFO order, and a cancelled one is skipped.
  3. Future.set_result does not run its callbacks immediately either; it schedules each with call_soon. That is why 'future-callback' lands after soon-A and soon-B (which were queued earlier), not at the set_result line.
  4. A timer that is already due (call_later(0, ...)) goes behind the callbacks that are already in the ready queue, and timers run in time order after that. 4.1 explains why: due timers are appended to the ready queue during the iteration.

3.2 Future: a promise with callbacks#

An asyncio.Future is an object with three states: pending, finished (with a result or an exception) and cancelled. You complete it with set_result(value) or set_exception(exc); you read it with result() (which raises if the future finished with an exception, or was cancelled, and raises InvalidStateError if it is still pending); and you can register add_done_callback(fn), which the loop calls (through call_soon, as shown above) when the future completes.

To make a future await-able, Future.__await__ does just this: if the future is not done, it yields itself (after setting an internal flag, _asyncio_future_blocking, to True), and when it is resumed, it returns self.result(). The Task that is driving the coroutine receives the yielded future out of send(), and that is the entire interface between a coroutine and the loop. 5.1 shows the Task's side of that contract with real messages.

Three practical rules follow:

  • Create futures with loop.create_future(), not by calling asyncio.Future() directly, so that the loop (or uvloop) can supply its own, faster implementation.
  • Futures belong to one loop and one thread. They are not thread-safe. If a callback runs on another thread, hop onto the loop thread first with call_soon_threadsafe (7.3).
  • An asyncio.Future is not a concurrent.futures.Future. The latter is the thread-world object (what ThreadPoolExecutor.submit returns): its .result() blocks the calling thread and it is thread-safe. The asyncio one cannot block (you await it) and is not thread-safe. loop.run_in_executor converts between them for you, and asyncio.wrap_future does so by hand.

3.3 Task: a coroutine with a driver#

A Task is a Future subclass that wraps a coroutine and drives it: its job is to call coro.send(None), look at what comes out, and arrange to be called again. Two methods in CPython's tasks.py do it: __step (run the coroutine until its next suspension) and __wakeup (a done-callback that calls __step again when the awaited future completes). The essential behaviour, verified against the CPython 3.14.6 source:

  1. At construction, the Task schedules its first step with loop.call_soon. It does not run the coroutine yet (unless eager, 3.5).
  2. A step is coro.send(None). If the coroutine returns (StopIteration), the Task's own result is set to stop.value; if it raises, the exception is stored on the Task; if it raises CancelledError, the Task becomes cancelled.
  3. If the coroutine yields a Future, the Task registers __wakeup as a done-callback on it and stops. Nothing is scheduled: the task is simply parked until that future completes.
  4. If the coroutine yields None (a bare yield, which is what asyncio.sleep(0) does), the Task reschedules __step with call_soon: "run me again on the next iteration".
  5. Anything else is a protocol error, reported as a RuntimeError thrown back into the coroutine (5.1).
python
# e06_task_first_step.py: create_task schedules the first step; it does not run it yet.
import asyncio


async def child(name: str, log: list[str]) -> None:
    log.append(f"{name}: start")
    await asyncio.sleep(0)       # yield to the loop once
    log.append(f"{name}: end")


async def main() -> None:
    log: list[str] = []
    t1 = asyncio.create_task(child("A", log))
    t2 = asyncio.create_task(child("B", log))
    log.append("main: tasks created")
    print("right after create_task, t1.done() is", t1.done())
    await asyncio.gather(t1, t2)
    for line in log:
        print(line)


asyncio.run(main())
Output6 lines
right after create_task, t1.done() is False
main: tasks created
A: start
B: start
A: end
B: end

create_task returned immediately and the log shows main: tasks created before either child started: scheduling, not running. Then the loop ran A's first step up to sleep(0), then B's first step; both yielded None, were rescheduled, and finished in the same order. This interleaving at await points, in FIFO order, is the whole of "concurrency" on one loop.

3.4 A whole await asyncio.sleep(...), end to end#

Putting Handle, Future and Task together, here is everything that happens when a task awaits a one-second sleep. This is the core of the whole lesson; if you understand this diagram, you understand asyncio.

sequenceDiagram
    participant L as Event loop
    participant T as Task
    participant C as Coroutine chain
    participant F as Future (inside sleep)
    L->>T: run __step (a Handle from the ready queue)
    T->>C: coro.send(None)
    C->>F: sleep() creates a Future and calls call_later(1.0, set_result)
    C-->>T: yields the Future (await suspends the whole chain)
    T->>F: add_done_callback(__wakeup), then park
    Note over L: ready queue empty: select() blocks until the timer is due
    L->>F: timer fires: set_result(None)
    F->>L: call_soon(__wakeup)
    L->>T: run __wakeup (next iteration)
    T->>C: coro.send(None) resumes after the await

Three things the diagram makes obvious: the coroutine never "sleeps": it is not running at all; the timer heap is what waits, so a thousand sleeping tasks cost a thousand heap entries and one select() call; and between "timer fires" and "coroutine resumes" there is at least one more trip through the ready queue (resumption is never instantaneous, and it queues behind everything already ready).

3.5 Eager tasks: run the first step now (Python 3.12)#

By default, as we saw, a new task waits for its turn. Python 3.12 added an opt-in change: with the eager task factory a task starts executing synchronously inside create_task, runs until its first real suspension, and is only handed to the loop if it actually has to wait. If the coroutine finishes without ever suspending, no loop scheduling happens at all.

python
# e07_eager_tasks.py: eager task factory (Python 3.12+) runs the first step immediately.
import asyncio


async def child(name: str, log: list[str]) -> str:
    log.append(f"{name}: start")
    await asyncio.sleep(0)
    log.append(f"{name}: end")
    return name


async def instant(log: list[str]) -> str:
    log.append("instant: ran without ever suspending")
    return "cached"


async def scenario(eager: bool) -> list[str]:
    loop = asyncio.get_running_loop()
    loop.set_task_factory(asyncio.eager_task_factory if eager else None)
    log: list[str] = []
    t = asyncio.create_task(child("A", log))
    i = asyncio.create_task(instant(log))
    log.append(f"main: after create_task (instant done={i.done()})")
    await asyncio.gather(t, i)
    return log


for eager in (False, True):
    print(f"eager={eager}")
    for line in asyncio.run(scenario(eager)):
        print("  ", line)
Output10 lines
eager=False
   main: after create_task (instant done=False)
   A: start
   instant: ran without ever suspending
   A: end
eager=True
   A: start
   instant: ran without ever suspending
   main: after create_task (instant done=True)
   A: end

Compare the two runs. In the eager run, A: start and instant: ran without ever suspending appear before main: after create_task, and instant's task is already done() the moment create_task returns. In the default run, nothing has started when create_task returns.

This is a semantic change, which the official docs call out in these words: "Immediate execution of the coroutine is a semantic change." Code that assumes "a new task never runs before my current code reaches its next await" is silently broken by the eager factory (an ordering assumption, a lock you took, a variable you set after create_task).

When is it worth it? When many of your tasks complete without suspending: for example a cache layer where most lookups hit memory, or request handlers that usually return a cached answer. Skipping the scheduler for those saves the ready-queue round trip. It does nothing for tasks that really wait on I/O. It is opt-in (loop.set_task_factory(asyncio.eager_task_factory), or per task: asyncio.Task(coro, eager_start=True) on 3.12+, or asyncio.create_task(coro, eager_start=True) on 3.14+; on 3.12 and 3.13 create_task has no eager_start parameter and raises TypeError), and off by default. asyncio.create_eager_task_factory(custom_task_constructor) (3.12) builds a factory around your own task class. The docs warn that "the application's task execution order is likely to change". Treat it like any optimization: measure before and after, and run your test suite under it.

3.6 What this means for an AI engineer#

  • asyncio.gather(*coros) and TaskGroup.create_task wrap each coroutine in a Task, so ten thousand pending embedding calls are ten thousand Tasks, ten thousand Futures and some timers: tens of thousands of small objects, not tens of thousands of threads. That is why unbounded fan-out fits in memory and why it still needs a semaphore for the provider's sake (01B.4, Part 1).
  • Fire-and-forget tasks that log or write metrics (a classic place to lose a task to the garbage collector) need a reference; a done-callback that logs exceptions is the minimum, or you meet "Task exception was never retrieved" in production.
  • Callbacks that finish a Future from an SDK's own thread need call_soon_threadsafe (7.3).

Part 4: The event loop, one iteration at a time#

4.1 The three structures and one iteration#

The event loop has exactly three pieces of state, and one iteration is a short fixed routine.

Structure Type in CPython Holds
ready queue a collections.deque of Handles callbacks that can run now
scheduled heap a heapq min-heap of TimerHandles ordered by when callbacks that run later
selector selectors.DefaultSelector (epoll, kqueue or select) file descriptors the loop is watching for readiness

loop.run_forever() is literally "call _run_once() until someone calls stop()". Reading the CPython 3.14.6 source (asyncio/base_events.py), one iteration is:

  1. Housekeeping. Drop cancelled timers from the front of the heap (and rebuild the heap if more than half of a big heap is cancelled).
  2. Compute the poll timeout. If the ready queue is non-empty (or the loop is stopping): 0, which means "do not wait". Else if there are timers: the time until the earliest timer (capped at 24 hours). Else: None, which means "block until some I/O happens".
  3. Poll. selector.select(timeout): this is the only place the loop ever sleeps. It returns the file descriptors that became ready.
  4. Process I/O events. For each ready file descriptor, append its registered callback (a Handle) to the ready queue.
  5. Promote due timers. Pop every timer whose time has come (within one clock resolution) off the heap and append it to the ready queue.
  6. Run a snapshot of the ready queue. Take ntodo = len(ready) now, and run exactly that many handles. Anything scheduled during this phase (a call_soon from a callback, a task's next step) waits for the next iteration.
flowchart TD
    A["1. drop cancelled timers"] --> B["2. timeout = 0 if ready,<br/>else time to next timer,<br/>else None"]
    B --> C["3. selector.select(timeout)<br/>the only place the loop sleeps"]
    C --> D["4. I/O-ready callbacks appended to ready queue"]
    D --> E["5. due timers appended to ready queue"]
    E --> F["6. run ntodo = len(ready) handles<br/>(a snapshot, FIFO)"]
    F -->|"next iteration"| A

The snapshot in step 6 is the fairness rule of the loop. Because only ntodo handles run per iteration, a task that calls await asyncio.sleep(0) in a loop cannot monopolize the loop: its next step goes to the back of the queue, behind everything that was already waiting. (4.5 shows it.)

4.2 What one iteration looks like in practice#

We can watch the ordering rules from 4.1 on the real loop. This example puts four things in the system at once: two ready callbacks, a socket that already has data waiting, and a timer that is already due.

python
# e08_run_once_ordering.py: I/O readiness vs ready callbacks vs timers on the real loop.
import asyncio
import socket


async def main() -> None:
    loop = asyncio.get_running_loop()
    a, b = socket.socketpair()
    a.setblocking(False)
    b.setblocking(False)
    log: list[str] = []

    def on_readable() -> None:
        data = a.recv(100)
        log.append(f"io: read {data!r}")
        loop.remove_reader(a)

    loop.add_reader(a, on_readable)
    b.send(b"ping")                       # data is already waiting on socket a
    loop.call_soon(log.append, "ready-1")
    loop.call_later(0, log.append, "timer-0")
    loop.call_soon(log.append, "ready-2")
    await asyncio.sleep(0.01)
    print(log)
    a.close()
    b.close()


asyncio.run(main())
Output1 line
['ready-1', 'ready-2', "io: read b'ping'", 'timer-0']

The order is ready-1, ready-2 (already in the ready queue when the iteration began), then the I/O callback (appended in step 4), then the timer (appended in step 5). The two call_soon callbacks come first even though the socket was readable before they were scheduled, because step 3 only collects I/O events at the poll; the callbacks that were already in the ready queue were there before the poll happened.

Two consequences matter in practice:

  • Do not rely on the relative order of I/O callbacks and timers in the same iteration. The loop's own documentation does not promise it for same-time timers, and it is an implementation detail for I/O versus timers.
  • Everything that "just happens" in asyncio (a task wake-up, a done-callback, gather collecting results) is a Handle on this one queue, so the cost of a wake-up is one queue operation and a function call.

4.3 A mini event loop in seventy lines#

Now we write one. (The order in this example depends on gaps of 10 to 20 ms between timers; on a very busy machine it can change.) The goal is the smallest program that has the same three structures (ready deque, timer heap, selector) and runs real async def coroutines. It has a Future (with __await__), a Task (with step), and a Loop (with the three-phase iteration). The loop is the 70-or-so lines from class Future to loop = Loop(); the example coroutines follow.

python
# e10_mini_loop.py: a ~70-line event loop that runs real `async def` coroutines.
import heapq
import selectors
import socket
import time
from collections import deque


class Future:
    def __init__(self, loop):
        self.loop, self.done, self.result, self.callbacks = loop, False, None, []

    def set_result(self, value):
        self.done, self.result = True, value
        for cb in self.callbacks:               # like asyncio: callbacks go through the ready queue
            self.loop.call_soon(cb, self)

    def add_done_callback(self, cb):
        self.callbacks.append(cb)

    def __await__(self):
        if not self.done:
            yield self                           # suspend: tell the Task what we are waiting for
        return self.result


class Task(Future):
    def __init__(self, loop, coro):
        super().__init__(loop)
        self.coro = coro
        loop.call_soon(self.step, None)          # first step is scheduled, not run

    def step(self, value):
        try:
            waiting_on = self.coro.send(value)   # run until the next suspension point
        except StopIteration as stop:
            self.set_result(stop.value)          # coroutine finished: complete the Task
            return
        waiting_on.add_done_callback(lambda fut: self.step(fut.result))  # wake me up later


class Loop:
    def __init__(self):
        self.ready, self.timers, self.selector, self.counter = deque(), [], selectors.DefaultSelector(), 0

    def call_soon(self, fn, *args):
        self.ready.append((fn, args))

    def call_later(self, delay, fn, *args):
        self.counter += 1                        # tie-breaker so the heap never compares functions
        heapq.heappush(self.timers, (time.monotonic() + delay, self.counter, fn, args))

    def wait_readable(self, sock):
        fut = Future(self)
        self.selector.register(sock, selectors.EVENT_READ, fut)
        return fut

    def run_until_complete(self, coro):
        main = Task(self, coro)
        while not main.done:
            if self.ready:
                timeout = 0                                     # never sleep while work is ready
            elif self.timers:
                timeout = max(0, self.timers[0][0] - time.monotonic())
            else:
                timeout = None                                  # nothing scheduled: wait for I/O
            if self.selector.get_map():                         # 1. poll the OS
                for key, _ in self.selector.select(timeout):
                    self.selector.unregister(key.fileobj)
                    key.data.set_result(key.fileobj)
            elif timeout:
                time.sleep(timeout)                             # no sockets: just wait for the timer
            while self.timers and self.timers[0][0] <= time.monotonic():   # 2. move due timers to ready
                _, _, fn, args = heapq.heappop(self.timers)
                self.call_soon(fn, *args)
            for _ in range(len(self.ready)):                    # 3. run a snapshot of ready
                fn, args = self.ready.popleft()
                fn(*args)
        return main.result


loop = Loop()


async def sleep(delay):
    fut = Future(loop)
    loop.call_later(delay, fut.set_result, None)
    await fut


async def fake_llm(name, delay, log):
    log.append(f"{name} sent")
    await sleep(delay)
    log.append(f"{name} replied")
    return name.upper()


async def read_from_socket(sock, log):
    await loop.wait_readable(sock)
    log.append(f"socket got {sock.recv(10)!r}")


async def main():
    log = []
    a, b = socket.socketpair()
    t1 = Task(loop, fake_llm("slow", 0.04, log))
    t2 = Task(loop, fake_llm("fast", 0.01, log))
    t3 = Task(loop, read_from_socket(a, log))
    await sleep(0.02)
    b.send(b"hello")
    results = [await t1, await t2, await t3]
    a.close()
    b.close()
    return log, results


log, results = loop.run_until_complete(main())
print(log)
print(results)
Output2 lines
['slow sent', 'fast sent', 'fast replied', "socket got b'hello'", 'slow replied']
['SLOW', 'FAST', None]

The coroutines (fake_llm, read_from_socket, main) are completely ordinary async def functions that await things. The mini loop ran them, interleaved them in the order the waits resolved (slow sent, fast sent, then fast replied after 10 ms, the socket data we sent at 20 ms, and finally slow after 40 ms), and returned their results. read_from_socket returned None, hence the None in the results.

Map each piece to what you now know:

Mini-loop piece Real asyncio equivalent
Future.__await__ yields self while pending asyncio.Future.__await__ (3.2)
Future.set_result schedules callbacks with call_soon the same (the order in 3.1)
Task.__init__ calls call_soon(self.step, None) the same: the first step is scheduled, not run (3.3)
Task.step calls coro.send(value) and registers a callback on what comes out Task.__step and __wakeup
Loop.run_until_complete phases 1-2-3 _run_once steps 3, 4-5 and 6 (4.1)
timeout = 0 if self.ready the same rule: never sleep while work is ready
wait_readable registers a socket with the selector loop.add_reader / sock_recv

Try it: change fake_llm("slow", 0.04, log) to 0.005 and predict the new order before you run it. Then add a fourth coroutine that does await sleep(0) in a loop of three iterations and see that it only advances once per loop iteration. (Hint: our mini sleep(0) would still schedule a timer; the real asyncio.sleep(0) yields a bare None instead, see 4.5.)

4.4 What the real loop adds#

Real asyncio feature What it does that our mini loop does not
Cancellation task.cancel() throws CancelledError into the coroutine at its current await (Part 6)
Exception handling a failed callback or an unretrieved task exception goes to loop.call_exception_handler, which logs it
Thread-safety call_soon_threadsafe wakes a sleeping select() through a self-pipe (a socket pair the loop always watches) (Part 7)
Signals add_signal_handler (Unix) integrates SIGINT/SIGTERM into the loop
Transports and protocols the byte-level API under asyncio.open_connection, streams, subprocesses and SSL
Executors run_in_executor hands blocking work to a thread pool and a Future back
Timer housekeeping the heap is compacted when many timers are cancelled
Debug mode slow-callback logging, never-awaited origins, thread checks (Part 8)
C acceleration Future and Task are implemented in C (the _asyncio module); the pure-Python versions in tasks.py are the readable reference
Platform loops selector loop on Unix (epoll, kqueue); ProactorEventLoop (I/O completion ports) is the default on Windows since Python 3.8

The loop and selector your machine picked are queryable, and so is the cost of tasks. This script prints them and then runs ten thousand coroutines, each waiting on its own timer, on one thread.

python
# e19_loop_facts.py: which loop and selector this machine uses, and how cheap tasks are.
import asyncio
import os
import selectors
import sys


async def main() -> None:
    loop = asyncio.get_running_loop()
    print("platform:", sys.platform)
    print("loop class:", type(loop).__name__)
    print("selector:", type(loop._selector).__name__ if hasattr(loop, "_selector") else "n/a (proactor)")
    print("DefaultSelector:", selectors.DefaultSelector.__name__)
    cpus = getattr(os, "process_cpu_count", os.cpu_count)() or 1   # process_cpu_count is 3.13+
    print("default executor workers = min(32, cpu+4) ->", min(32, cpus + 4))
    await asyncio.sleep(0)
    results = await asyncio.gather(*(asyncio.sleep(0.01, result=i) for i in range(10_000)))
    print("tasks completed on one thread:", len(results))


asyncio.run(main())

The first lines depend on your platform and the executor line on your CPU count, so the output below (from a macOS machine) is labelled illustrative. The last line is the useful one.

Example output · illustrative6 lines
platform: darwin
loop class: _UnixSelectorEventLoop
selector: KqueueSelector
DefaultSelector: KqueueSelector
default executor workers = min(32, cpu+4) -> 14
tasks completed on one thread: 10000

On Linux you would see EpollSelector; on Windows the loop is the Proactor loop (which has no _selector attribute, so the script prints n/a). Because the default thread-pool executor is bounded (min(32, os.process_cpu_count() + 4) in 3.13 and 3.14, from the concurrent.futures source), a burst of to_thread or getaddrinfo calls can queue behind it. The official docs warn that name resolution (getaddrinfo) uses this same default executor, so a saturated pool shows up as "mysterious connection timeouts".

4.5 Fairness and starvation inside one loop#

Because a task runs until its next suspension, the loop is only as fair as its tasks are polite. Two experiments:

python
# e09_sleep0_fairness.py: a loop iteration runs a snapshot of the ready queue; sleep(0) yields.
import asyncio


async def chatty(name: str, n: int, log: list[str], yield_each: bool) -> None:
    for i in range(n):
        log.append(f"{name}{i}")
        if yield_each:
            await asyncio.sleep(0)       # one trip through the loop, then back in the queue


async def run(yield_each: bool) -> str:
    log: list[str] = []
    await asyncio.gather(chatty("a", 3, log, yield_each), chatty("b", 3, log, yield_each))
    return " ".join(log)


print("with sleep(0):   ", asyncio.run(run(True)))
print("without sleep(0):", asyncio.run(run(False)))
Output2 lines
with sleep(0):    a0 b0 a1 b1 a2 b2
without sleep(0): a0 a1 a2 b0 b1 b2

With await asyncio.sleep(0) between steps, the two tasks take turns (a0 b0 a1 b1 ...): each sleep(0) yields a bare None, the Task reschedules itself at the back of the ready queue (3.3 rule 4), and the other task gets a turn. Without it, a runs to completion before b ever starts: not because anything is "wrong", but because there is no suspension point to switch at.

Three rules fall out:

  • await does not necessarily yield to the loop. Awaiting a coroutine that completes without suspending (or a Future that is already done) just continues. Only a real suspension (a pending Future, or sleep(0)'s bare yield) lets other tasks run. A "polite" loop-heavy coroutine calls await asyncio.sleep(0) every so often, but see the next rule.
  • A CPU-bound loop inside a coroutine starves the loop. Chunking with sleep(0) helps fairness, but it keeps the CPU work on the loop thread and slows every other task. Real CPU work belongs in a process pool or a worker thread that releases the GIL (7.3, 01C.1, 01C.5).
  • Starvation has precise causes. Event-loop starvation, queue fairness and priority are treated properly in 01C.4; the point here is the mechanism: one iteration cannot end until every handle in its snapshot has returned.

4.6 What this means for an AI engineer#

  • Latency spikes in an async API have a mechanical reading. If p99 latency rises while CPU is low, look for handles that run long: JSON-parsing a giant response, tokenizing a long prompt, a synchronous SDK call, a re with catastrophic backtracking. The next iteration cannot start until they return, and every timer and wake-up waits.
  • asyncio timeouts are only as good as the loop's wake-up. A timeout(5) fires at the first iteration after five seconds in which the loop gets to run. A blocked loop makes every timeout late: this is why a slow handler can cause "timeouts" in unrelated requests (9.2 measures this).
  • The mini loop is a good interview and debugging model. When a tool such as py-spy or python -m asyncio pstree shows a task parked, you now know exactly what it is parked on: a Future whose done-callback is that task's __wakeup.

Part 5: Awaitables, async iteration and the life of a loop#

Deep-dive

5.1 Awaitables and what a Task accepts#

An awaitable is anything you can put after await. There are three kinds in the standard library (the second includes Future and Task, so the split is not exclusive):

Awaitable What await does with it
a coroutine object (the result of calling an async def function) drives it directly, like yield from
any object with __await__ returning an iterator, which includes a Future (and so a Task) drives that iterator; for a Future, that means suspending until it completes, then returning its result or raising its exception
a generator-based coroutine: a generator function decorated with types.coroutine (the legacy 3.4-era spelling, used by e03 and e22 below) drives the generator; the decorator sets the CO_ITERABLE_COROUTINE flag, which is what makes a generator object awaitable even though it has no __await__

At the very bottom of every await chain there is a yield, and the object that comes out of it is received by the Task. We saw the Task's rules in 3.3; here they are with a real Task, using three hand-made awaitables: one that yields None, one that yields a real Future, and one that yields garbage.

python
# e22_task_protocol.py: what a real asyncio Task accepts from a coroutine's yield.
import asyncio
import types


@types.coroutine
def bare_yield():
    yield                                       # None: "run me again next loop iteration"


@types.coroutine
def bad_yield():
    yield "not a future"                        # anything else is a protocol violation


class Wait:
    """A hand-made awaitable that yields a real Future, exactly like Future.__await__ does."""
    def __init__(self, delay: float) -> None:
        self.delay = delay

    def __await__(self):
        fut = asyncio.get_running_loop().create_future()
        asyncio.get_running_loop().call_later(self.delay, fut.set_result, "slept")
        fut._asyncio_future_blocking = True     # what Future.__await__ sets before yielding itself
        yield fut
        return fut.result()


async def main() -> None:
    log: list[str] = []

    async def other() -> None:
        log.append("other ran")

    asyncio.create_task(other())
    await bare_yield()                          # the loop gets one turn, so `other` runs
    log.append("main resumed after bare yield")
    print(log)
    print("custom awaitable returned:", await Wait(0.01))
    try:
        await bad_yield()
    except RuntimeError as exc:
        print("RuntimeError:", exc)


asyncio.run(main())
Output3 lines
['other ran', 'main resumed after bare yield']
custom awaitable returned: slept
RuntimeError: Task got bad yield: 'not a future'
  • A bare yield is accepted: the Task reschedules itself for the next iteration, so other got a turn before main resumed. This is what asyncio.sleep(0) does internally.
  • A Future that the Task recognizes (it has the _asyncio_future_blocking flag set, which is what Future.__await__ does) parks the Task until the future completes. Wait is a miniature asyncio.sleep.
  • Anything else is thrown back into the coroutine as RuntimeError: Task got bad yield: .... If you ever see this message, you almost certainly used an await-able from another async framework (or a generator-based one) inside asyncio. This is the technical reason trio and asyncio coroutines are not interchangeable: they yield different things to different schedulers.

5.2 Async generators and their finalization#

01B.3, 5.1-5.2 teaches how to use async for, async with and async generators. The mechanics are the same as for coroutines, with two extra protocols.

  • async for x in obj calls obj.__aiter__() once, then repeatedly awaits iterator.__anext__() until it raises StopAsyncIteration. Each __anext__() returns an awaitable, so each step can suspend.
  • async with cm as v awaits cm.__aenter__(), runs the block, and awaits cm.__aexit__(exc_type, exc, tb) (even when the block raises).
  • An async generator (an async def containing yield) is an object with __anext__, asend(value), athrow(exc) and aclose(). Each of these returns an awaitable. await agen.aclose() throws GeneratorExit at the paused yield, so finally blocks run.
  • Async comprehensions (PEP 530) are async for in expression form: [tok async for tok in stream].

Here is the async for loop written out by hand, followed by asend and aclose:

python
# e21_asyncgen_by_hand.py: async generators and `async for` desugared; asend/athrow/aclose.
import asyncio


async def stream_tokens():
    try:
        for tok in ["The", " answer", " is", " 42"]:
            await asyncio.sleep(0)               # pretend each token takes a network round trip
            got = yield tok                      # asend() can push a value in
            if got:
                print("  generator received:", got)
    finally:
        print("  generator cleanup (finally ran)")


async def main() -> None:
    # `async for` is this loop, written out:
    agen = stream_tokens()
    parts = []
    while True:
        try:
            parts.append(await agen.__anext__())   # __anext__ returns an awaitable
        except StopAsyncIteration:
            break
    print("async for equivalent:", "".join(parts))

    agen = stream_tokens()
    print(await agen.__anext__())
    print(await agen.asend("hello"))             # resumes at `yield`, sends "hello" in
    await agen.aclose()                          # throws GeneratorExit at the yield: finally runs

asyncio.run(main())
Output6 lines
  generator cleanup (finally ran)
async for equivalent: The answer is 42
The
  generator received: hello
 answer
  generator cleanup (finally ran)

Read the output as a trace. The first generator finished normally (its finally printed), and the manual __anext__ loop produced the same text async for would. The second generator was left half-way: asend("hello") resumed it at the yield (the generator printed what it received), and await agen.aclose() ran its cleanup.

Finalization is where async generators bite. A synchronous generator that is abandoned half-way is cleaned up by the garbage collector immediately (reference counting), and its finally runs. An async generator's cleanup is itself asynchronous (aclose() is an awaitable), and the garbage collector cannot await. So the interpreter has a hook for it: while the loop is running it has installed a pair of hooks (sys.set_asyncgen_hooks) that the interpreter calls for every async generator: one records the generator so the loop can find it later, and a finalizer that, when the generator is about to be collected, schedules aclose() on the loop for you. At shutdown, loop.shutdown_asyncgens() closes any that are still open. You saw that last step in action in the asyncio.run experiment (5.3).

The practical rules:

  • break out of an async for over a generator that holds a resource (an HTTP stream, a database cursor, a file) and the generator is not closed deterministically; cleanup waits for the finalizer. Wrap it: async with contextlib.aclosing(gen()) as stream: closes it on exit.
  • Never await inside a finally of an abandoned generator and expect it to run "now". It runs whenever the finalizer's task gets scheduled.
  • Cancelling a consumer does not close the producer it was iterating unless you structured it that way (the same aclosing rule).

5.3 asyncio.run and asyncio.Runner: start and stop a loop#

01B.3, 3.1 and 3.9 cover how to call them. Here is what they do, from runners.py in the 3.14.6 source.

Start: create a new event loop (loop_factory() if you passed one, else the platform default), run it, and wrap your coroutine in a Task with a copied context. If the main thread's SIGINT handler is still Python's default, install one that cancels the main task on the first Ctrl-C (so your finally blocks run) and lets a second Ctrl-C raise KeyboardInterrupt as usual (a tight loop that never awaits cannot be cancelled, so it needs that second Ctrl-C). After the main task is cancelled and cleanup is done, Runner.run() still ends by raising KeyboardInterrupt, which matters for exit codes in containers (asyncio Runner docs).

Stop (Runner.close()), in this exact order:

  1. Cancel every task still pending and run the loop until they have all finished their cancellation (_cancel_all_tasks).
  2. loop.shutdown_asyncgens(): aclose() every async generator that is still open.
  3. loop.shutdown_default_executor(300): wait for the default thread pool's threads to join, for at most 300 seconds (THREAD_JOIN_TIMEOUT in asyncio/constants.py). On timeout it only warns and moves on: the threads are not killed.
  4. Close the loop.
python
# e15_run_internals.py: what asyncio.run does around your main(), in order.
import asyncio


async def ticker():
    try:
        while True:
            yield "tick"
            await asyncio.sleep(0.01)
    finally:
        print("asyncgen finalizer ran (aclose via shutdown_asyncgens)")


async def background():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print("leftover task was cancelled by asyncio.run on exit")
        raise


still_open = []                                 # keeps the generator alive so only shutdown can close it


async def main():
    gen = ticker()
    still_open.append(gen)
    print(await anext(gen))                     # leave the async generator suspended, un-closed
    asyncio.create_task(background(), name="leftover")
    await asyncio.to_thread(lambda: None)       # forces creation of the default thread-pool executor
    print("main returns now")


# Hand-written version of asyncio.run(main()) using the public Runner (3.11+):
with asyncio.Runner() as runner:
    loop = runner.get_loop()
    runner.run(main())
print("after the with-block: loop closed =", loop.is_closed())
Output5 lines
tick
main returns now
leftover task was cancelled by asyncio.run on exit
asyncgen finalizer ran (aclose via shutdown_asyncgens)
after the with-block: loop closed = True

The trace follows the four steps: main returned, the leftover task was cancelled (and ran its except CancelledError), then the open async generator was finalized, and finally the loop was closed. Two practical consequences:

  • Background tasks you never awaited get cancelled at exit, not finished. A "fire and forget" metrics flush started right before asyncio.run returns can be lost. Await it, or keep a list and gather it in a finally.
  • A blocking function stuck in the default executor delays asyncio.run from returning by up to five minutes (step 3), which looks exactly like "my process will not exit after Ctrl-C". After the 300 s, asyncio emits a RuntimeWarning and returns, but the worker thread is still alive and the interpreter still waits for it at exit, so a worker blocked forever keeps the process alive forever. Make workers stoppable (an Event, client timeouts) or use your own executor.

asyncio.run(coro, *, debug=None, loop_factory=None) is a thin wrapper over Runner and cannot be called while another loop is running in the same thread (9.1 shows the message). In Python 3.14 it accepts any awaitable, not only a coroutine (from the official docs).

Event-loop policies are being removed (Python 3.14)

Before 3.14 you customised the loop with an event-loop policy: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()), or WindowsSelectorEventLoopPolicy() on Windows. As of Python 3.14, the whole policy system is deprecated and scheduled for removal in Python 3.16 (from What's New in Python 3.14, gh-127949), including get_event_loop_policy, set_event_loop_policy, AbstractEventLoopPolicy, DefaultEventLoopPolicy and the two Windows policy classes. The replacement is the loop_factory argument:

python
# Illustrative: choose the loop implementation without a global policy.
import asyncio


async def main() -> None:
    await asyncio.sleep(0)


# Windows: ask for a selector loop instead of the default Proactor loop.
asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)  # 3.12+

# uvloop (third-party, not run in this lesson): pass its factory the same way.
#   import uvloop
#   asyncio.run(main(), loop_factory=uvloop.new_event_loop)  # 3.12+

asyncio.run(loop_factory=) needs Python 3.12; on 3.11 it raises TypeError. The portable spelling works on 3.11 too: with asyncio.Runner(loop_factory=asyncio.SelectorEventLoop) as r: r.run(main()).

Related 3.14 changes from the same release notes: asyncio.get_event_loop() now raises RuntimeError if there is no current event loop (instead of creating one), and the child-watcher classes deprecated since 3.12 (ThreadedChildWatcher and friends) were removed. asyncio.iscoroutinefunction() is deprecated (removal in 3.16); use inspect.iscoroutinefunction(). If your code is loop = asyncio.get_event_loop(); loop.run_until_complete(...), change it to asyncio.run(...).

Primitives are Futures

For a lesson whose thesis is "every wake-up is a Future plus a callback", the commonest Futures in real code live inside asyncio.Lock, Event, Semaphore, Condition and Queue: each keeps a deque of waiter Futures and wakes them first-in, first-out. That is why asyncio.Lock is FIFO-fair (01C.4 relies on it), why a lost set() or an unfed queue leaves a task parked forever (8.3), and why a cancelled waiter must remove itself from the deque. A hand-written lock (task C is cancelled while waiting):

python
# e27_mini_primitives.py: a lock and a queue are Futures in a deque; cancelling a waiter cleans up.
import asyncio
from collections import deque


class MiniLock:
    def __init__(self) -> None:
        self._locked = False
        self._waiters: deque[asyncio.Future] = deque()

    async def acquire(self) -> None:
        if not self._locked and not self._waiters:
            self._locked = True
            return
        fut = asyncio.get_running_loop().create_future()
        self._waiters.append(fut)                 # park on a Future, like Lock.acquire
        try:
            await fut
        except asyncio.CancelledError:
            if fut in self._waiters:
                self._waiters.remove(fut)         # a cancelled waiter must leave the line
            raise
        self._locked = True

    def release(self) -> None:
        self._locked = False
        while self._waiters:                      # wake the first waiter still waiting (FIFO)
            fut = self._waiters.popleft()
            if not fut.done():
                fut.set_result(None)
                break


async def worker(name: str, lock: MiniLock, log: list[str]) -> None:
    await lock.acquire()
    log.append(f"{name} in")
    await asyncio.sleep(0.01)
    log.append(f"{name} out")
    lock.release()


async def main() -> None:
    lock, log = MiniLock(), []
    tasks = [asyncio.create_task(worker(n, lock, log)) for n in "ABCD"]
    await asyncio.sleep(0)
    tasks[2].cancel()                              # C gives up while waiting
    await asyncio.gather(*tasks, return_exceptions=True)
    print(log)
    print("waiters left:", len(lock._waiters))


asyncio.run(main())
Output2 lines
['A in', 'A out', 'B in', 'B out', 'D in', 'D out']
waiters left: 0
Real call What it does underneath
Lock.acquire() creates a Future, appends it to _waiters, awaits it
Event.wait() creates a Future, appends it to _waiters; set() completes them all
Queue.get() when empty, creates a Future in _getters and awaits it; put() completes one

asyncio.gather works the same way: one done-callback per child, and the outer Future completes when the counter reaches zero. Cancelling the outer future cancels the children, and return_exceptions=True turns child exceptions into results. Transports and protocols, the callback-style layer under streams that 4.4 names, are documented in the Transports and Protocols page.

Version map as of November 2026

Python What changed for this lesson's topic
3.11 asyncio.Runner, TaskGroup, asyncio.timeout(), cancelling()/uncancel(), context= on create_task
3.12 eager tasks, asyncio.run(loop_factory=), wait_for rebuilt on timeout
3.13 uncancel() rescinds a pending cancellation when the counter reaches zero; Queue.shutdown()
3.14 policy system deprecated, call-graph introspection and python -m asyncio ps/pstree, get_event_loop() raises without a loop, create_task(eager_start=)
3.15 (released 9 October 2026) TaskGroup.cancel() (early termination of a group), --retries option on ps/pstree (per the 3.15 docs; not run here: the outputs in this lesson came from Python 3.14.6)

5.4 What this means for an AI engineer#

  • Graceful shutdown of an LLM service is Runner.close() in slow motion: stop accepting requests, let in-flight streams finish or cancel them, close the provider client, then exit. If your container is killed 30 seconds after SIGTERM but run() is still waiting up to 300 seconds on a blocking SDK call in the executor, you lose the race (11C.1).
  • Streaming endpoints are async generators. The cleanup rules above decide whether an abandoned stream frees its provider connection promptly or at the next garbage collection.
  • Custom loops (uvloop) are a one-line loop_factory now, with no global state: a good thing when tests and application code want different loops.

Part 6: Cancellation and timeouts as mechanism#

01B.3, 4.1 is the usage guide (always re-raise CancelledError, clean up in finally). This part explains why those rules exist, because the machinery in asyncio.timeout, TaskGroup and wait_for all hangs off one mechanism.

6.1 How Task.cancel() works#

From the 3.14.6 source, task.cancel() does three things:

  1. Increments the task's count of cancellation requests (cancelling()).
  2. If the task is currently parked on a Future, calls cancel() on that future. This completes it as cancelled, so the task's __wakeup callback is scheduled, and when it runs it throws CancelledError into the coroutine at the await where it was parked (coro.throw(...) instead of coro.send(None)).
  3. Otherwise (the task is already scheduled to run) it sets a flag so the next step throws CancelledError.

Several well-known properties follow:

  • Cancellation is a request delivered at an await. It cannot interrupt a coroutine between two awaits, so a task in a long synchronous loop is not cancellable until it next suspends. task.cancel() returns True immediately, but the task is not cancelled yet; task.cancelled() becomes True only when the coroutine finishes with CancelledError.
  • CancelledError is an ordinary exception thrown from the await, so try/finally and async with clean up normally. That is the whole value of cooperative cancellation: the task can release locks, flush buffers and close clients.
  • A task can refuse. If a coroutine catches CancelledError and does not re-raise, the task simply keeps going, and cancelled() stays False. The official docs call suppressing cancellation "actively discouraged".
  • Cancelling a task cancels what it awaits. Awaiting a task or a gathered group from a cancelled parent propagates the cancellation downwards, because step 2 cancels the future the parent is parked on.
  • Cancelling an await on a thread does not stop the thread. The next experiment shows it.
python
# e23_cancel_thread.py: cancelling the awaiting task does NOT stop the worker thread.
import asyncio
import threading
import time

finished = threading.Event()


def blocking_embed(texts: list[str]) -> int:
    time.sleep(0.2)                              # stands in for a blocking SDK call
    finished.set()
    return len(texts)


async def main() -> None:
    task = asyncio.create_task(asyncio.to_thread(blocking_embed, ["a", "b", "c"]))
    await asyncio.sleep(0.05)                    # let the thread start
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("task cancelled:", task.cancelled())
    print("worker already finished right after cancel:", finished.is_set())
    await asyncio.sleep(0.3)
    print("worker finished later anyway:", finished.is_set())


asyncio.run(main())
Output3 lines
task cancelled: True
worker already finished right after cancel: False
worker finished later anyway: True

The task is cancelled at once, but the worker thread has no await to be interrupted at and runs to completion in the background, still using a thread-pool slot, a connection and perhaps a provider's rate limit. Threads cannot be cancelled from outside in Python. For blocking work you want to be abandonable, give the worker a way to notice (a threading.Event it polls between chunks, or a client timeout) or use a process you can terminate.

6.2 cancelling() and uncancel(): whose cancellation is it?#

Since Python 3.11 each task keeps a counter of cancellation requests (cancelling()) that uncancel() decrements. Why would a counter be needed? Because a task can be cancelled for two different reasons at once: by an outer scope (a client disconnected, the parent was cancelled), and by an inner scope (asyncio.timeout expired, a TaskGroup aborted). When an inner scope sees CancelledError, it needs to decide: did I cause this, or did someone outside? It remembers the count when it started; at exit it calls uncancel() to take back its own request, and if the count is back to where it began, the cancellation was its own and it can convert it (to TimeoutError, or to an ExceptionGroup); otherwise it lets CancelledError continue upwards.

python
# e11_cancel_internals.py: cancel() throws CancelledError at the suspension point; cancelling()/uncancel().
import asyncio


async def polite() -> None:
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print("polite: cleaning up, then re-raising")
        raise


async def stubborn(counts: list[int]) -> str:
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        counts.append(asyncio.current_task().cancelling())   # cancel requests seen so far
        asyncio.current_task().uncancel()                    # we really are swallowing it
        return "stubborn: swallowed the cancellation"
    return "never"


async def main() -> None:
    t = asyncio.create_task(polite())
    await asyncio.sleep(0)               # let it reach its await
    print("cancel() returned", t.cancel(), "| cancelling() =", t.cancelling())
    try:
        await t
    except asyncio.CancelledError:
        print("main: task.cancelled() =", t.cancelled())

    counts: list[int] = []
    s = asyncio.create_task(stubborn(counts))
    await asyncio.sleep(0)
    s.cancel()
    print(await s, "| cancelling() inside handler was", counts, "| cancelled():", s.cancelled())

    # timeout() is built on exactly this: call_at + task.cancel() + uncancel() + translate to TimeoutError
    try:
        async with asyncio.timeout(0.01):
            await asyncio.sleep(10)
    except TimeoutError:
        print("main: timeout() turned CancelledError into TimeoutError;",
              "current task cancelling() =", asyncio.current_task().cancelling())


asyncio.run(main())
Output5 lines
cancel() returned True | cancelling() = 1
polite: cleaning up, then re-raising
main: task.cancelled() = True
stubborn: swallowed the cancellation | cancelling() inside handler was [1] | cancelled(): False
main: timeout() turned CancelledError into TimeoutError; current task cancelling() = 0

Walk through it:

  • polite re-raised: the task ended cancelled(). cancelling() was 1 right after cancel().
  • stubborn caught the exception and returned a value: cancelled() is False, because the cancellation was suppressed. It called uncancel() to drop the counter, as the docs require for code that swallows a cancellation. (Without that call, the task would still report cancelling() == 1, and a later asyncio.timeout or TaskGroup around it would mis-judge whose cancellation it was.)
  • After the timeout block, the task's counter is back to 0: the timeout took its own request back and translated CancelledError into TimeoutError.

cancel(msg) and shield. task.cancel("reason") (3.9) puts the message in the CancelledError's args, and since 3.11 it propagates up the await chain. asyncio.shield(inner) is the standard way to survive a timeout: the outer await is cancelled but the inner task keeps running. Keep your own reference to the inner task, because the loop holds only a weak one.

python
# e25_shield_msg_except_star.py: cancel(msg), asyncio.shield, and except* on a TaskGroup.
import asyncio


async def slow_save() -> str:
    await asyncio.sleep(0.05)
    print("inner: save finished even though the caller timed out")
    return "saved"


async def boom(kind: type[Exception], text: str) -> None:
    await asyncio.sleep(0.01)
    raise kind(text)


async def main() -> None:
    # 1. cancel(msg): the message travels in CancelledError.args
    t = asyncio.create_task(asyncio.sleep(10))
    await asyncio.sleep(0)
    t.cancel("client went away")
    try:
        await t
    except asyncio.CancelledError as exc:
        print("cancel message:", exc.args)

    # 2. shield: the timeout cancels the outer await, not the inner task
    inner = asyncio.create_task(slow_save())      # keep a reference: the loop holds only a weak one
    try:
        async with asyncio.timeout(0.01):
            await asyncio.shield(inner)
    except TimeoutError:
        print("outer: timed out; inner.done() =", inner.done())
    print("inner result:", await inner)

    # 3. TaskGroup raises an ExceptionGroup; except* handles each kind separately
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(boom(ValueError, "bad input"))
            tg.create_task(boom(KeyError, "missing key"))
    except* ValueError as eg:
        print("ValueError group:", [str(e) for e in eg.exceptions])
    except* KeyError as eg:
        print("KeyError group:", [repr(e) for e in eg.exceptions])


asyncio.run(main())
Output6 lines
cancel message: ('client went away',)
outer: timed out; inner.done() = False
inner: save finished even though the caller timed out
inner result: saved
ValueError group: ['bad input']
KeyError group: ["KeyError('missing key')"]

6.3 How asyncio.timeout() is built#

timeout() is not magic; it is a small class built on exactly the parts we have covered:

  1. On __aenter__ it records the current task and its cancelling() count, and schedules a timer with loop.call_at(deadline, self._on_timeout).
  2. When the timer fires (if the block has not finished), _on_timeout calls task.cancel() on the task that entered the block.
  3. The task is woken with CancelledError at its current await.
  4. On __aexit__ it cancels the timer; if it had expired, it calls task.uncancel(), and if the count is back to the recorded one and the exception is a CancelledError, it raises TimeoutError from it.

Hence the three behaviours in the docs: the TimeoutError can only be caught outside the async with block (the translation happens in __aexit__); a timeout interrupts only at an await (a CPU-bound or blocking block overruns it, and the timeout fires late: 9.2); and timeouts nest correctly because of the counter. In current CPython asyncio.wait_for is a thin wrapper around asyncio.timeout (verified in the 3.14.6 source), so they share all of this. The usage guide, including reschedule() and the wait_for comparison, is 01B.3, 3.5.

6.4 How TaskGroup uses the same mechanism#

01B.3, 3.4 shows the behaviour: when one child fails, siblings are cancelled and the group raises an ExceptionGroup. Mechanically, in taskgroups.py: each child gets a done-callback; when a child ends with an exception, the group (1) records the error, (2) aborts the remaining children (cancel() on each), and (3) cancels the parent task (the one inside the async with body) so that whatever the body was awaiting is interrupted, setting a flag so that __aexit__ knows to call uncancel() on the parent. __aexit__ then waits for all children, undoes its own cancellation request and raises the collected errors as an ExceptionGroup. If the outside world cancelled the parent meanwhile, the counter is still non-zero after uncancel() and CancelledError propagates correctly.

TaskGroup re-raises KeyboardInterrupt and SystemExit rather than wrapping them, and wraps everything else in an ExceptionGroup, which you handle with except* (PEP 654, shown in the run in 6.2; the syntax is taught in 01B.3, 3.4). Python 3.15 adds TaskGroup.cancel() to terminate a group early, replacing the "extra task that raises a custom exception" boilerplate (3.15 only, not run here).

The design rule: structured concurrency is built from cancel(), uncancel() and the counter. If your code breaks the counter (swallowing CancelledError without uncancel()), you break all of it.

6.5 What this means for an AI engineer#

  • A client disconnect should stop the model call. With a StreamingResponse in Starlette/FastAPI, a client disconnect cancels the streaming task, so CancelledError arrives at your await on the provider's stream. For a normal (non-streaming) endpoint the handler is not cancelled for you: poll await request.is_disconnected() between expensive steps, or run the model call in a task you cancel yourself. Newer servers may instead make send() raise OSError, so check what your server and framework version do (framework side: 03.3 Part 10, 11C.1, 2.8). Your finally (or async with) closes the HTTP response, which typically makes the provider stop generating (check your provider's behaviour), so you stop paying for tokens nobody will read. That works only if the code awaiting the stream is cancellable, which it is when it is an await and is not when it is a blocking SDK call in a thread (the experiment above).
  • Deadlines per request are asyncio.timeout, and the correct place to catch TimeoutError is outside the block, mapped to a clear error for the caller (03.9, 5.3).
  • Never write except BaseException in agent loops to keep an agent alive after a tool failure: use except Exception. A swallowed cancellation makes an "uncancellable" agent that survives its own timeout.

Part 7: Crossing the thread boundary#

An event loop lives on one thread, and almost everything in asyncio is not thread-safe. Real services cross that boundary all the time: a blocking SDK, a database driver, a background thread delivering events, a thread-pool request handler calling into async code. These are the correct crossings.

7.1 Why call_soon from another thread is wrong#

loop.call_soon appends a handle to the ready deque. That alone is not the problem; the problem is that the loop might be asleep in select(None), waiting for I/O that will never come, so the new callback sits in the queue unrun until something else wakes the loop. And the loop's other data structures (the timer heap, Future callback lists) are plain Python objects with no locks.

loop.call_soon_threadsafe(fn, *args) does what call_soon does, plus it wakes the loop: it writes one byte (b"\0") to the loop's self-pipe, a socket pair the loop always watches, so a sleeping select() returns immediately (_write_to_self in selector_events.py). It is the documented way to schedule a callback from another thread (the docs say it must be used for that), and run_coroutine_threadsafe is built on it.

In debug mode asyncio checks and raises. The next experiment shows the real message, the right way to run a coroutine from another thread, and the right way to complete a Future.

python
# e14_threadsafe.py: call_soon is not thread-safe; call_soon_threadsafe and run_coroutine_threadsafe are.
import asyncio
import threading


async def lookup(key: str) -> str:
    await asyncio.sleep(0.01)
    return f"value-for-{key}"


async def main() -> None:
    loop = asyncio.get_running_loop()
    done = loop.create_future()
    problems: list[str] = []

    def other_thread() -> None:
        try:
            loop.call_soon(print, "unsafe")               # wrong thread
        except RuntimeError as exc:
            problems.append(str(exc))
        fut = asyncio.run_coroutine_threadsafe(lookup("k1"), loop)   # right way, returns concurrent Future
        value = fut.result(timeout=2)
        loop.call_soon_threadsafe(done.set_result, value)  # right way to complete an asyncio Future

    t = threading.Thread(target=other_thread)
    t.start()
    print("main got:", await done)
    t.join()
    print("debug-mode check from the wrong thread raised:", problems[0])


asyncio.run(main(), debug=True)
Output2 lines
main got: value-for-k1
debug-mode check from the wrong thread raised: Non-thread-safe operation invoked on an event loop other than the current one

7.2 run_coroutine_threadsafe: call async code from a thread#

asyncio.run_coroutine_threadsafe(coro, loop) submits a coroutine to a running loop from another thread and returns a concurrent.futures.Future (the thread-world kind, with a blocking .result(timeout=...)), as in the experiment. It is how a synchronous worker thread, a synchronous framework callback or a test harness calls into an async library. Always pass a timeout to .result(): if the loop is not running, or is blocked, the thread would otherwise hang forever. On TimeoutError the submitted coroutine keeps running on the loop, so call fut.cancel() in the except TimeoutError branch, which cancels the coroutine there. (asyncio.run() from a worker thread is a different tool: it creates a new loop on that thread, so objects bound to the main loop, such as a shared HTTP client, cannot be used there.)

7.3 Bridging callback APIs and blocking code#

Callback APIs to await. Many SDKs and drivers are callback-based and finish on their own thread. The standard bridge is: create a Future on the loop, and have the callback complete it through call_soon_threadsafe.

python
# e20_callback_bridge.py: turn a callback-style API into an awaitable with loop.create_future().
import asyncio
import threading


class LegacyClient:
    """Pretend SDK: completes work on its own thread and calls back."""
    def fetch(self, key: str, on_done, on_error) -> None:
        def work() -> None:
            if key == "bad":
                on_error(ValueError("no such key"))
            else:
                on_done(f"document:{key}")
        threading.Timer(0.01, work).start()


def _resolve(fut: asyncio.Future, value) -> None:
    # Runs on the loop thread. The awaiting task may have been cancelled (timeout, shutdown),
    # which cancels fut; a late set_result would then raise InvalidStateError on the loop.
    if not fut.done():
        fut.set_result(value)


def _fail(fut: asyncio.Future, exc: BaseException) -> None:
    if not fut.done():
        fut.set_exception(exc)


async def fetch(client: LegacyClient, key: str) -> str:
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    # The callback runs on the foreign thread, so it must hop onto the loop thread first.
    client.fetch(
        key,
        lambda value: loop.call_soon_threadsafe(_resolve, fut, value),
        lambda exc: loop.call_soon_threadsafe(_fail, fut, exc),
    )
    return await fut


async def main() -> None:
    client = LegacyClient()
    print(await fetch(client, "a1"))
    try:
        await fetch(client, "bad")
    except ValueError as exc:
        print("error crossed the bridge:", exc)
    # A timeout cancels the future; the late callback must be ignored, not raise.
    try:
        async with asyncio.timeout(0.001):
            await fetch(client, "slow")
    except TimeoutError:
        print("timed out; waiting for the late callback")
    await asyncio.sleep(0.05)
    print("late callback ignored, no InvalidStateError")


asyncio.run(main())
Output4 lines
document:a1
error crossed the bridge: no such key
timed out; waiting for the late callback
late callback ignored, no InvalidStateError

Note that both outcomes cross the bridge: a result with set_result and an error with set_exception. If the callback instead called fut.set_result(value) directly from the foreign thread, you would be mutating a loop-owned object from the wrong thread: sometimes it works, sometimes the awaiting task is never woken.

The _resolve and _fail guards matter as soon as you add a timeout. When the awaiting task is cancelled (a timeout, a client disconnect, shutdown), fut becomes cancelled, and a late callback that runs fut.set_result on the loop thread raises InvalidStateError, which the loop logs as Exception in callback Future.set_result(). A late callback after cancellation must never raise on the loop. In a real wrapper you would also add fut.add_done_callback(...) to unregister the client callback or cancel the legacy request when fut.cancelled() is true.

Blocking code to a thread. asyncio.to_thread(func, *args) is, in its entirety, contextvars.copy_context() plus loop.run_in_executor(None, ctx.run(func...)) (from asyncio/threads.py): it copies the current context and runs the function in the default executor, a ThreadPoolExecutor of at most min(32, cpu_count + 4) threads (4.4). The usage patterns are in 01B.3, 3.8. Three internals to add:

  • The default executor is shared with the loop's own name resolution. getaddrinfo runs there. A burst of slow to_thread calls can delay DNS lookups, which shows up as connection timeouts in unrelated code; the official docs warn about this. For heavy blocking workloads, create a dedicated ThreadPoolExecutor and pass it to run_in_executor(executor, ...).
  • Threads help only for blocking code that releases the GIL (network and file waits, many C extensions). A pure-Python CPU loop in a thread still holds the GIL and competes with the loop thread (01C.5); use a ProcessPoolExecutor for CPU-heavy work (run_in_executor accepts one), keeping in mind that arguments and results are pickled (01C.7).
  • The thread is not cancellable (the experiment in 6.1).

7.4 contextvars: what travels with a task#

Thread-local storage cannot carry "the current request ID" in async code: all tasks run on the same thread, so a threading.local value would be shared and overwritten by every task. contextvars.ContextVar (PEP 567) solves it: a Context is a mapping of variables, and the loop makes sure that each unit of work runs inside the right one.

  • A Task gets a copy of the current context when it is created. Changes the task makes to a variable are visible inside the task (and tasks it creates later), but never leak back to the parent or to siblings.
  • A Handle created by call_soon captures the context at scheduling time (a copy), or the one you pass with context=.
  • asyncio.to_thread copies the context into the thread, so a variable set before the call is readable inside the blocking function.
python
# e12_contextvars.py: each Task gets a COPY of the context at creation; threads via to_thread inherit it too.
import asyncio
import contextvars

request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")


async def handler(name: str) -> str:
    request_id.set(f"req-{name}")             # set inside this task's own context copy
    await asyncio.sleep(0)
    in_thread = await asyncio.to_thread(request_id.get)    # to_thread copies the current context
    return f"{name}: sees {request_id.get()}, thread sees {in_thread}"


async def main() -> None:
    request_id.set("parent")
    print(await asyncio.gather(handler("a"), handler("b")))
    print("parent still sees:", request_id.get())          # children could not change it

    loop = asyncio.get_running_loop()
    seen: list[str] = []
    request_id.set("at-schedule-time")
    loop.call_soon(lambda: seen.append("call_soon: " + request_id.get()))
    request_id.set("changed-later")
    custom = contextvars.copy_context()
    custom.run(request_id.set, "custom")
    loop.call_soon(lambda: seen.append("explicit context: " + request_id.get()), context=custom)
    await asyncio.sleep(0)
    print(seen)


asyncio.run(main())
Output3 lines
['a: sees req-a, thread sees req-a', 'b: sees req-b, thread sees req-b']
parent still sees: parent
['call_soon: at-schedule-time', 'explicit context: custom']

Each handler saw its own request_id (req-a, req-b) even though both ran on one thread, and the parent still saw "parent". The call_soon callback saw the value at scheduling time (at-schedule-time), not changed-later; an explicit context= overrides it.

Context gotchas, with a run (Python 3.14.6):

python
# e26_context_gotchas.py: run_in_executor does not copy the context; reset() needs the same Context.
import asyncio
import contextvars

request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")


def read_id() -> str:
    return request_id.get()


async def main() -> None:
    request_id.set("req-42")
    loop = asyncio.get_running_loop()
    print("to_thread:       ", await asyncio.to_thread(read_id))
    print("run_in_executor: ", await loop.run_in_executor(None, read_id))

    # An explicit context= isolates or injects values for one task
    ctx = contextvars.copy_context()
    ctx.run(request_id.set, "req-injected")
    async def read_async() -> str:
        return request_id.get()

    print("create_task ctx: ", await asyncio.create_task(read_async(), context=ctx))
    print("caller still:    ", request_id.get())

    # reset(token) must run in the Context that created the token
    token = request_id.set("req-43")
    async def reset_elsewhere() -> None:
        try:
            request_id.reset(token)
        except ValueError as exc:
            print("reset in another task: ValueError:", str(exc).split(" was ", 1)[1])
    await asyncio.create_task(reset_elsewhere())
    request_id.reset(token)
    print("reset in same context ok:", request_id.get())


asyncio.run(main())
Output6 lines
to_thread:        req-42
run_in_executor:  -
create_task ctx:  req-injected
caller still:     req-42
reset in another task: ValueError: created in a different Context
reset in same context ok: req-42
  • create_task(coro, context=ctx), TaskGroup.create_task(..., context=) (3.11) and Runner.run(coro, context=) inject or isolate context deliberately.
  • loop.run_in_executor does not copy the context (only to_thread does), so a raw executor call sees the default.
  • call_soon_threadsafe copies the context of the calling thread, not the loop's.
  • var.reset(token) raises ValueError in a different Context from the one that created the token (common across tasks and async generators).
  • An async generator runs in the context of whoever calls __anext__, not where it was created.

Rules of thumb:

  • Set once, near the top of the request. A task spawned before you set the variable will not see it; a task spawned after gets a snapshot, so later changes in the parent are invisible to it.
  • Use var.set() tokens with var.reset(token) when you need to restore a value around a block.
  • Do not store mutable shared state in a ContextVar and expect isolation. Only the binding is per-context; if two contexts hold the same list object, they share it.

7.5 What this means for an AI engineer#

  • Request IDs, tenant IDs, trace spans and per-user budgets belong in ContextVars. Logging filters and tracing libraries read them, which is how one log line can say which request it belongs to even with a thousand requests interleaved (11A.1).
  • A synchronous SDK inside an async service goes through to_thread or a dedicated executor, and its cancellation story is "it finishes anyway", so give it its own client timeout. When the provider offers an async client, prefer it (03.9, 2.2 and 2.6).
  • Bridge, do not share. An SDK that calls you back on its own thread (some audio and realtime SDKs do) is bridged with call_soon_threadsafe, never by touching Futures or queues from that thread (the realtime lessons in Module 09 build on this).

Part 8: Seeing inside a running loop: debug mode and introspection#

Deep-dive

Async bugs are intermittent and timing-dependent, so you need instruments. Python has three layers of them: asyncio's debug mode, a loop-lag monitor you write yourself, and (new in 3.14) a way to ask a running process what its tasks are waiting on.

8.1 Debug mode#

Debug mode is off by default. The official documentation lists four ways to turn it on: set PYTHONASYNCIODEBUG=1; use Python Development Mode (python -X dev); pass debug=True to asyncio.run(); or call loop.set_debug(True). It also recommends raising the asyncio logger to DEBUG and showing ResourceWarnings. What it enables, in the docs' list (three items), plus two documented elsewhere on the same page:

  • Non-thread-safe APIs (such as call_soon and call_at) raise if called from the wrong thread (you saw this in 7.1).
  • A slow I/O selector poll is logged.
  • Callbacks that run longer than loop.slow_callback_duration (default 100 ms) are logged: this is your blocking-call detector.
  • Never-awaited coroutines report the traceback of where the coroutine was created (the stack of the call that built it); never-retrieved exceptions likewise carry their creation traceback.

The next script triggers two of them on purpose, captures the log, and prints facts rather than raw log lines (the log lines contain timings and file paths).

python
# e13_debug_mode.py: debug mode logs slow callbacks and shows where a never-awaited coroutine was created.
import asyncio
import gc
import logging
import time
import warnings


class Capture(logging.Handler):
    def __init__(self) -> None:
        super().__init__()
        self.messages: list[str] = []

    def emit(self, record: logging.LogRecord) -> None:
        self.messages.append(record.getMessage())


async def forgotten() -> None:
    return None


async def main() -> None:
    loop = asyncio.get_running_loop()
    loop.slow_callback_duration = 0.02          # default is 0.1 s
    time.sleep(0.05)                            # a blocking call hidden in a coroutine step
    forgotten()                                 # BUG: never awaited
    gc.collect()                                # force the warning now, not at a random moment


cap = Capture()
logging.getLogger("asyncio").addHandler(cap)
logging.getLogger("asyncio").propagate = False
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    asyncio.run(main(), debug=True)
print("slow-callback log lines:", len(cap.messages))
print("log mentions 'took' and 'seconds':", all(w in cap.messages[0] for w in ("took", "seconds")))
print("warning:", str(caught[0].message).splitlines()[0])
print("creation traceback attached:", "Coroutine created at" in str(caught[0].message))
Output4 lines
slow-callback log lines: 1
log mentions 'took' and 'seconds': True
warning: coroutine 'forgotten' was never awaited
creation traceback attached: True

The log line you would see in a real service has this shape (illustrative): Executing <Task pending name='Task-3' coro=<parse_invoice() running at app.py:41>> took 0.121 seconds. It names the exact coroutine step, and the line it was on, that held the loop (Exercise 5 uses this).

8.2 A loop-lag monitor you can leave on#

The cheapest production signal for "the loop is blocked" is a heartbeat: a task that sleeps for a small interval and measures how late it woke up. If the loop is healthy the lateness is microseconds; if any handle runs long, the heartbeat is late by exactly that much, because the timer cannot fire until the long handle returns (the 4.1 rules).

python
# e24_lag_monitor.py: a production-style event-loop lag monitor (a heartbeat that measures its own lateness).
import asyncio
import time
from dataclasses import dataclass, field


@dataclass
class LagMonitor:
    interval: float = 0.01
    worst: float = 0.0
    samples: int = 0
    _task: asyncio.Task | None = field(default=None, repr=False)

    async def _run(self) -> None:
        loop = asyncio.get_running_loop()
        while True:
            expected = loop.time() + self.interval
            await asyncio.sleep(self.interval)
            lag = loop.time() - expected          # how late the loop got back to us
            self.worst = max(self.worst, lag)
            self.samples += 1

    def start(self) -> None:
        self._task = asyncio.create_task(self._run(), name="lag-monitor")

    async def stop(self) -> None:
        assert self._task is not None
        self._task.cancel()
        try:
            await self._task
        except asyncio.CancelledError:
            pass


def tokenize_big_prompt() -> int:
    time.sleep(0.15)                              # stands in for 150 ms of synchronous CPU work
    return 4096


async def main() -> None:
    monitor = LagMonitor()
    monitor.start()
    await asyncio.sleep(0.05)
    print("idle loop, worst lag under 50 ms:", monitor.worst < 0.05)
    monitor.worst = 0.0
    tokenize_big_prompt()                         # BUG: called directly on the loop thread
    await asyncio.sleep(0.02)
    print("after sync work, worst lag over 100 ms:", monitor.worst > 0.1)
    monitor.worst = 0.0
    await asyncio.to_thread(tokenize_big_prompt)  # FIX: off the loop thread
    print("with to_thread, worst lag under 50 ms:", monitor.worst < 0.05)
    await monitor.stop()


asyncio.run(main())
Output3 lines
idle loop, worst lag under 50 ms: True
after sync work, worst lag over 100 ms: True
with to_thread, worst lag under 50 ms: True

The idle loop stayed prompt, the direct call of a 150 ms synchronous function made the heartbeat 100 ms+ late, and moving the same call to a thread restored a healthy loop. (The thresholds are loose on purpose, so the output is stable across machines.) In a real service you export worst or a histogram of lag as a metric (11A.2) and alert when p99 lag exceeds, say, 100 ms. A rising lag with low CPU usually means something is blocking on a lock or a synchronous call; a rising lag with high CPU usually means CPU work on the loop thread.

8.3 Python 3.14: introspection of tasks#

Debugging "which task is stuck, and waiting for what?" used to need guesswork or a debugger. Python 3.14 added call-graph introspection (gh-91048) in two forms (verified in What's New in Python 3.14 and the asyncio call-graph documentation):

From inside the process: asyncio.capture_call_graph() returns a FutureCallGraph for the current task (or a task or future you pass in), and asyncio.print_call_graph() prints it; asyncio.format_call_graph() returns the text. A FutureCallGraph has future, call_stack (the frames of the coroutine chain, from the cr_await links of 2.2) and awaited_by (the tasks waiting on this one).

python
# e18_call_graph.py: Python 3.14 asyncio introspection (capture_call_graph / print_call_graph).
import asyncio


async def fetch_embedding() -> None:
    graph = asyncio.capture_call_graph()        # None outside a running task
    stack = [entry.frame.f_code.co_name for entry in graph.call_stack]
    awaited_by = [[e.frame.f_code.co_name for e in g.call_stack] for g in graph.awaited_by]
    print("call_stack (innermost first):", stack)
    print("awaited_by:", awaited_by, "| task name:", graph.future.get_name())


async def ingest_document() -> None:
    await fetch_embedding()


async def main() -> None:
    await asyncio.create_task(ingest_document(), name="ingest-doc-42")


asyncio.run(main())
Output2 lines
call_stack (innermost first): ['fetch_embedding', 'ingest_document']
awaited_by: [['main']] | task name: ingest-doc-42

The graph tells you the coroutine chain inside the task (fetch_embedding called by ingest_document) and who is waiting for the task (main). That second part is something a plain stack trace has never been able to give you. A request handler could dump this graph when a request exceeds its deadline.

capture_call_graph(future=None, /, *, depth=1, limit=None) takes depth (frames to skip) and limit (frames to keep). Here is print_call_graph() inside a TaskGroup (Python 3.14.6; addresses normalised, file paths on your machine will differ, so treat the paths as illustrative):

python
# e28_call_graph_print.py: print_call_graph() inside a TaskGroup (addresses normalised).
import asyncio
import io
import re
from contextlib import redirect_stdout


async def embed() -> None:
    buf = io.StringIO()
    with redirect_stdout(buf):
        asyncio.print_call_graph()
    print(re.sub(r"0x[0-9a-f]+", "0x...", buf.getvalue()))


async def main() -> None:
    async with asyncio.TaskGroup() as tg:
        tg.create_task(embed(), name="embed-1")


asyncio.run(main())
Output10 lines
* Task(name='embed-1', id=0x...)
  + Call stack:
  |   File '/opt/homebrew/Cellar/python@3.14/3.14.6/Frameworks/Python.framework/Versions/3.14/lib/python3.14/asyncio/graph.py', line 276, in print_call_graph()
  |   File '/home/you/lab/e28_call_graph_print.py', line 11, in async embed()
  + Awaited by:
    * Task(name='Task-1', id=0x...)
      + Call stack:
      |   File '/opt/homebrew/Cellar/python@3.14/3.14.6/Frameworks/Python.framework/Versions/3.14/lib/python3.14/asyncio/taskgroups.py', line 121, in async TaskGroup._aexit()
      |   File '/opt/homebrew/Cellar/python@3.14/3.14.6/Frameworks/Python.framework/Versions/3.14/lib/python3.14/asyncio/taskgroups.py', line 72, in async TaskGroup.__aexit__()
      |   File '/home/you/lab/e28_call_graph_print.py', line 16, in async main()

What to run when a service hangs: python -m asyncio pstree PID first (is a task parked on a Future nobody completes?), then python -m asyncio ps PID for the flat list. Attaching needs the remote debugging permissions (typically root on macOS, ptrace scope on Linux).

From outside the process: two new command-line tools inspect a running Python 3.14 process by PID, with no change to the target's code:

bash
python -m asyncio ps PID      # a flat table: every task, its name, its coroutine stack, who awaits it
python -m asyncio pstree PID  # the same data as a tree of awaiting relationships

The docs describe ps as "a task table: a flat listing of all tasks, their names, their coroutine stacks, and which tasks are awaiting them" and pstree as a visual async call tree; if the await graph has a cycle (a task waiting on itself through others: an asyncio deadlock) the tool says so instead of printing a tree. Python 3.15 adds a --retries N option to both. Their output looks like this (illustrative: your exact output will differ), from a toy program with three tasks parked on sleep:

text
Example output (illustrative):
  tid  task id  task name  coroutine stack           awaiter chain  awaiter name  awaiter id
  ...  0x...    worker-1   main -> worker -> sleep   0x...          Task-1        0x...

If the graph has a cycle, ps still lists every task, but pstree refuses and prints ERROR: await-graph contains cycles - cannot print a tree!. We do not run these here: they need a second running process and, depending on your operating system's rules for attaching to another process, elevated privileges (see the remote-debugging section of the 3.14 documentation). They are the first stdlib tool that can show you a hung asyncio service from the outside. They rely on a per-thread list of native tasks introduced in 3.14, which the release notes also credit with a 10-20% improvement in standard asyncio benchmarks and lower memory use.

Other tools you should know about, all stdlib: asyncio.all_tasks() (every unfinished task of the loop), asyncio.current_task(), task.get_stack() and task.print_stack() (the current position of a suspended coroutine chain), task.get_name() (give tasks names with create_task(..., name=...): it makes every tool above readable) and loop.get_debug(). Third-party samplers such as py-spy dump can also read a stuck process's Python stacks, but they show thread stacks, not the async await graph (illustrative: py-spy is not run here).

8.4 What this means for an AI engineer#

  • Name every task (create_task(coro, name=f"embed-batch-{i}")). When an agent loop hangs at 3 a.m., ps output full of Task-4817 is useless.
  • Ship the lag monitor in every async service, and put its p99 next to your LLM latency dashboards: it separates "the provider is slow" from "my event loop is busy".
  • Run your tests with debug mode on so that a blocking call added to an async path fails (or at least warns) in CI, long before production (01B.8 for the test harness).

Reference

01B.3, 4.2 and Part 8 already show the classic user-level bugs (a never-awaited coroutine, a lost task, an unretrieved exception, time.sleep in async code). These are the ones that need the internals from Parts 3-7 to explain. One script triggers them all, on purpose, with the real messages (path-specific details are normalized away):

python
# e16_bug_gallery.py: loop-level bugs, each triggered on purpose, with the real message.
import asyncio
import re


async def inner() -> None:
    await asyncio.sleep(0)


async def nested_run() -> None:
    coro = inner()
    try:
        asyncio.run(coro)                       # BUG: a loop is already running in this thread
    except RuntimeError as exc:
        print("2)", exc)
    coro.close()                                # silence the "never awaited" warning for the demo


def wrong_loop_future() -> None:
    other = asyncio.new_event_loop()
    fut = other.create_future()                 # Future belongs to `other`

    async def waiter() -> None:
        await fut                               # awaited from a different loop

    try:
        asyncio.run(waiter())
    except RuntimeError as exc:
        print("1)", re.sub(r"Task <.*?> got", "Task <...> got", str(exc), flags=re.S))
    finally:
        other.close()


async def check_then_act() -> None:
    stock = {"widgets": 1}
    sold: list[str] = []

    async def buy(who: str) -> None:
        if stock["widgets"] > 0:                # check
            await asyncio.sleep(0)              # any await between check and act lets another task in
            stock["widgets"] -= 1               # act
            sold.append(who)

    await asyncio.gather(buy("alice"), buy("bob"))
    print("5) sold:", sold, "| stock:", stock["widgets"])


async def heartbeat_lag(block: bool) -> bool:
    ticks: list[float] = []
    loop = asyncio.get_running_loop()

    async def beat() -> None:
        for _ in range(5):
            ticks.append(loop.time())
            await asyncio.sleep(0.01)

    async def work() -> None:
        await asyncio.sleep(0.015)
        if block:
            import time
            time.sleep(0.2)                     # blocks the only thread
        else:
            await asyncio.to_thread(lambda: __import__("time").sleep(0.2))

    await asyncio.gather(beat(), work())
    return max(b - a for a, b in zip(ticks, ticks[1:])) > 0.1


async def main() -> None:
    await nested_run()
    print("3) heartbeat starved by time.sleep:", await heartbeat_lag(True))
    print("4) heartbeat starved with to_thread:", await heartbeat_lag(False))
    await check_then_act()


wrong_loop_future()
asyncio.run(main())
try:
    exec("def f():\n    await inner()")
except SyntaxError as exc:
    print("6)", exc.msg)
Output6 lines
1) Task <...> got Future <Future pending> attached to a different loop
2) asyncio.run() cannot be called from a running event loop
3) heartbeat starved by time.sleep: True
4) heartbeat starved with to_thread: False
5) sold: ['alice', 'bob'] | stock: -1
6) 'await' outside async function
# Symptom (real message) Cause (the mechanism) Fix
1 RuntimeError: Task <...> got Future <Future pending> attached to a different loop A Future was created on loop A and awaited by a Task on loop B (the check in Task.__step, 3.3). Typical sources: a client or lock created at import time and used from a different asyncio.run; objects shared between threads' loops. Create loop-bound objects (clients, locks, queues, futures) inside the running loop, one client per loop (03.9, 2.3).
2 asyncio.run() cannot be called from a running event loop run() creates a new loop and runs it in the current thread, but this thread already has one running (Jupyter, FastAPI handlers, an async def main calling a sync helper that calls asyncio.run). await the coroutine; in a notebook use top-level await; in a sync helper called from async code, make the helper async or use to_thread (01B.3, 6.1).
3 no error; every timer and request is late A synchronous call (time.sleep, a sync SDK, big JSON parse) runs on the loop thread; the iteration cannot finish (4.1). to_thread, a dedicated executor, a process pool, or the async client (9.2).
4 (the fixed version: no lag) The same work off the loop thread: the heartbeat stays on time.
5 sold: ['alice', 'bob'] and stock: -1 A check-then-act race at an await: the if and the decrement are separated by a suspension point (9.3). Hold an asyncio.Lock across check and act, or remove the await between them.
6 SyntaxError: 'await' outside async function await is yield from for coroutines, valid only inside an async def (2.2). Make the function async, or call asyncio.run at the top.

More that did not fit the script:

Symptom Cause Fix
Task got bad yield: ... An awaitable from another async framework (or a hand-made generator) yielded something the Task does not accept (5.1). Use one framework's awaitables per loop; write library code against anyio, or run both with trio-asyncio.
Non-thread-safe operation invoked on an event loop other than the current one (debug mode) call_soon, create_task or future.set_result called from a foreign thread (7.1). call_soon_threadsafe or run_coroutine_threadsafe. Without debug mode this silently corrupts or stalls.
a background task "disappears" only a weak reference to the Task existed (3.3). Keep a reference; prefer TaskGroup.
async for over a stream never frees its connection after break the async generator is closed by a finalizer, not deterministically (5.2). async with aclosing(...).
a timeout never fires / fires 10 s late the loop is blocked, or the code swallowed CancelledError (6.2, 6.3). Remove blocking calls; re-raise cancellation.
ContextVar value missing in a callback or worker the task or callback was created before the variable was set, or the thread was started without a context copy (7.4). Set early; use to_thread (copies context) rather than a raw threading.Thread.
process will not exit after Ctrl-C a task in the default executor is still blocked, and Runner.close() waits up to 300 s before run() returns, and then the interpreter still waits for the thread (5.3). Make the worker stoppable; use your own executor and shut it down with a timeout.
works with uvloop, breaks without (or the reverse) code depended on an implementation detail (the order of I/O versus timer callbacks, a private _selector) (4.2). Rely only on documented ordering (FIFO call_soon).

9.2 The blocking call, with measured proof#

Rows 3 and 4 of the script are the same experiment as 01B.3, 8.1, but measured at the level of the loop: a beat() task is supposed to tick every 10 ms. With a time.sleep(0.2) inside another coroutine, the gap between two consecutive ticks exceeded 100 ms (True); with the same wait moved to asyncio.to_thread, it did not (False). The mechanism is the snapshot rule of 4.1: the iteration that runs work() cannot reach its timer phase until work() returns.

9.3 The check-then-act race at an await point#

Row 5 is worth a section, because "asyncio is single-threaded, so there are no race conditions" is the most common wrong belief about it. A race condition needs only two things: shared state, and a point where another piece of code can run between your check and your act. In threaded code that point is "almost anywhere". In asyncio it is every await. In buy(), the check (stock > 0) and the act (stock -= 1) are separated by await asyncio.sleep(0); two tasks both pass the check before either acts, and stock goes negative.

The fix is to make the check-and-act atomic with respect to other tasks, by holding an asyncio.Lock across both (a lock is cheap here: it is just a Future-based queue; see 01B.3, 3.7), or by deleting the await between them (do the check and the act in one synchronous stretch, which nothing can interrupt). What is true: between two awaits, nothing else runs, so a plain counter increment such as n += 1 with no await inside is safe within one loop. 01C.3 treats races in depth: data races, atomic operations and the cases that involve several threads.

9.4 What this means for an AI engineer#

  • Almost all production asyncio bugs reduce to four things: blocked loop (9.2), lost or swallowed cancellation (Part 6), wrong-thread access (Part 7), state shared across an await (9.3). Keep that list next to your code review checklist.
  • Intermittent behaviour is normal for these bugs: they depend on timing. Reproduce them deterministically (as these scripts do) before you attempt a fix.

Part 10: Sync vs async in the real world#

10.1 Choosing a model for an AI workload#

01C.1 classifies work as I/O-bound or CPU-bound and compares the four Python models in general. Here is the decision from the sync vs async side, for typical AI-engineering jobs.

Workload Best fit Why
200 LLM or embedding API calls, results needed together asyncio with a semaphore (01B.4) pure waiting; thousands of pending calls cost almost nothing
A chat backend streaming tokens to many users asyncio (ASGI) each stream is a long-lived suspended coroutine
One notebook cell that calls a model five times a plain for loop, or asyncio.gather if you care complexity is not worth it for five calls
Calling a vendor SDK that only has a sync client a thread pool (to_thread or ThreadPoolExecutor) threads give concurrency without rewriting the SDK
Local embedding with a model in-process (CPU/GPU) batching, then processes or the library's own parallelism CPU-bound: async adds nothing; the loop would be blocked
Parsing thousands of PDFs ProcessPoolExecutor, driven from async if the rest is async CPU-bound; avoids the GIL (01C.5)
Reading many small files from disk threads (to_thread) or just sequential ordinary file I/O is blocking for the loop; the OS buffers it
A CLI that processes one file and exits synchronous code no concurrency requirement; simplest wins
A queue worker reading jobs and calling a model async worker with bounded concurrency, or N worker processes scale with processes, concurrency with async inside each

10.2 WSGI vs ASGI: the same split in web frameworks#

Web frameworks make the sync/async choice for you at the server contract level.

WSGI is the classic synchronous contract: the server calls a plain function app(environ, start_response) and the function returns an iterable of bytes. The worker (a process or a thread of Gunicorn, uWSGI or the dev server) is busy until the function returns. Concurrency means more workers or threads: Flask, and classic Django, run this way. Waiting on an LLM call for 5 seconds holds a worker for 5 seconds.

ASGI is the asynchronous contract: the server calls an async def app(scope, receive, send) coroutine. It awaits events (the request body, each outgoing message), so the server can keep thousands of connections open on a single loop; it also covers WebSockets and long-lived streams, which WSGI cannot express. Starlette, FastAPI and (partially) Django use it, typically under Uvicorn.

Both contracts can be driven by hand, with no server, which shows the difference:

python
# e17_wsgi_vs_asgi.py: the two web-server contracts, driven by hand with no server installed.
import asyncio


def wsgi_app(environ, start_response):          # WSGI: a plain function, one call per request
    body = f"hello {environ['PATH_INFO']}".encode()
    start_response("200 OK", [("Content-Type", "text/plain")])
    return [body]                               # an iterable of bytes; the thread is busy until it returns


async def asgi_app(scope, receive, send):       # ASGI: a coroutine; every await frees the loop
    assert scope["type"] == "http"
    await receive()                             # waits for the request body event
    await asyncio.sleep(0.01)                   # e.g. await an LLM call
    await send({"type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")]})
    await send({"type": "http.response.body", "body": f"hello {scope['path']}".encode(), "more_body": False})


async def drive_asgi(path: str) -> list[dict]:
    sent: list[dict] = []

    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        sent.append(message)

    await asgi_app({"type": "http", "path": path}, receive, send)
    return sent


captured = {}
body = wsgi_app({"PATH_INFO": "/a"}, lambda status, headers: captured.update(status=status))
print("WSGI :", captured["status"], body)

async def main() -> None:
    results = await asyncio.gather(drive_asgi("/x"), drive_asgi("/y"))   # two requests, one thread
    for messages in results:
        print("ASGI :", [m["type"] for m in messages], messages[-1]["body"])

asyncio.run(main())
Output3 lines
WSGI : 200 OK [b'hello /a']
ASGI : ['http.response.start', 'http.response.body'] b'hello /x'
ASGI : ['http.response.start', 'http.response.body'] b'hello /y'

The WSGI app returns when done and the thread was occupied throughout. The two ASGI requests were interleaved on one thread: each await in asgi_app (receive, sleep, send) is a point where the other request advances.

WSGI ASGI
App is a function a coroutine function
Concurrency unit a worker process/thread a task on the event loop (plus workers for scale-out)
Long-lived connections (SSE, WebSocket) poor fit: one worker held per connection natural fit
Blocking call inside a handler blocks that worker only blocks the whole loop (all requests on that process)
Typical servers Gunicorn, uWSGI, waitress Uvicorn, Hypercorn, Daphne

Note the last-but-one row: it is the trade made explicit. FastAPI lets you choose per endpoint: an async def endpoint runs on the loop (never block inside it), a plain def endpoint runs in a thread pool (blocking is fine, but you are limited by the pool size). The practical rules are in 01B.7, 4.1; the deployment sizing consequences (processes, workers, memory per worker) are in 11C.1.

10.3 Layering sync and async code#

A codebase that mixes both needs a deliberate structure, not accidents:

  • Async at the edges that wait, sync in the middle that computes. Parsing, chunking, scoring and formatting are plain functions; only the functions that talk to the network are async. Pure functions are trivially testable and need no loop.
  • One loop per process, started at the top (asyncio.run(main())), not scattered run_until_complete calls. A library should expose an async API and let the application own the loop.
  • Providing both sync and async APIs is common for SDKs: the provider SDKs ship separate sync and async clients, and often generate one from the other, because a function cannot be both. That is "function colouring" (01B.3, 6.3): an async def can only be called properly from another async def, so the choice spreads upward through your call graph. Decide at the boundary: the service entry point decides, and everything below follows.
  • Adapting sync to async: await asyncio.to_thread(sync_fn, ...) (7.3). Adapting async to sync: asyncio.run(coro()) from a plain top-level function, never from inside a running loop (row 2 in 9.1).

10.4 When async is not worth it#

Async is a tool with a price; reach for it when the arithmetic favours it. Reasons to stay synchronous (or to use threads):

Situation Why sync is better
Few concurrent operations (a handful of calls) a thread pool of a few workers gets the same speed-up with ordinary code and ordinary stack traces
CPU-bound work async gives no parallelism and starves the loop; use processes (01C.5)
Your key dependencies have only blocking APIs you would wrap everything in to_thread, getting the downsides of both
A short script, one-off job or notebook the colouring and debugging overhead outweighs any gain
A team that is new to async a stalled loop and a swallowed CancelledError are harder to diagnose than a slow thread
Modest scale where a worker pool already meets the load the simplest design that meets the requirement is the right one

Reasons to choose async: thousands of simultaneous, mostly idle connections (streaming, WebSockets, fan-out to many providers), strict control over cancellation and timeouts, and a stack (ASGI, async SDKs) already built for it.

10.5 uvloop, trio and anyio#

01B.3, 6.4 introduces these. What the internals add:

  • uvloop replaces the event loop implementation (the Loop of 4.1) with one written in Cython on top of libuv (the same library underneath Node.js). The README (as of November 2026) says it "makes asyncio 2-4x faster" and shows uvloop.run(main()) or asyncio.Runner(loop_factory=uvloop.new_event_loop). The gain applies to the work inside the loop (I/O handling, transports, timers), not to your own Python code in handlers. Because your coroutines are unchanged, an LLM service dominated by provider latency may see little difference; a service doing massive numbers of small socket operations sees more. Benchmark with your own traffic. Its README does not state Windows support; check the project before relying on it there. uvloop is not run in this lesson (illustrative only), and your code must not depend on loop internals (9.1, last row).
  • trio is a separate async framework with its own scheduler, built around structured concurrency: every task lives inside a nursery (the model asyncio.TaskGroup borrowed), and cancel scopes give precise, composable cancellation. Its awaitables yield different objects than asyncio's, so trio code cannot run on an asyncio loop and vice versa (5.1); trio-asyncio is a bridge.
  • anyio is a compatibility layer: per its documentation it "works on top of either asyncio or Trio" and "implements Trio-like structured concurrency (SC) on top of asyncio", with task groups, cancellation scopes and worker-thread helpers. Libraries that must work for both worlds (such as httpx's transports) are written against it.

For an AI engineer the default is clear: asyncio, because the provider SDKs, FastAPI and most of the ecosystem assume it. Consider anyio if you write a library, and uvloop as a late-stage optimization once profiling shows loop overhead matters.

10.6 What this means for an AI engineer#

  • Pick the model by the shape of the waiting: many idle waits means async; blocking-only dependencies means threads; CPU work means processes; and when you cannot tell, measure (01C.1).
  • In a web service, the sync/async decision is made per endpoint and per dependency, so know what runs on the loop and what runs on a thread pool, and never put a blocking call on the former.
  • Keep the loop healthy: monitor its lag (8.2), name your tasks (8.4), and treat cancellation as a first-class signal (Part 6).

Common misconceptions#

Misconception Reality
"async makes my code faster" It makes waiting overlap. A single call is exactly as slow; CPU-bound code gets no speed-up and blocks the loop (1.1, 10.4).
"await always lets other tasks run" Only a real suspension does. Awaiting a coroutine that never suspends, or an already-completed Future, just continues (4.5).
"create_task starts the coroutine immediately" It schedules the first step; nothing runs until the current task suspends. Eager tasks (3.12, opt-in) are the exception (3.3, 3.5).
"The event loop is single-threaded, so asyncio code has no race conditions" There are no data races within one loop, but a check separated from its act by an await is a race (9.3).
"A coroutine is a thread" / "a task is a thread" A coroutine is a pausable frame on the heap; tasks share one OS thread and are switched only at await (2.1).
"call_later(0, f) and call_soon(f) are the same" call_soon is FIFO with other ready callbacks; a due timer is appended after them during the iteration (3.1).
"Cancelling a task stops its work" It delivers CancelledError at the next await. A task can swallow it, and a thread started by to_thread keeps running (6.1).
"except BaseException in a worker keeps agents robust" It also swallows CancelledError, which breaks timeout, TaskGroup and shutdown (6.2).
"asyncio.run just runs my coroutine" It also installs a SIGINT handler, then on exit cancels leftover tasks, closes async generators and joins the executor, up to 300 s before run() returns (5.3).
"threading.local carries per-request data in async code" All tasks share a thread; use contextvars (7.4).
"uvloop makes my service several times faster" It speeds up the loop's own I/O machinery, not your handlers; the README's "2-4x" is for an echo-server benchmark. Measure (10.5).
"Async is always better than threads for I/O" Often, at high concurrency. For a handful of calls, or blocking-only libraries, threads are simpler and just as fast (10.4).

Key takeaways#

  • Sync vs async is about what a waiting function does: it freezes its thread (sync) or gives the thread back and asks to be resumed (async). Callbacks, futures and async/await are three spellings of the same model.
  • A coroutine is a generator in disguise. await is yield from with a type check; a whole await chain suspends and resumes as one unit through send().
  • The loop schedules three things: Handles (callbacks), Futures (promises) and Tasks (coroutine drivers). Each wake-up is a Handle on the ready queue; call_soon is FIFO, and Future.set_result schedules its callbacks rather than running them.
  • One iteration is fixed: poll the selector (the only place the loop sleeps), append ready I/O callbacks, append due timers, then run a snapshot of the ready queue. A long callback delays everything behind it.
  • The core of an event loop is about seventy lines (a ready deque, a timer heap and a selector), and the real one adds cancellation, thread-safety, signals, transports and C speed.
  • Cancellation is a request delivered as CancelledError at an await, tracked by a counter (cancelling()/uncancel()) that timeout() and TaskGroup rely on. Clean up, then re-raise.
  • Cross the thread boundary only with call_soon_threadsafe, run_coroutine_threadsafe or to_thread. Everything else in asyncio is not thread-safe, and cancelled thread work keeps running.
  • contextvars give each task its own view of request-scoped data; threads from to_thread inherit a copy.
  • Instrument the loop: debug mode in development, a lag monitor in production, capture_call_graph and python -m asyncio ps/pstree (3.14) when something hangs. Name your tasks.
  • Choose by the shape of the waiting. Many idle waits: async. Blocking-only libraries: threads. CPU work: processes. Few concurrent operations: stay synchronous.
  • As of November 2026 (Python 3.14, with 3.15 current): the event-loop policy system is deprecated and is scheduled for removal in 3.16 (check the 3.15 notes before upgrading); pass loop_factory instead. get_event_loop() raises RuntimeError when there is no loop.

Where you'll use this in the AI path#

Where What you use from this lesson
01B.4, Concurrency Patterns for I/O-Heavy Work bounded fan-out, queues and rate limits are all loop-level patterns: now you know what a semaphore waiter and a queue get park on
03.9, a sync call inside async code the blocking-call bug (9.2) and its measurement (8.2)
03.9, a deadline for a whole job timeout and cancellation as mechanism (Part 6)
03.3, async streaming async generators and their finalization (5.2)
08A.2, parallel tool calls, bounded tasks, TaskGroup cancellation and swallowed CancelledError in agent loops
08F.8, async tools and the trap in them sync tools on the loop thread, to_thread and the executor (7.3)
11A.1, context propagation across async and services contextvars in tasks and threads (7.4)
11C.1, the streaming endpoint ASGI streams, disconnects and cancellation (10.2, 6.5)
01C.3, 01C.4, 01C.5 the next lessons: races across threads, asyncio deadlocks and loop starvation, and why threads cannot parallelize CPU work

Terms introduced in this lesson#

Term Meaning
Synchronous a call that does not return until its result is ready; the caller's stack (and thread) waits
Asynchronous a call that gives control back while it waits and is resumed later by a scheduler
Callback a function you hand to a framework to be called when something is ready
Coroutine (object) a pausable, resumable frame produced by calling an async def function; has send, throw, close
Awaitable anything usable after await: a coroutine, a Future/Task, or an object with __await__
__await__ the method returning an iterator that await drives
Event loop the scheduler that runs ready callbacks, due timers and I/O-ready callbacks, one iteration at a time
Ready queue the FIFO deque of Handles that can run now
Timer heap the min-heap of TimerHandles ordered by due time
Selector the OS readiness API wrapper (epoll, kqueue, select) the loop polls
Handle / TimerHandle one scheduled callback (with its arguments and context); can be cancelled
Future a promise: a slot for a result or exception, with callbacks fired (via call_soon) on completion
Task a Future that drives a coroutine by calling send() step by step
Eager task a task that runs its first step synchronously at creation (Python 3.12, opt-in)
Snapshot rule one loop iteration runs only the callbacks that were ready when it began
Self-pipe a socket pair the loop watches so another thread can wake a sleeping select()
call_soon_threadsafe the thread-safe way to schedule a callback on a loop from another thread
Cancellation counter Task.cancelling(), incremented by cancel() and decremented by uncancel()
Loop lag how late the loop gets back to a timer; the signal for a blocked loop
WSGI / ASGI the synchronous and asynchronous web-server application contracts
loop_factory the argument to asyncio.run/Runner that selects the loop implementation (replaces policies)

Exercises#

Run the solutions yourself; each was run for real and the output is pasted. Solutions use only the standard library, and the scripts are shown in full or can be assembled from the snippets in each part.

Exercise 1 (coroutines by hand). Write a coroutine total_cost() that awaits two "requests" (one for prompt tokens, one for completion tokens) and returns the sum, and a drive() function that runs it with send() and answers each request from a dictionary, with no event loop.

Solution
python
# x01_drive_by_hand.py: Exercise 1 solution. A mini "scheduler" that drives a coroutine and answers each request.
import types


@types.coroutine
def request(label: str):
    answer = yield label                        # hand a request to the driver, get the answer back
    return answer


async def total_cost() -> int:
    a = await request("price of prompt tokens")
    b = await request("price of completion tokens")
    return a + b


def drive(coro, answers: dict[str, int]) -> int:
    value = None
    while True:
        try:
            label = coro.send(value)            # run to the next request
        except StopIteration as stop:
            return stop.value
        print("driver got request:", label)
        value = answers[label]                  # reply on the next send()


print("total:", drive(total_cost(), {"price of prompt tokens": 30, "price of completion tokens": 12}))
Output3 lines
driver got request: price of prompt tokens
driver got request: price of completion tokens
total: 42

request is a @types.coroutine generator, so the yield at the bottom of the await chain hands the label to drive, and the next send supplies the answer. StopIteration.value is the coroutine's return value.

Exercise 2 (predict the order). Without running it, predict the printed list. Then run it.

python
# x02_predict_order.py: Exercise 2. Predict the order before running.
import asyncio


async def job(name: str, log: list[str]) -> None:
    log.append(f"{name} start")
    await asyncio.sleep(0)
    log.append(f"{name} end")


async def main() -> None:
    loop = asyncio.get_running_loop()
    log: list[str] = []
    asyncio.create_task(job("T1", log))
    loop.call_soon(log.append, "cb1")
    asyncio.create_task(job("T2", log))
    loop.call_soon(log.append, "cb2")
    log.append("main")
    await asyncio.sleep(0.01)
    print(log)


asyncio.run(main())
Solution
Output1 line
['main', 'T1 start', 'cb1', 'T2 start', 'cb2', 'T1 end', 'T2 end']

main is running, so nothing else can run until it reaches its await: first "main" is appended. Then the first loop iteration runs the ready queue in FIFO order: the T1 first step, cb1, the T2 first step, cb2 (everything was queued in that order). Both tasks yield a bare None at sleep(0) and are put back at the end, so T1 end, T2 end come in the next iteration.

Exercise 3 (extend the mini loop). The mini loop's Task.step assumes every suspension yields a Future. Add support for a bare yield (like asyncio.sleep(0)): the task should be rescheduled with call_soon. Show two tasks alternating.

Solution

The change is three lines in Task.step, right after the except StopIteration block:

diff
+        if waiting_on is None:                   # bare yield: "run me again next iteration"
+            self.loop.call_soon(self.step, None)
+            return
         waiting_on.add_done_callback(lambda fut: self.step(fut.result))

Add the diff to the Task class of the mini loop in 4.3 (the class Future to loop = Loop() part), then replace the example coroutines with these. Each task calls await sleep0(), an awaitable that does a bare yield, between steps:

python
class _Yield:
    def __await__(self):
        yield                                    # a bare yield, like asyncio's __sleep0


async def sleep0():
    await _Yield()


async def chatty(name, n, log):
    for i in range(n):
        log.append(f"{name}{i}")
        await sleep0()


async def main():
    log = []
    tasks = [Task(loop, chatty("a", 3, log)), Task(loop, chatty("b", 3, log))]
    for t in tasks:
        await t
    return log


print(" ".join(loop.run_until_complete(main())))
Output1 line
a0 b0 a1 b1 a2 b2

The tasks alternate, because each rescheduled step goes to the back of the ready queue, behind the other task's step. That is the same behaviour as asyncio.sleep(0) (4.5).

Exercise 4 (timeouts on a callback bridge). A legacy client may never call back (a lost message). Wrap the bridge from 7.3 with a deadline so the awaiting task does not hang forever.

Solution
python
# x04_callback_timeout.py: Exercise 4 solution. A callback API that never answers, guarded by asyncio.timeout.
import asyncio


class SilentClient:
    def fetch(self, key: str, on_done, on_error) -> None:
        pass                                     # never calls back: a lost message


def _resolve(fut, value) -> None:
    if not fut.done():                           # a late callback after cancellation must not raise
        fut.set_result(value)


def _fail(fut, exc) -> None:
    if not fut.done():
        fut.set_exception(exc)


async def fetch(client: SilentClient, key: str) -> str:
    loop = asyncio.get_running_loop()
    fut = loop.create_future()
    client.fetch(
        key,
        lambda v: loop.call_soon_threadsafe(_resolve, fut, v),
        lambda e: loop.call_soon_threadsafe(_fail, fut, e),
    )
    return await fut


async def main() -> None:
    try:
        async with asyncio.timeout(0.05):
            await fetch(SilentClient(), "doc-1")
    except TimeoutError:
        print("gave up after the deadline; the awaiting task was cancelled, not left parked forever")


asyncio.run(main())
Output1 line
gave up after the deadline; the awaiting task was cancelled, not left parked forever

The task is parked on a Future nobody will ever complete. asyncio.timeout schedules a timer that cancels the task (6.3), so the await fut raises CancelledError, which the context manager converts to TimeoutError outside the block. The _resolve guard is there for the opposite case: if the legacy client does answer late, after the task was cancelled, fut is already cancelled and an unguarded set_result would raise InvalidStateError on the loop thread (7.3). In real code also unregister whatever the legacy client holds (a fut.add_done_callback that cancels the request when fut.cancelled()), in a finally.

Exercise 5 (find the blocker with debug mode). A service handles invoices; occasionally every request stalls for about 100 ms. Using debug mode, find out which coroutine is responsible, without reading the code of all of them.

Solution
python
# x05_find_blocker.py: Exercise 5 solution. Use debug mode to name the coroutine that blocked the loop.
import asyncio
import logging
import time


class Capture(logging.Handler):
    def __init__(self) -> None:
        super().__init__()
        self.lines: list[str] = []

    def emit(self, record: logging.LogRecord) -> None:
        self.lines.append(record.getMessage())


async def embed_chunk(i: int) -> int:
    await asyncio.sleep(0.001)
    return i


async def parse_invoice() -> int:
    time.sleep(0.12)                             # the hidden blocking call
    return 1


async def main() -> None:
    await asyncio.gather(embed_chunk(1), parse_invoice(), embed_chunk(2))


cap = Capture()
log = logging.getLogger("asyncio")
log.addHandler(cap)
log.propagate = False
asyncio.run(main(), debug=True)                  # default slow_callback_duration = 0.1 s
slow = [line for line in cap.lines if "took" in line]
print("slow callbacks logged:", len(slow))
print("culprit named in the log:", any("parse_invoice" in line for line in slow))
Output2 lines
slow callbacks logged: 1
culprit named in the log: True

In debug mode the loop logs Executing <...> took N seconds for any callback slower than slow_callback_duration (default 0.1 s). The message includes the Task's representation, which names the coroutine (parse_invoice) and the line it was executing. Lower loop.slow_callback_duration to hunt shorter stalls.

Exercise 6 (the swallowed cancellation). Show that a worker that catches CancelledError and returns breaks asyncio.timeout, and fix it.

Solution
python
# x06_swallowed_cancel.py: Exercise 6 solution. A swallowed CancelledError defeats asyncio.timeout.
import asyncio


async def bad_worker() -> str:
    try:
        await asyncio.sleep(10)
        return "finished"
    except asyncio.CancelledError:
        return "caught CancelledError and carried on"      # BUG: never re-raised


async def good_worker() -> str:
    try:
        await asyncio.sleep(10)
        return "finished"
    except asyncio.CancelledError:
        print("  good_worker: releasing resources")
        raise                                               # clean up, then re-raise


async def run(worker) -> None:
    try:
        async with asyncio.timeout(0.02):
            print("  result:", await worker())
    except TimeoutError:
        print("  TimeoutError raised, as it should be")


for w in (bad_worker, good_worker):
    print(w.__name__)
    asyncio.run(run(w))
Output5 lines
bad_worker
  result: caught CancelledError and carried on
good_worker
  good_worker: releasing resources
  TimeoutError raised, as it should be

bad_worker swallowed the cancellation, so the context manager never saw a CancelledError to convert, and the block silently "succeeded" with a misleading result: no TimeoutError. good_worker cleans up and re-raises; the timeout works. If you truly must suppress a cancellation, call asyncio.current_task().uncancel() as the docs require (6.2).

Exercise 7 (a thread feeding the loop). An SDK delivers audio chunks on its own thread. Write a consumer coroutine that processes them in order using an asyncio.Queue, delivering chunks safely.

Solution
python
# x07_thread_to_queue.py: Exercise 7 solution. A producer thread feeds an asyncio.Queue safely.
import asyncio
import threading
import time

SENTINEL = None


def audio_thread(loop: asyncio.AbstractEventLoop, queue: asyncio.Queue) -> None:
    for chunk in (b"chunk-1", b"chunk-2", b"chunk-3"):
        time.sleep(0.01)                                     # the SDK's own thread produces data
        loop.call_soon_threadsafe(queue.put_nowait, chunk)   # NOT queue.put_nowait(chunk) directly
    loop.call_soon_threadsafe(queue.put_nowait, SENTINEL)


async def main() -> None:
    loop = asyncio.get_running_loop()
    queue: asyncio.Queue[bytes | None] = asyncio.Queue()
    threading.Thread(target=audio_thread, args=(loop, queue), daemon=True).start()
    while (chunk := await queue.get()) is not SENTINEL:
        print("consumer got", chunk)
    print("stream finished")


asyncio.run(main())
Output4 lines
consumer got b'chunk-1'
consumer got b'chunk-2'
consumer got b'chunk-3'
stream finished

asyncio.Queue is not thread-safe, so the thread never touches it directly: it calls loop.call_soon_threadsafe(queue.put_nowait, chunk), which both schedules the call on the loop thread and wakes the loop's select(). A sentinel marks the end of the stream.

Exercise 8 (request IDs in logs). Make every log line carry the ID of the request that produced it, with two requests interleaved on one thread.

Solution
python
# x08_log_request_id.py: Exercise 8 solution. One logging filter, many interleaved requests.
import asyncio
import contextvars
import logging
import sys

request_id: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")


class RequestIdFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = request_id.get()                 # read from the *current task's* context
        return True


handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("[%(request_id)s] %(message)s"))
handler.addFilter(RequestIdFilter())
log = logging.getLogger("app")
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False


async def handle(rid: str, delay: float) -> None:
    request_id.set(rid)
    log.info("received")
    await asyncio.sleep(delay)
    log.info("model call finished")


async def main() -> None:
    await asyncio.gather(handle("r-1", 0.02), handle("r-2", 0.01))


asyncio.run(main())
Output4 lines
[r-1] received
[r-2] received
[r-2] model call finished
[r-1] model call finished

Each handle call runs inside its own task and its own context copy, so request_id.set(rid) is private. The logging filter reads the variable at log time, so each line shows the right ID even though the lines of the two requests are interleaved.

Exercise 9 (eager tasks: which assumptions break?). Switching to asyncio.eager_task_factory is "free" for a service. Name two assumptions in typical code that it could silently break, and one where it helps. (Use the experiment in 3.5 to check your answer.)

Solution

Breaks: (1) code that does t = create_task(work()); shared["task"] = t and expects work() to start after that assignment (with eager start, work() runs first and may read shared["task"] and miss it); (2) log lines or metrics that assume "task created" is recorded before "task started" (the eager task's first lines now come first, which can break log-based tests and ordering assertions). More generally any code that depends on "a new task never runs before the creator's next await". Helps: workloads where many tasks complete without suspending (cache hits, validation failures), because they skip a scheduler round trip. Everything else is unchanged. Measure and run your tests under the factory before adopting it.

Exercise 10 (async generator cleanup). Show the difference between abandoning an async generator with break and closing it with contextlib.aclosing.

Solution
python
# x10_aclosing.py: Exercise 10 solution. When does an abandoned async generator clean up?
import asyncio
from contextlib import aclosing


async def stream():
    try:
        for tok in ("a", "b", "c"):
            yield tok
    finally:
        print("  stream cleanup ran")


async def without_aclosing() -> None:
    async for tok in stream():
        break                                    # abandon the generator half-way
    print("  after break (cleanup has NOT run yet)")
    await asyncio.sleep(0)                       # the finalizer's aclose() task gets a turn


async def with_aclosing() -> None:
    async with aclosing(stream()) as s:
        async for tok in s:
            break
    print("  after break (cleanup ran before this line)")


print("without aclosing:")
asyncio.run(without_aclosing())
print("with aclosing:")
asyncio.run(with_aclosing())
Output6 lines
without aclosing:
  after break (cleanup has NOT run yet)
  stream cleanup ran
with aclosing:
  stream cleanup ran
  after break (cleanup ran before this line)

Without aclosing, cleanup is performed later by the finalizer's scheduled aclose(): the line after break runs first. With aclosing, aclose() is awaited when the block exits, so cleanup is deterministic. For a generator that holds an HTTP response, that difference is whether the connection is released immediately.

Exercise 11 (a streaming ASGI app). Write a minimal ASGI application that streams three tokens as server-sent events and drive it by hand.

Solution
python
# x11_asgi_stream.py: Exercise 11 solution. A minimal streaming ASGI app (like an SSE token stream).
import asyncio


async def token_stream_app(scope, receive, send):
    await send({"type": "http.response.start", "status": 200,
                "headers": [(b"content-type", b"text/event-stream")]})
    for tok in ("Hello", " from", " ASGI"):
        await asyncio.sleep(0)                   # pretend each token takes a network round trip
        await send({"type": "http.response.body", "body": f"data: {tok}\n\n".encode(), "more_body": True})
    await send({"type": "http.response.body", "body": b"", "more_body": False})


async def main() -> None:
    sent = []

    async def receive():
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        sent.append(message)

    await token_stream_app({"type": "http", "path": "/stream"}, receive, send)
    print("status:", sent[0]["status"])
    print("body chunks:", [m["body"] for m in sent[1:]])


asyncio.run(main())
Output2 lines
status: 200
body chunks: [b'data: Hello\n\n', b'data:  from\n\n', b'data:  ASGI\n\n', b'']

The response starts with a http.response.start message, continues with body messages flagged more_body: True, and ends with an empty body with more_body: False. Each await send(...) is a suspension point where other requests can run, which is why one loop can hold thousands of open streams.

Exercise 12 (choose the model). For each workload, choose sync, threads, asyncio or processes, and say why: (a) 5,000 chat completions with a rate limit; (b) a vendor SDK with only a blocking client, 40 calls; (c) tokenizing 10 GB of text locally; (d) a 20-line script that summarizes one file.

Solution

(a) asyncio with a semaphore and a rate limiter: pure waiting, thousands pending. (b) Threads (to_thread or a ThreadPoolExecutor with a bounded size): blocking client, modest concurrency; async would need wrapping every call anyway. (c) Processes (ProcessPoolExecutor, with chunked input): CPU-bound, and threads would fight over the GIL in standard CPython (01C.5). (d) Plain synchronous code: nothing to overlap, and the simplest design wins.


Check yourself#

  1. What is the difference between a blocked call stack and a suspended one, and why can one thread serve thousands of suspended coroutines?
  2. Name the three stages of the evolution from callbacks to async/await. What do all three share?
  3. What does coro.send(None) do on a fresh coroutine, and how does a coroutine return a value?
  4. What is await equivalent to, and what must an object have to be awaitable?
  5. What are the three kinds of object the event loop schedules, and which one drives a coroutine?
  6. Does loop.create_task(coro()) run the coroutine before it returns? Does future.set_result(1) run the done-callbacks before it returns?
  7. List the six steps of one event-loop iteration in order. Where does the loop sleep?
  8. Why does a long-running callback delay timers that are not even related to it?
  9. A task yields None from its coroutine. What does the Task do? What if it yields a string?
  10. What does task.cancel() actually do, and what is the counter for?
  11. Why can TimeoutError only be caught outside async with asyncio.timeout(...)? What breaks it from inside?
  12. Why is loop.call_soon unsafe from another thread, and what does call_soon_threadsafe add?
  13. After asyncio.run(main()) finishes, what happens to tasks you never awaited and to open async generators? In what order?
  14. Why are threading.local values wrong for per-request data in async code, and what replaces them?
  15. Name two situations in which async is not worth it and what you would use instead.

Further resources#


← 01C.1: Concurrency, Parallelism and Context Switching | Module 01C overview | 01C.3: Race Conditions and Thread Safety →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close