01B.3 Async Python: async/await and the Event Loop

FoundationsLesson 3 of 1110,045 words8 parts
Module 01B · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

Almost everything an AI engineer's code does is waiting: waiting for an LLM API to generate a token stream, waiting for an embedding endpoint, waiting for a vector database, waiting for a webhook. A single LLM call takes one to thirty seconds, and for almost all of that time your CPU is doing nothing. Async Python is the language feature built for exactly this shape of work: it lets one thread juggle hundreds of tasks that are each mostly asleep, so the waits overlap instead of queueing up. This lesson teaches async/await and the event loop from first principles — what a coroutine really is, why forgetting one await silently does nothing, how tasks share one thread, how to cancel and time out work cleanly, and how to write the fake async backend (ScriptedBackend) that every later lesson in this module builds on. Everything runs on the standard library alone: no API key, no packages, no network.

What you'll learn

  • Why async exists: I/O-bound vs CPU-bound work, and the arithmetic of waiting (sequential vs concurrent timing, for real)
  • The mental model: coroutine functions vs coroutine objects, await as a pause point, the event loop as a scheduler, tasks, and cooperative scheduling
  • The core asyncio API: asyncio.run, create_task, gather (result order and return_exceptions), TaskGroup with ExceptionGroup/except*, asyncio.timeout vs wait_for, as_completed and wait(FIRST_COMPLETED), asyncio.sleep
  • The coordination primitives (Event, Lock, Semaphore, Queue) — enough to recognise them; the full patterns are lesson 01B.4
  • asyncio.to_thread for blocking code, run_in_executor awareness, contextvars, asyncio.Runner, and asyncio debug mode
  • Cancellation and errors: task.cancel(), CancelledError (and why you never swallow it), try/finally cleanup, asyncio.shield, "Task exception was never retrieved", partial results
  • Async iterators and context managers: async for, async with, __aiter__/__anext__, async generators and aclose, contextlib.asynccontextmanager
  • Mixing sync and async code: asyncio.run from sync, to_thread from async, why you can't nest asyncio.run (Jupyter, FastAPI), the SDK async clients, "function colouring", anyio/trio, uvloop, and free-threaded Python
  • A gallery of the classic async bugs, each with the real warning or traceback Python prints
  • ScriptedBackend: the fake async LLM client (async def complete(), async def stream()) that lessons 01B.4–01B.10 reuse

What you don't need

  • Any prior async experience — this lesson builds the model from zero. If you've written Promise.all in JavaScript or CompletableFuture code in Java, the "Coming from another stack" callouts will feel familiar.
  • Threads, processes or the GIL in depth. This lesson compares them in one table and one section; the full treatment is lesson 01B.4.
  • An API key, a provider SDK, or a running server. Every example is standard-library Python you can paste into a file and run.

Setup

You need Python 3.11 or newer (3.13 or 3.14 recommended) and nothing else — asyncio is in the standard library. Check your version:

bash
python3 --version

Save each snippet as a .py file and run it with python3 file.py, or inside a uv project with uv run python file.py (see 01B.1 if you haven't set one up yet). No API key needed — every call in this lesson is faked with asyncio.sleep and canned replies.


What you must be able to do after this lesson#

  • Explain why async helps with I/O-bound work and measure the speed-up
  • Explain what a coroutine, await and the event loop each do
  • Run coroutines concurrently with create_task, gather and TaskGroup
  • Apply a timeout with asyncio.timeout
  • Cancel a task safely without swallowing CancelledError
  • Call blocking code from async code with asyncio.to_thread
  • Use the ScriptedBackend fake async client in later lessons

Why this matters for an AI engineer#

You'll hear async discussed at every layer of the AI stack — SDK clients, web frameworks, agent loops, ingestion pipelines — and the same few ideas explain all of it:

You'll hear... You'll understand it after...
"Use the AsyncOpenAI client, not OpenAI" Part 1 and 6.3
"One await per request; the event loop multiplexes them" Part 2
"Never call a blocking SDK inside async def" Part 6 and the bugs gallery
"Bound the fan-out with a Semaphore" 3.7 (full patterns: 01B.4)
"asyncio.gather returns results in input order" 3.3
"A TaskGroup cancels siblings on failure" 3.4
"Wrap the stream in asyncio.timeout" 3.5
"Stream tokens with async for" Part 5 and 03.3, Part 10
"Close the client, or you leak connections" 6.3 and 03.9, 2.3
"Test it with a ScriptedBackend, no network" Part 7

Part 1: The problem async solves#

1.1 Waiting is the job#

Picture a support-ticket triage script. For each ticket it must (a) fetch the ticket over HTTP, (b) send the text to an LLM for classification, (c) write the result back. Steps (a) and (b) are network calls: the CPU sends a request and then sits idle while bytes travel and the remote machine thinks. A typical LLM call takes one to thirty seconds, and the CPU is busy for maybe a few milliseconds of it.

Now run that script over 100 tickets one at a time:

  • 100 tickets × ~2 s per call = ~200 seconds of wall-clock time, almost all of it spent waiting.
  • The CPU utilisation during those 200 seconds is close to zero.

The fix isn't a faster CPU or a bigger machine. It's overlapping the waits: while ticket 1's request is in flight, start ticket 2's, and ticket 3's, and so on. If the server can handle 20 requests at once, the same 100 tickets finish in roughly 5 × 2 s = ~10 seconds — up to a 20× speed-up from using the idle time that was already there.

1.2 I/O-bound vs CPU-bound#

The deciding question for any workload is: where does the time go?

Workload Time goes to Example in an AI product Right tool
I/O-bound Waiting on network, disk, other machines LLM API calls, database queries, file downloads, embedding batches Async (this lesson), or threads
CPU-bound Actual computation on this machine Tokenizing a huge corpus, computing embeddings locally with NumPy, resizing images Processes (separate cores), or native libraries that release the GIL

An LLM API call is the textbook I/O-bound task: ~99% waiting. That is why async is the pattern for AI engineering — almost everything you call is slow and remote.

1.3 Try it: sequential vs concurrent, for real#

asyncio.sleep is the perfect stand-in for a network wait: it pauses the coroutine without burning CPU, exactly like a socket read would. Here are five "API calls" of 0.2 s each, run one-at-a-time and then all-at-once:

python
# timing_demo.py — save and run: python3 timing_demo.py
import asyncio
import time

CALLS = 5
LATENCY = 0.2


async def fake_call(i: int) -> str:
    await asyncio.sleep(LATENCY)          # the "network wait"
    return f"reply {i}"


async def sequential() -> None:
    start = time.perf_counter()
    for i in range(CALLS):
        await fake_call(i)
    print(f"sequential : {time.perf_counter() - start:.2f} s")


async def concurrent() -> None:
    start = time.perf_counter()
    await asyncio.gather(*(fake_call(i) for i in range(CALLS)))
    print(f"concurrent : {time.perf_counter() - start:.2f} s")


async def main() -> None:
    await sequential()
    await concurrent()


asyncio.run(main())
Example output · illustrative2 lines
sequential : 1.00 s
concurrent : 0.20 s

Five waits of 0.2 s add up to 1.0 s sequentially, but overlap into ~0.2 s when concurrent — the whole batch takes about as long as the slowest single call. Scale that to 100 tickets at ~2 s each and you go from ~200 s to ~2–10 s depending on how many the provider lets you run at once. (How many is a rate-limit question, not an async question — that's 01B.4 and 03.9.)

1.4 Where async is not needed#

Async earns its complexity only when there are many overlapping waits. Be honest about the cases where it's overhead:

  • A single call. One LLM request has nothing to overlap with; await client... once is fine, but you gain nothing vs a sync call.
  • A short script or CLI that makes one or two calls. Sequential asyncio.run works, but plain sync code is simpler and perfectly fast.
  • CPU-bound work. Tokenizing, local embedding math, image processing — async won't help; see the table in 1.2.
  • Simple request/response web handlers where each request is independent — a framework like FastAPI still uses async underneath, but you may never write asyncio yourself (01B.7).

1.5 Threads vs processes vs async — the preview#

Three ways to overlap work, one row each. The details and the decision table are in Part 6 and 01B.4:

Approach How it overlaps Best for Cost
Async (asyncio) One thread switches between tasks at each await Many concurrent I/O waits (HTTP, DB, LLM calls) Single-threaded; a blocking call stalls everything
Threads (threading, concurrent.futures) OS schedules threads on multiple cores; threads block independently Blocking I/O, legacy sync libraries, some CPU work GIL limits pure-Python CPU parallelism; more memory per thread
Processes (multiprocessing, ProcessPoolExecutor) Separate interpreters on separate cores CPU-bound work: heavy math, parsing, local models Highest overhead; data must be pickled between processes

For AI engineering the answer is almost always async for the network calls, threads for the occasional blocking library, processes for the rare CPU-heavy job. Keep that table; 01B.4 makes it precise.


Part 2: The mental model — coroutines, await and the event loop#

2.1 async def makes a coroutine function, not a coroutine#

Writing async def in front of a function does something subtle and crucial: it makes calling that function return a coroutine object instead of running it. Nothing executes until something else drives it.

python
# coroutine_basics.py — run: python3 coroutine_basics.py
import asyncio
import gc
import inspect


async def fetch_ticket(ticket_id: int) -> str:
    print(f"  fetch_ticket({ticket_id}) is actually running")
    await asyncio.sleep(0)                       # even the tiniest await
    return f"ticket-{ticket_id}"


print("1. call the function:")
coro = fetch_ticket(7)
print("   type:", type(coro).__name__)
print("   is a coroutine object:", inspect.iscoroutine(coro))
print("   name:", coro.__qualname__)

print("2. nothing ran yet — no 'actually running' line above")

print("3. drive it one step at a time:")
coro.send(None)                                  # runs until the first await
print("   after send(None): paused at the await")
try:
    coro.send(None)
except StopIteration as done:
    print("   finished, return value:", done.value)

print("4. the forgotten-coroutine warning:")
fetch_ticket(99)                                 # created, never awaited, dropped
# The RuntimeWarning is printed when the object is garbage-collected;
# gc.collect() makes it happen here instead of at an unpredictable moment.
gc.collect()

Output (the RuntimeWarning goes to the error stream, so it may appear before the prints when output is piped — in a terminal it shows where it happens):

text
1. call the function:
   type: coroutine
   is a coroutine object: True
   name: fetch_ticket
2. nothing ran yet — no 'actually running' line above
3. drive it one step at a time:
  fetch_ticket(7) is actually running
   after send(None): paused at the await
   finished, return value: ticket-7
4. the forgotten-coroutine warning:
coroutine_basics.py:30: RuntimeWarning: coroutine 'fetch_ticket' was never awaited
  fetch_ticket(99)                                 # created, never awaited, dropped
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Read that carefully — it contains the three facts everything else builds on:

  1. Calling an async def function does not run it. fetch_ticket(7) returned a coroutine object — a paused computation, like a function call that was written down but not yet executed. inspect.iscoroutine confirms it.
  2. A coroutine only runs when driven. coro.send(None) started it; it printed its line, hit await asyncio.sleep(0), and paused, handing control back. The second send finished it, and its return value arrived inside the StopIteration exception (done.value — that's just how generators and coroutines report a return value).
  3. Creating a coroutine and dropping it is a bug. fetch_ticket(99) was never awaited, so it never ran — and Python warns coroutine 'fetch_ticket' was never awaited when the object is collected. This warning is the #1 async beginner bug; you'll see its cousins in Part 8.

2.2 await: the pause point#

await does two things at once:

  • It pauses the current coroutine and returns control to the event loop.
  • It arranges to resume this coroutine when the awaited thing finishes (a timer, a socket read, another task).

Two rules fall out:

  • await is only legal inside async def. Try it in a plain function and you get SyntaxError: 'await' outside async function.
  • Only awaitables can be awaited: coroutines, tasks, and futures. await 42 gives TypeError: object int can't be used in 'await' expression.

2.3 The event loop: the scheduler#

The event loop is the piece of code that actually runs your coroutines. It keeps a list of tasks that are ready to run, runs each one until it hits an await, parks it, runs the next ready one, and repeats. When nothing is ready, it sleeps in the operating system's I/O multiplexing call (epoll on Linux, kqueue on macOS, IOCP on Windows) and wakes when a socket, timer or signal has news.

flowchart LR
    subgraph caller ["Your code"]
        S["asyncio.run(main())"]
    end
    subgraph loop ["event loop — one thread"]
        R["ready queue"]
        E["OS I/O wait<br/>(epoll / kqueue / IOCP)"]
        T1["task A: paused at await"]
        T2["task B: paused at await"]
        T3["task C: paused at await"]
        R --> T1 & T2 & T3
        T1 & T2 & T3 -->|"hits an await"| R
        R -->|"queue empty"| E
        E -->|"I/O or timer ready"| R
    end
    S --> loop

Key properties:

  • One thread. The default loop runs everything on a single thread. Hundreds of tasks share it; only one runs at any instant.
  • Cooperative, not preemptive. A task keeps running until it awaits something that isn't immediately ready. The loop cannot interrupt a task that never awaits — that's the blocking bug in Part 8.
  • I/O multiplexing. While tasks wait on sockets or timers, the OS wakes the loop the moment any of them is ready. This is how one thread serves thousands of connections.

asyncio.run(main()) is the standard entry point: it creates an event loop, runs main() to completion inside it, then closes the loop. Call it once, at the bottom of your script.

2.4 Tasks: coroutines the loop schedules#

A task is a coroutine that the event loop has been asked to schedule independently. asyncio.create_task(coro) wraps the coroutine in a Task and puts it on the loop's schedule; it starts running at the next opportunity, concurrently with whatever else is running.

python
# interleave_demo.py — run: python3 interleave_demo.py
import asyncio


async def worker(name: str, steps: int = 3) -> None:
    for i in range(1, steps + 1):
        print(f"{name} step {i}")
        await asyncio.sleep(0)          # pause: let the other tasks run
    print(f"{name} done")


async def main() -> None:
    # create_task schedules each coroutine as an independent task
    a = asyncio.create_task(worker("A"))
    b = asyncio.create_task(worker("B"))
    c = asyncio.create_task(worker("C"))
    await asyncio.gather(a, b, c)


asyncio.run(main())
Output12 lines
A step 1
B step 1
C step 1
A step 2
B step 2
C step 2
A step 3
B step 3
C step 3
A done
B done
C done

Watch the interleaving: main created three tasks, then gather awaited all of them. The loop ran A's step 1, hit its await, switched to B's step 1, then C's, then back to A's step 2 — round-robin at every pause point. That's the whole trick: each await asyncio.sleep(0) is a voluntary "my turn is over, someone else go". A real await on a network call parks the task until the data arrives, which can be seconds — and the loop fills those seconds with other tasks' work.

sequenceDiagram
    participant M as main()
    participant L as event loop
    participant A as task A
    participant B as task B
    participant C as task C
    M->>L: asyncio.run(main())
    M->>A: create_task(worker A)
    M->>B: create_task(worker B)
    M->>C: create_task(worker C)
    L->>A: step 1 runs
    A-->>L: await sleep → yields
    L->>B: step 1 runs
    B-->>L: await sleep → yields
    L->>C: step 1 runs
    C-->>L: await sleep → yields
    L->>A: step 2 runs
    A-->>L: await sleep → yields
    L->>B: step 2 runs
    B-->>L: await sleep → yields
    L->>C: step 2 runs
    C-->>L: await sleep → yields
    L->>A: step 3, returns
    L->>B: step 3, returns
    L->>C: step 3, returns
    L-->>M: gather() returns [A, B, C]

2.5 asyncio.sleep vs time.sleep — the canonical trap#

This is the single most important distinction in the lesson:

time.sleep(1) await asyncio.sleep(1)
What it does Blocks the whole thread for 1 s Pauses only this coroutine; the loop runs other tasks
CPU Sleeps at OS level — no CPU burned, but the loop can't run Frees the thread entirely
In async code Freezes every other task The intended way to wait

time.sleep is for synchronous code. Inside async def, always write await asyncio.sleep(...). Part 8 demonstrates the freeze with a heartbeat task. (asyncio.sleep(0) is special: it doesn't wait at all — it just yields control once, which is how the interleaving demo above works.)

2.6 Running coroutines in a REPL or notebook#

In a plain script, asyncio.run(main()) is the entry point. In Jupyter/IPython, the notebook kernel already runs an event loop, so asyncio.run(...) fails with RuntimeError: asyncio.run() cannot be called from a running event loop — and pasting it is the classic notebook mistake (03.9, 2.5 reproduces it). The fix is to use the notebook's own loop: write await main() or results = await classify_all() at the top level of a cell — IPython and Jupyter support top-level await. The standalone python -m asyncio REPL (Python 3.8+) gives you the same top-level await in a terminal:

pycon
>>> import asyncio
>>> await asyncio.sleep(0)
>>> print("top-level await works")
top-level await works

(The >>> prompts mark a REPL transcript; everything else in this lesson is a .py file you save and run.)


Part 3: The core asyncio API#

This part is the reference shelf: the functions you'll actually call. Each gets a runnable example; the patterns built on them (bounded fan-out, worker pools, rate limiting) are lesson 01B.4's job.

3.1 asyncio.run — the entry point#

python
async def main() -> None:
    ...

asyncio.run(main())        # create a loop, run main() to the end, close the loop

Rules that matter:

  • Call it once per program, at the top level (bottom of the script). It cannot be nested — 6.1 covers the error and the fixes.
  • It cancels leftover tasks when main() returns: any create_task you forgot to await is cancelled, not leaked. Convenient — but it also means fire-and-forget tasks silently die at the end of main() (Part 8).
  • In Python 3.11+ you can instead use asyncio.Runner, a reusable context manager for running async code from sync code (3.9).

3.2 asyncio.create_task — schedule independently#

python
task = asyncio.create_task(coro(), name="fetch-ticket-7")
  • The coroutine starts at the next loop iteration, concurrently with the caller.
  • The returned Task is a Future: await task gives its return value, task.result() works after it's done, task.done()/task.cancelled() report state.
  • Keep a reference. The event loop holds only a weak reference to tasks. A task with no strong reference can be garbage-collected mid-flight — the "Task was destroyed but it is pending!" bug in Part 8.
  • name= is worth setting: it shows up in tracebacks, debug logs and asyncio.all_tasks().
  • asyncio.current_task() returns your own Task — the standard way to get a handle on yourself for naming, self-cancellation or debugging; asyncio.all_tasks() lists every task on the loop.

3.3 asyncio.gather — fan out and collect#

gather is the workhorse: pass it several awaitables, it schedules them all concurrently, and returns a list of results in input order — regardless of which finished first.

python
# gather_demo.py — run: python3 gather_demo.py
import asyncio


async def fetch(label: str, delay: float) -> str:
    await asyncio.sleep(delay)
    if label == "b":
        raise ValueError("ticket database is down")
    return f"{label} reply"


async def main() -> None:
    # Deliberately submit in an order that finishes OUT of order:
    # "slow" sleeps longest but is listed first.
    labels = [("slow", 0.05), ("b", 0.01), ("fast", 0.0)]

    print("== gather with return_exceptions=True ==")
    results = await asyncio.gather(
        *(fetch(label, delay) for label, delay in labels),
        return_exceptions=True,
    )
    for (label, _), result in zip(labels, results):
        print(f"  {label:<5} -> {result!r}")

    print("== gather without it: the first exception wins ==")
    try:
        await asyncio.gather(*(fetch(label, delay) for label, delay in labels))
    except ValueError as e:
        print("  raised:", type(e).__name__, "-", e)


asyncio.run(main())
Output6 lines
== gather with return_exceptions=True ==
  slow  -> 'slow reply'
  b     -> ValueError('ticket database is down')
  fast  -> 'fast reply'
== gather without it: the first exception wins ==
  raised: ValueError - ticket database is down

Three facts to memorise:

  1. Order is preserved. results[i] is the answer for input i — "slow" is first even though it finished last. Same guarantee as Promise.all.
  2. return_exceptions=True turns failures into values. The ValueError sits in the results list as an exception instance instead of exploding the whole batch — the pattern for "give me partial results" (01B.4 builds a proper Result type on it).
  3. Without it, the first exception propagates — and the other tasks keep running. gather raises ValueError, but "slow" and "fast" didn't stop; their results are simply discarded. The waste is real — billed requests and side effects continue in the background — but you will not get a "Task exception was never retrieved" warning even if an orphan fails later: gather installs a done-callback on every child that marks late-finishing exceptions as retrieved. (That warning is real for raw create_task fire-and-forget — 4.2.) What gather can't give you is cancellation: the orphans run to completion regardless, which is exactly what TaskGroup prevents.

3.4 TaskGroup — structured concurrency#

asyncio.TaskGroup (Python 3.11+) is the modern, safer alternative to manual create_task + gather. It gives you structured concurrency: the tasks' lifetimes are nested inside the async with block, so you can't leave a task running by accident.

python
# taskgroup_demo.py — run: python3 taskgroup_demo.py
import asyncio


async def worker(name: str, fail: bool = False) -> str:
    try:
        for i in range(6):
            await asyncio.sleep(0)
            print(f"{name} step {i}")
            if fail and i == 3:
                raise RuntimeError(f"{name} exploded")
        return f"{name} ok"
    except asyncio.CancelledError:
        print(f"{name} was cancelled")
        raise


async def main() -> None:
    print("== one task fails inside a TaskGroup ==")
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(worker("good-1"))
            tg.create_task(worker("bad", fail=True))
            tg.create_task(worker("good-2"))
    except* RuntimeError as group:
        print("caught by except*:", [str(e) for e in group.exceptions])


asyncio.run(main())
Output17 lines
== one task fails inside a TaskGroup ==
good-1 step 0
bad step 0
good-2 step 0
good-1 step 1
bad step 1
good-2 step 1
good-1 step 2
bad step 2
good-2 step 2
good-1 step 3
bad step 3
good-2 step 3
good-1 step 4
good-2 was cancelled
good-1 was cancelled
caught by except*: ['bad exploded']

What just happened, precisely:

  • bad raised RuntimeError at step 3.
  • The TaskGroup cancelled its siblings — good-1 and good-2 got CancelledError at their next await (that's the "was cancelled" lines; note they re-raised, as they must).
  • The group waited for every task to actually finish unwinding, then raised an ExceptionGroup — a single exception containing all the failures (a BaseExceptionGroup when a failure is a BaseException rather than an Exception; except* matches both).
  • except* RuntimeError as group is the matching handler (except-star): it catches only the RuntimeErrors inside the group; group.exceptions is the tuple of matched exceptions. Other exception types would propagate separately.

This is the behaviour you want for fan-out: one failure shouldn't leave siblings running (they're still costing money and holding connections), and failures arrive together, typed, instead of vanishing into "never retrieved" warnings. gather is fine for "run these, collect whatever comes back"; TaskGroup is better for "these tasks are one unit of work — succeed or fail together". 03.9, 4.3 compares them on real SDK calls.

3.5 Timeouts: asyncio.timeout vs wait_for#

Every network call needs a timeout — an unbounded await on a dead connection hangs your worker forever. Two APIs:

python
# timeouts_demo.py — run: python3 timeouts_demo.py
import asyncio


async def slow() -> str:
    await asyncio.sleep(10)          # stands in for a hung API call
    return "never"


async def main() -> None:
    print("== asyncio.timeout (a context manager around any code) ==")
    try:
        async with asyncio.timeout(0.05):
            await slow()
    except TimeoutError:
        print("  caught builtin TimeoutError")

    print("== asyncio.wait_for (wraps one awaitable) ==")
    try:
        await asyncio.wait_for(slow(), timeout=0.05)
    except TimeoutError:
        print("  caught builtin TimeoutError")

    print("== asyncio.TimeoutError is the same object ==")
    print(" ", asyncio.TimeoutError is TimeoutError)


asyncio.run(main())
Output6 lines
== asyncio.timeout (a context manager around any code) ==
  caught builtin TimeoutError
== asyncio.wait_for (wraps one awaitable) ==
  caught builtin TimeoutError
== asyncio.TimeoutError is the same object ==
  True
  • async with asyncio.timeout(seconds) (3.11+) wraps any block of code — several awaits, a whole pipeline stage — and raises builtin TimeoutError when the deadline passes. It cancels the code inside, then converts the resulting CancelledError into TimeoutError. This is the one to reach for.
  • await asyncio.wait_for(awaitable, timeout) wraps a single awaitable. Since Python 3.12 it's implemented on top of asyncio.timeout, so behaviour matches; the context-manager form is more flexible (it can cover multiple awaits and non-task code).
  • asyncio.TimeoutError is TimeoutError (same object since 3.11) — except TimeoutError catches both.

3.6 as_completed and wait — completion order and first-done#

gather waits for all tasks and returns in input order. Sometimes you want the opposite: process results as they finish, or react to the first one.

python
# wait_demo.py — run: python3 wait_demo.py
import asyncio


async def job(name: str, gate: asyncio.Event) -> str:
    await gate.wait()                    # "work" finishes when we open the gate
    return f"{name} finished"


async def run_as_completed() -> None:
    gates = {name: asyncio.Event() for name in "abc"}
    tasks = {name: asyncio.create_task(job(name, gates[name]), name=name) for name in "abc"}
    it = iter(asyncio.as_completed(tasks.values()))
    # Finish them OUT of submission order: c, then a, then b — and consume
    # each result before opening the next gate, so the order can't be luck.
    print("== as_completed ==")
    for name in ("c", "a", "b"):
        gates[name].set()
        await asyncio.wait({tasks[name]})     # that one task is really done
        print(" ", await next(it))


async def run_wait() -> None:
    gates = {name: asyncio.Event() for name in "abc"}
    tasks = [asyncio.create_task(job(name, gates[name]), name=name) for name in "abc"]
    gates["b"].set()                      # only "b" finishes
    await asyncio.sleep(0)
    print("== wait(FIRST_COMPLETED) ==")
    done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    print("  done:", sorted(t.get_name() for t in done))
    print("  pending:", sorted(t.get_name() for t in pending))
    for t in pending:
        t.cancel()
    await asyncio.gather(*pending, return_exceptions=True)


async def main() -> None:
    await run_as_completed()
    await run_wait()


asyncio.run(main())
Output7 lines
== as_completed ==
  c finished
  a finished
  b finished
== wait(FIRST_COMPLETED) ==
  done: ['b']
  pending: ['a', 'c']
  • asyncio.as_completed(tasks) yields awaitables in the order tasks complete. Each yielded future resolves to that task's result. Use it for "process whichever finishes first" — progress bars, first-success-wins races, streaming partial results.
  • await asyncio.wait(tasks, return_when=...) returns (done, pending) sets without raising on task exceptions. FIRST_COMPLETED (the default is ALL_COMPLETED) returns as soon as any task finishes — the primitive for "race several calls, take the winner". You must handle the pending set yourself (cancel or keep waiting), which is why TaskGroup/gather are usually nicer.

3.7 The coordination primitives: Event, Lock, Semaphore, Queue#

Four classes for tasks to talk to each other. You only need to recognise them now — the real patterns (worker pools, rate limiters, pipelines, backpressure) are 01B.4.

python
# primitives_demo.py — run: python3 primitives_demo.py
import asyncio


async def demo_event() -> None:
    ready = asyncio.Event()

    async def waiter() -> None:
        await ready.wait()
        print("  event: waiter released")

    t = asyncio.create_task(waiter())
    await asyncio.sleep(0)
    print("  event: still waiting?", not ready.is_set())
    ready.set()
    await t


async def demo_semaphore() -> None:
    sem = asyncio.Semaphore(2)          # at most 2 at once
    running = 0
    peak = 0

    async def worker(i: int) -> None:
        nonlocal running, peak
        async with sem:
            running += 1
            peak = max(peak, running)
            await asyncio.sleep(0)
            running -= 1

    await asyncio.gather(*(worker(i) for i in range(6)))
    print(f"  semaphore: 6 workers, peak in flight = {peak}")


async def demo_queue() -> None:
    q: asyncio.Queue[int | None] = asyncio.Queue()

    async def consumer() -> None:
        while True:
            item = await q.get()
            if item is None:                      # sentinel: shut down
                q.task_done()
                return
            print(f"  queue: consumed {item}")
            q.task_done()

    c = asyncio.create_task(consumer())
    for i in range(3):
        await q.put(i)
    await q.put(None)
    await q.join()                                 # wait until all task_done()
    await c


async def main() -> None:
    await demo_event()
    await demo_semaphore()
    await demo_queue()


asyncio.run(main())
Output6 lines
  event: still waiting? True
  event: waiter released
  semaphore: 6 workers, peak in flight = 2
  queue: consumed 0
  queue: consumed 1
  queue: consumed 2
Primitive One-line job AI-engineering use
asyncio.Event One task signals "it's ready" to others Startup/shutdown flags, "model loaded" signals
asyncio.Lock Only one task holds it at a time Protecting shared state (caches, counters, files)
asyncio.Semaphore(n) At most n tasks inside at once Bounded concurrency — the rate-limit dial
asyncio.Queue Producer/consumer hand-off Worker pools, streaming pipelines, backpressure

3.8 asyncio.to_thread and run_in_executor#

Sometimes you're stuck with a blocking function — a sync SDK, a file read, a CPU chunk. await asyncio.to_thread(fn, *args) (3.9+) runs it on a worker thread so the loop stays free:

python
# to_thread_demo.py — run: python3 to_thread_demo.py
import asyncio
import threading
import time

loop_is_free = threading.Event()


def blocking_work() -> str:
    """Stands in for a sync SDK call that blocks for ~0.15 s."""
    time.sleep(0.15)
    return "sync result"


async def heartbeat() -> int:
    beats = 0
    while not loop_is_free.is_set():
        await asyncio.sleep(0.01)
        beats += 1
        if beats == 8:                      # exactly 8 beats, then signal done
            loop_is_free.set()
    return beats


async def main() -> None:
    hb = asyncio.create_task(heartbeat())
    await asyncio.sleep(0.03)               # heartbeat is running
    result = await asyncio.to_thread(blocking_work)   # blocking work off-loop
    beats = await hb
    print("thread returned:", result)
    print(f"heartbeats during the thread call: {beats}   <- loop never froze")


asyncio.run(main())
Output2 lines
thread returned: sync result
heartbeats during the thread call: 8   <- loop never froze

The heartbeat task kept beating while the blocking call ran on a side thread — the loop was never frozen. await asyncio.to_thread(sync_fn, arg) is the escape hatch whenever a library gives you only a sync API. Caveats: the default executor is a small thread pool (min(32, cpu_count + 4) threads), to_thread copies the current contextvars context into the thread (good — request IDs propagate), and it does not help CPU-bound work (the GIL means threads don't parallelise pure Python — 01B.4).

loop.run_in_executor(executor, fn, *args) is the lower-level API to_thread wraps — it lets you choose the executor (a custom ThreadPoolExecutor or ProcessPoolExecutor). You'll meet it in libraries; prefer to_thread in your own code.

3.9 asyncio.Runner and debug mode#

asyncio.Runner (3.11+) is a context manager for running async code from synchronous code — useful when main() isn't your only entry point (tests, REPLs, callbacks):

python
# runner_ctx.py — run: python3 runner_ctx.py
import asyncio
import contextvars

request_id = contextvars.ContextVar("request_id", default="none")


async def handle() -> str:
    # contextvars set by the caller are visible inside tasks automatically
    return f"handling request {request_id.get()}"


async def main() -> None:
    request_id.set("req-42")
    a = asyncio.create_task(handle())
    b = asyncio.create_task(handle())
    print(await asyncio.gather(a, b))


def sync_entry() -> None:
    # asyncio.Runner: a reusable, explicit way to run async code from sync code
    with asyncio.Runner() as runner:
        print(runner.run(main()))


sync_entry()
Output2 lines
['handling request req-42', 'handling request req-42']
None

Two things in that demo worth noting:

  • contextvars.ContextVar is how you carry per-request state (request IDs, tenant IDs, tracing context) through async code without passing it as arguments. Each task sees the value set where it was created; asyncio.to_thread copies it into the worker thread. This is the mechanism behind every modern logging/tracing library.
  • Runner.run() can be called repeatedly on the same runner — each call runs a fresh main()-style coroutine to completion.

Debug mode makes the loop noisy on purpose — it logs slow callbacks, unretrieved exceptions and unawaited coroutines that production would hide:

bash
PYTHONASYNCIODEBUG=1 python3 your_script.py      # or: python3 -X dev your_script.py

(PowerShell: $env:PYTHONASYNCIODEBUG=1; python your_script.py; cmd: set PYTHONASYNCIODEBUG=1 && python your_script.py.)

-X dev enables asyncio debug plus other development checks (warnings, faulthandler). Inside code you can query it:

python
import asyncio

async def main() -> None:
    print("loop debug mode:", asyncio.get_running_loop().get_debug())

asyncio.run(main())
Output · with PYTHONASYNCIODEBUG=1 or -X dev; False in a normal run1 line
loop debug mode: True

Use it while developing; the slow-callback warnings it emits are how you catch blocking calls (Part 8). In debug mode a callback or task step that holds the loop for more than 100 ms (the default loop.slow_callback_duration) is logged as a "slow callback" — a blocking call announcing itself.


Part 4: Cancellation and errors#

Deep-dive

4.1 task.cancel() and CancelledError#

Any task can be cancelled: task.cancel() schedules a CancelledError to be raised inside the coroutine at its next await. The task then unwinds — running finally blocks and async with/async for cleanups — and finishes as cancelled.

python
# cancel_demo.py — run: python3 cancel_demo.py
import asyncio

started = asyncio.Event()


async def worker() -> None:
    try:
        print("worker step 0")
        started.set()                     # tell main: we're running now
        for i in range(1, 5):
            await asyncio.sleep(0)
            print(f"worker step {i}")
    except asyncio.CancelledError:
        print("worker saw CancelledError")
        raise                          # always re-raise: never swallow it
    finally:
        print("worker cleanup ran")


async def shielded() -> None:
    try:
        await asyncio.sleep(0.06)
        print("shielded inner completed")
    except asyncio.CancelledError:
        print("shielded inner was cancelled")
        raise


async def main() -> None:
    print("== cancel a task ==")
    t = asyncio.create_task(worker(), name="worker")
    await started.wait()                  # cancel exactly after step 0
    t.cancel()
    try:
        await t
    except asyncio.CancelledError:
        print("await t raised CancelledError; t.cancelled() =", t.cancelled())

    print("== shield: outer cancelled, inner keeps going ==")
    inner = asyncio.ensure_future(shielded())
    # shield() returns a Future, not a coroutine — ensure_future accepts
    # both; create_task would reject the Future with a TypeError.
    outer = asyncio.ensure_future(asyncio.shield(inner))
    await asyncio.sleep(0.01)
    outer.cancel()
    try:
        await outer
    except asyncio.CancelledError:
        print("outer task cancelled")
    print("inner result:", await inner)


asyncio.run(main())
Output9 lines
== cancel a task ==
worker step 0
worker saw CancelledError
worker cleanup ran
await t raised CancelledError; t.cancelled() = True
== shield: outer cancelled, inner keeps going ==
outer task cancelled
shielded inner completed
inner result: None

The rules:

  • CancelledError inherits from BaseException, not Exception (since 3.8) — a bare except Exception won't catch it, which is deliberate: cancellation must propagate.
  • Never swallow it. If you catch CancelledError, clean up and raise again (or raise a different exception only if you truly mean to convert it). Swallowing cancellation breaks timeouts, TaskGroup shutdown and server disconnect handling.
  • try/finally is your cleanup guarantee. The finally ran even though the task was cancelled mid-await — close files, release locks, write "cancelled" status there.
  • await t on a cancelled task raises CancelledError in the awaiting code too; check t.cancelled() to distinguish "was cancelled" from "failed".
  • asyncio.shield(inner) protects inner from the outer cancellation: cancelling the shielded await stops waiting but lets inner finish. Use it for "save this checkpoint even if the caller goes away" — and understand it also means the work keeps costing money after the user is gone, so it's a deliberate choice, not a default.

These are the warnings Python actually prints; learn to recognise them:

"Task exception was never retrieved" — a task raised, finished, and nobody ever called result()/exception()/await on it:

python
# never_retrieved.py — run: python3 never_retrieved.py
import asyncio


async def boom() -> None:
    await asyncio.sleep(0)
    raise ValueError("something went wrong")


async def main() -> None:
    t = asyncio.create_task(boom(), name="boom")
    await asyncio.sleep(0.01)          # let it fail; nobody awaits t
    print("main is done; t's exception was never retrieved")


asyncio.run(main())

Output (the path shown is the machine's own; like §2.1, the warning goes to the error stream, so it can appear before the main is done print when output is piped — in a terminal it shows where it happens):

text
Task exception was never retrieved
future: <Task finished name='boom' coro=<boom() done, defined at /path/to/never_retrieved.py:5> exception=ValueError('something went wrong')>
Traceback (most recent call last):
  File "/path/to/never_retrieved.py", line 7, in boom
    raise ValueError("something went wrong")
ValueError: something went wrong
main is done; t's exception was never retrieved

The fix is always the same: await every task you create, or call task.exception() to mark it retrieved. gather/TaskGroup/as_completed all retrieve for you — that's part of why they're safer than raw create_task.

"Task was destroyed but it is pending!" — a pending task lost its last strong reference and was garbage-collected mid-flight:

python
# lost_task.py — run: python3 lost_task.py
import asyncio


async def slow() -> None:
    await asyncio.sleep(60)


async def main() -> None:
    asyncio.create_task(slow(), name="lost")   # fire-and-forget, no reference
    # main returns while 'lost' is still pending


loop = asyncio.new_event_loop()
loop.run_until_complete(main())
loop.close()          # pending task destroyed here -> the warning
Output · again, the path is the machine's own2 lines
Task was destroyed but it is pending!
task: <Task pending name='lost' coro=<slow() done, defined at /path/to/lost_task.py:5> wait_for=<Future pending cb=[Task.task_wakeup()]>>>

The event loop keeps only a weak reference to tasks — asyncio.create_task(...) whose result you don't store can vanish mid-execution. Keep tasks in a list/set/dict (or use TaskGroup, which holds them), and always give fire-and-forget work an owner.

RuntimeError: asyncio.run() cannot be called from a running event loop — nesting entry points. Covered in 6.1.

RuntimeWarning: coroutine '...' was never awaited — the forgotten-coroutine warning from 2.1: you called an async def and dropped the result. Usually a missing await or a missing create_task.

4.3 Partial results and graceful failure#

Real fan-out shouldn't be all-or-nothing. The production shape is: run everything, collect successes and failures, report both. gather(return_exceptions=True) gives you the raw material; 01B.4 turns it into a Result type with per-item errors. For timeouts that leave siblings running, asyncio.wait + explicit pending-set handling is the lower-level tool. The principle to carry forward: decide your failure policy per call site — fail-fast (TaskGroup), partial-results (gather+return_exceptions), or first-success-wins (wait/as_completed) — and write it down, because the default is never what you want.


Part 5: Async iterators and context managers#

Deep-dive

5.1 async for and async with#

Async code needs async versions of the two protocols every Python programmer knows:

Sync Async
for x in iterable: async for x in async_iterable:
with cm: async with acm:
__iter__ / __next__ __aiter__ / __anext__
__enter__ / __exit__ __aenter__ / __aexit__

async for appears everywhere in AI code: iterating an LLM token stream, reading SSE events, paging through API results. async with appears for clients and streams: async with httpx.AsyncClient() as client: and async with stream: are how SDKs guarantee connections close — the pattern 03.3, Part 10 uses for every provider.

5.2 Async generators#

An async generator is an async def that uses yield — it produces values one at a time, and each __anext__ can await between yields. This is the shape of a streaming LLM response: tokens arrive over time, and the consumer processes each as it lands.

python
# asyncgen_demo.py — run: python3 asyncgen_demo.py
import asyncio
import contextlib
from collections.abc import AsyncIterator


async def token_stream(words: list[str], delay: float = 0.0) -> AsyncIterator[str]:
    """An async generator: yields tokens like a streaming LLM SDK does."""
    for w in words:
        await asyncio.sleep(delay)
        yield w


@contextlib.asynccontextmanager
async def timer(label: str) -> AsyncIterator[None]:
    print(f"{label}: start")
    try:
        yield
    finally:
        print(f"{label}: end")


async def main() -> None:
    print("== async for over an async generator ==")
    async for tok in token_stream(["the", "cat", "sat"]):
        print("  token:", tok)

    print("== aclose() stops it early ==")
    gen = token_stream(["a", "b", "c", "d"])
    print("  first:", await gen.__anext__())
    await gen.aclose()
    try:
        await gen.__anext__()
    except StopAsyncIteration:
        print("  closed: StopAsyncIteration")

    print("== async with (asynccontextmanager) ==")
    async with timer("demo"):
        print("  inside the block")


asyncio.run(main())
Output11 lines
== async for over an async generator ==
  token: the
  token: cat
  token: sat
== aclose() stops it early ==
  first: a
  closed: StopAsyncIteration
== async with (asynccontextmanager) ==
demo: start
  inside the block
demo: end

Rules of the road:

  • Consume with async for chunk in gen: or manually with await gen.__anext__() (StopAsyncIteration ends it, like StopIteration for sync generators).
  • await gen.aclose() when you stop early — it throws GeneratorExit inside at the current yield, running the generator's finally blocks (closing the upstream HTTP stream, in real SDKs). Breaking out of async for does not close it automatically; use async with or call aclose().
  • @contextlib.asynccontextmanager turns an async generator into an async context manager: yield once inside try/finally and you get async with for free. It's how you write cleanup wrappers (timers, locks, sessions) without a class.

This is exactly the mechanism behind SDK streaming: client.responses.create(..., stream=True) returns an async stream you consume with async for — the full per-provider forms are in 03.3, 10.1, and the wire format underneath is 03.3, Part 2.


Part 6: Mixing sync and async#

Deep-dive

6.1 Calling async from sync, and sync from async#

The two directions, and the one forbidden combination:

You have You want The tool
Sync code (a def, a CLI main, a pytest test) To run a coroutine asyncio.run(coro()) — once, top level
Async code (async def) To call a blocking function await asyncio.to_thread(fn, ...)
Async code To call another coroutine await coro() or create_task/gather/TaskGroup
Inside a running loop To call asyncio.run again Forbidden — RuntimeError
python
# nested_run.py — run: python3 nested_run.py
import asyncio


async def hello() -> str:
    return "hi"


async def main() -> None:
    print("== asyncio.run inside a running loop ==")
    try:
        asyncio.run(hello())
    except RuntimeError as e:
        print("RuntimeError:", e)


asyncio.run(main())

Output (the RuntimeWarning goes to the error stream and can appear before the prints when output is piped — same caveat as 2.1):

text
nested_run.py:14: RuntimeWarning: coroutine 'hello' was never awaited
  print("RuntimeError:", e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
== asyncio.run inside a running loop ==
RuntimeError: asyncio.run() cannot be called from a running event loop

Read the warning too: hello() is evaluated as asyncio.run's argument before run raises — so a coroutine object is created and immediately dropped, which is exactly the forgotten-coroutine warning from 2.1. That's not a quirk of this demo; it's the same bug shape as a missing await, and it's why the fixes below matter.

This fires in exactly the places beginners hit it:

  • Jupyter/notebooks — the kernel already runs a loop. Fix: top-level await in the cell (2.6); the detailed reproduction is 03.9, 2.5.
  • Inside FastAPI/Starlette handlers — the server owns the loop. Fix: make the handler async def and await inside it (01B.7); never call asyncio.run there.
  • Nested asyncio.run in sync code — if main() itself calls asyncio.run, you get this error. Fix: await the inner coroutine instead, or restructure so only the outermost call uses run.
  • Calling async from sync inside a loop — e.g., a sync callback invoked by the loop that tries asyncio.run. Fix: asyncio.run_coroutine_threadsafe(coro, loop) schedules it onto the running loop from another thread (rare; prefer restructuring).

6.2 Sync code inside async: to_thread and run_in_executor#

Covered in 3.8: await asyncio.to_thread(blocking_fn, arg) runs the blocking call on a worker thread while the loop keeps scheduling. It's the escape hatch for sync-only libraries — but it's a pressure valve, not a design. If a library is sync-only and you call it constantly, the thread pool saturates and you're back to serial waits; the real fix is the async version of the library (the SDKs all ship one — 6.3).

6.3 The SDK clients and "function colouring"#

Every major provider SDK ships two clients: a sync one and an async one. The names, as of November 2026:

Provider Sync client Async client
OpenAI OpenAI AsyncOpenAI
Anthropic Anthropic AsyncAnthropic
Google Gemini (google-genai) genai.Client genai.Client(...).aio (AsyncModels etc.)
OpenRouter OpenAI with base_url AsyncOpenAI with base_url

The rules that matter for your own code:

  • One client per process, shared across tasks, closed properly. Each async client owns a connection pool; create it once, await client.close() (or async with) at shutdown. 03.9, 2.3 owns the details — a client created per task defeats pooling and exhausts file descriptors.
  • Match client to context. In an async def service (FastAPI, a worker pool), use the async client. In a sync script or a sync test, the sync client is fine. Never call the sync client inside async def — it blocks the loop (Part 8 shows the freeze).
  • await the async methods. await client.responses.create(...), await client.messages.create(...), await genai_client.aio.models.generate_content_stream(...) — forgetting the await gives you a coroutine object, not a response.

6.4 anyio, trio, uvloop and free-threaded Python — the landscape#

You don't need any of these to write async Python, but you'll meet them:

  • anyio — a higher-level async API (task groups, cancellation scopes, to_thread equivalents) that works on both asyncio and trio. It's what httpx, starlette/fastapi's test utilities and trio-style libraries standardise on. If a library's docs mention anyio, it's telling you its primitives are loop-agnostic.
  • trio — an alternative async library with stricter semantics (structured concurrency by default, no call_soon footguns). Excellent, but a different ecosystem; asyncio is what the AI SDKs and FastAPI assume.
  • uvloop — a drop-in faster event loop built on libuv, used by production services (uvicorn's --loop uvloop). As of November 2026 the latest release is 0.23.0 (October 2026), actively maintained with wheels for current Pythons including free-threaded builds. You never write uvloop code — you install it and point your server at it; the asyncio API is identical.
  • Free-threaded Python — Python 3.13 shipped an experimental build without the GIL; Python 3.14 made it officially supported (PEP 779), though the GIL-enabled build is still the default. It removes the restriction that only one thread runs Python bytecode at a time — which matters for threads doing CPU work, not for asyncio (asyncio was never GIL-bound; it juggles waits, not computation). Expect "does this library support free-threading?" to become a routine question; check sys._is_gil_enabled() and the package's classifier. Single-threaded code pays roughly a 5–10% penalty on the free-threaded build.

Part 7: ScriptedBackend — the fake async backend#

Everything in this module needs something to call that behaves like an LLM without being one. Later lessons (01B.4–01B.10) reuse this exact class — it lives in the running aitoolkit project. It is pure standard library, deterministic, and exercises every async idea from this lesson: async def, await, asyncio.sleep, an async generator for stream(), and call recording for assertions.

python
# src/aitoolkit/backend.py — save and run: python3 src/aitoolkit/backend.py
import asyncio
import random
import time
from collections.abc import AsyncIterator
from dataclasses import dataclass, field


@dataclass
class Usage:
    input_tokens: int = 0
    output_tokens: int = 0


@dataclass
class Completion:
    text: str
    model: str = "scripted-1"
    usage: Usage = field(default_factory=Usage)
    latency_s: float = 0.0
    raw: dict = field(default_factory=dict)   # what a real SDK might return


class ScriptedBackend:
    """A fake async LLM backend.

    replies: prompt-substring -> canned reply (first match wins).
    default_reply: used when nothing matches.
    latency: seconds of fake "thinking" per call (asyncio.sleep, not time.sleep!).
    stream_delay: per-token delay when streaming.
    fail_first: raise RuntimeError on the first N calls (for retry tests).
    seed: seeds the ±10% latency jitter, so timings stay reproducible.
    """

    def __init__(
        self,
        replies: dict[str, str] | None = None,
        default_reply: str = "(no scripted reply for this prompt)",
        latency: float = 0.05,
        stream_delay: float = 0.01,
        fail_first: int = 0,
        seed: int = 0,
    ) -> None:
        self.replies = replies or {}
        self.default_reply = default_reply
        self.latency = latency
        self.stream_delay = stream_delay
        self.fail_first = fail_first
        self.calls: list[dict] = []          # every call attempt, for assertions
        self._rng = random.Random(seed)      # jitter source — seed makes it reproducible

    def _reply_for(self, prompt: str) -> str:
        for needle, reply in self.replies.items():
            if needle in prompt:
                return reply
        return self.default_reply

    async def _maybe_fail(self, prompt: str) -> None:
        if self.fail_first > 0:
            self.fail_first -= 1
            raise RuntimeError(f"scripted backend failure for: {prompt[:40]!r}")

    async def _sleep(self, base: float) -> None:
        """Fake wait with ±10% jitter — real APIs don't answer on a metronome."""
        await asyncio.sleep(base * self._rng.uniform(0.9, 1.1) if base else 0.0)

    async def complete(self, prompt: str, *, model: str | None = None) -> Completion:
        """One non-streaming call — the shape of client.chat.completions.create()."""
        self.calls.append({"prompt": prompt, "mode": "complete"})  # failed attempts count too
        await self._maybe_fail(prompt)
        start = time.perf_counter()
        await self._sleep(self.latency)       # the "model thinking": pure waiting
        text = self._reply_for(prompt)
        elapsed = time.perf_counter() - start
        return Completion(
            text=text,
            model=model or "scripted-1",
            usage=Usage(input_tokens=len(prompt.split()), output_tokens=len(text.split())),
            latency_s=elapsed,
            raw={"id": "chatcmpl-scripted", "object": "chat.completion"},
        )

    async def stream(self, prompt: str, *, model: str | None = None) -> AsyncIterator[str]:
        """An async generator of text chunks — the shape of an SDK token stream.

        `async for chunk in backend.stream(prompt):` works exactly like the
        streaming APIs in lesson 03.3. Callers that stop early should
        `await gen.aclose()` (or use `async with`) so cleanup runs.
        """
        self.calls.append({"prompt": prompt, "mode": "stream"})  # failed attempts count too
        await self._maybe_fail(prompt)
        await self._sleep(self.latency)
        text = self._reply_for(prompt)
        for token in text.split(" "):
            await self._sleep(self.stream_delay)
            yield token + " "
        # a real SDK's stream ends with a usage/finish event; ours is a trailing "" marker
        yield ""


async def main() -> None:
    backend = ScriptedBackend(
        replies={"weather": "It is sunny and 21C.", "joke": "Why did the model break? It had too many parameters."},
        default_reply="I don't have a scripted answer for that.",
        latency=0.01,
        stream_delay=0.001,
    )

    c = await backend.complete("what is the weather in Paris?")
    print("complete:", c.text)
    print("  usage:", c.usage)

    print("stream:")
    parts = []
    async for chunk in backend.stream("tell me a joke"):
        parts.append(chunk)
    print("  joined:", "".join(parts).strip())

    print("calls recorded:", len(backend.calls))


if __name__ == "__main__":        # demo only: importing the module must not run it
    asyncio.run(main())
Output5 lines
complete: It is sunny and 21C.
  usage: Usage(input_tokens=6, output_tokens=5)
stream:
  joined: Why did the model break? It had too many parameters.
calls recorded: 2

Why it's shaped this way — every choice maps to a real SDK behaviour you'll meet later:

  • async def complete() mirrors await client.chat.completions.create(...) / await client.responses.create(...): one call, one result object. Later lessons swap ScriptedBackend for a real AsyncOpenAI behind the same signature.
  • stream() is an async generator — async for chunk in backend.stream(prompt) is the same consumption pattern as async for event in stream in 03.3, Part 10. It yields text chunks, not event objects, because this module's lessons need text; the event-level detail is Module 03's.
  • latency uses asyncio.sleep, not time.sleep — deliberately, so concurrent complete() calls genuinely overlap in demos (01B.4's bounded fan-out gets a real speed-up).
  • fail_first injects failures so retry/timeout lessons (01B.9) have something deterministic to retry against — the same trick as ScriptedModel's canned turns in 08A.2 (that one is for the agent loop; this one is for raw completion calls — different layers, same idea).
  • calls records every call attempt — the append runs before fail_first can raise, so len(backend.calls) counts retries too. Tests can then assert "the pipeline made exactly 3 calls" without a mock framework — 01B.8 builds on it.
  • seed + _sleep's jitter keep timings realistic (real APIs don't answer on a metronome) while staying reproducible: same seed, same jitter sequence.

This is the module's canonical fake: later lessons import aitoolkit.backend.ScriptedBackend rather than redefining it. The if __name__ == "__main__": guard on the demo matters for that reason: without it, import aitoolkit.backend would run the demo, and under uvicorn (which imports your app while its loop is already running) the module-level asyncio.run would raise the RuntimeError from 6.1. The contract they rely on is exactly what's above — await backend.complete(prompt, *, model=None) returns the Completion dataclass (read .text/.usage; it is not a bare string), backend.stream(prompt, *, model=None) is an async generator of str chunks, and backend.calls is a list of {"prompt", "mode"} dicts.


Part 8: Common bugs and production habits#

Reference

8.1 The blocking call that freezes everything#

The #1 production async bug: a synchronous call inside async def. The loop can't interrupt it, so every other task — other users' requests, heartbeats, shutdown handlers — waits. Here's a heartbeat task that counts its beats while a "sync SDK call" (time.sleep) runs:

python
# blocking_demo.py — run: python3 blocking_demo.py
import asyncio
import time


async def heartbeat(beats: list[int], stop: asyncio.Event) -> None:
    while not stop.is_set():
        await asyncio.sleep(0.01)
        beats[0] += 1


async def main() -> None:
    beats = [0]
    stop = asyncio.Event()
    hb = asyncio.create_task(heartbeat(beats, stop))

    await asyncio.sleep(0.05)                 # let the heartbeat get going
    before = beats[0]

    time.sleep(0.15)                          # BLOCKING: the loop cannot run
    during_block = beats[0] - before          # always 0 — heartbeat froze too

    await asyncio.sleep(0.05)                 # loop free again
    resumed = beats[0] - before - during_block

    stop.set()
    await hb
    print(f"beats before block : {before}")
    print(f"beats during block : {during_block}   <- the loop was frozen")
    print(f"beats after resume  : {resumed}   <- and it recovered")


asyncio.run(main())
Example output · illustrative3 lines
beats before block : 4
beats during block : 0   <- the loop was frozen
beats after resume  : 5   <- and it recovered

Zero beats during the block. The heartbeat didn't get slow — it got nothing, because time.sleep held the only thread the loop has. In a web service this is the difference between "one slow request" and "the whole server stalls". The fixes, in order of preference:

  1. Use the async version of the library (AsyncOpenAI, httpx.AsyncClient, asyncpg — the async twin exists for almost everything).
  2. Wrap the unavoidable sync call in await asyncio.to_thread(fn, ...) (3.8) — proven above in to_thread_demo.py.
  3. If it's CPU-bound, it doesn't belong on the loop at all — a ProcessPoolExecutor (01B.4).
Bug Symptom Fix
Missing await RuntimeWarning: coroutine 'x' was never awaited; function "returns" a coroutine object instantly await it, or create_task/gather it deliberately
time.sleep / sync SDK in async def Whole loop freezes; heartbeats stop; "server unresponsive" Async library, or to_thread
Dropped task reference Task was destroyed but it is pending! Keep tasks in a collection; use TaskGroup
Never-retrieved exception Task exception was never retrieved + traceback at GC await/gather/TaskGroup every task; call task.exception()
gather without return_exceptions First error kills the batch; orphans keep running — results discarded, work and cost continue Decide the policy: return_exceptions=True or TaskGroup
Unbounded create_task/gather Thousands of tasks → rate limits, socket exhaustion, memory spike Bound with Semaphore (01B.4)
Shared mutable state, no lock Intermittent wrong results; += on a shared counter loses updates asyncio.Lock, or give each task its own state and merge
Nested asyncio.run RuntimeError: ... running event loop Top-level await in notebooks; async def handlers in FastAPI; one run per program
Unclosed client/stream ResourceWarning, leaked sockets, hung shutdown async with / await client.close(); await gen.aclose() on early exit
asyncio.get_event_loop() with no running loop DeprecationWarning on 3.12–3.13 (and it quietly creates a loop); RuntimeError on 3.14+ asyncio.get_running_loop() inside coroutines; asyncio.run at top level

8.3 Decision table: which concurrency tool?#

Situation Use Why
Many concurrent I/O waits (HTTP, DB, LLM calls) asyncio + gather/TaskGroup/Semaphore Overlaps waits on one thread; cheapest concurrency there is
A blocking sync library inside async code await asyncio.to_thread(fn) Keeps the loop free without rewriting the library
CPU-bound work (parsing, local model, heavy math) ProcessPoolExecutor / separate process Threads don't parallelise pure Python (GIL); processes use real cores
Legacy thread-safe blocking I/O, no async version ThreadPoolExecutor / concurrent.futures Threads block independently; fine for modest concurrency
A single call, a script, a one-off Plain sync code Async adds complexity with zero benefit (1.4)
"Run these, take the first success" asyncio.wait(FIRST_COMPLETED) or as_completed Completion-order primitives
"These tasks are one unit — fail together" asyncio.TaskGroup Structured concurrency; cancels siblings on failure

8.4 Previews: testing and FastAPI#

Two places you'll meet async immediately after this lesson — the details are theirs, the hooks are yours:

  • Testing async code (01B.8): pytest-asyncio (or anyio's plugin) runs async def test_ functions on a loop; ScriptedBackend from Part 7 is the fake you inject — no network, deterministic, and backend.calls proves how many calls a pipeline made. The general test-double taxonomy is 01B.8; the LLM-specific version is 03.10.
  • FastAPI (01B.7): async def endpoints run on the server's event loop — which is why a blocking call inside one stalls every request, exactly the bug in 8.1. The framework's def endpoints run in a thread pool instead; lifespan hooks create and close shared async clients. 07.11, 1.3 shows a production service using all of it.

Common misconceptions#

Misconception Reality
"async def starts the work when you call it." Calling it returns a coroutine object; nothing runs until it's awaited, tasked or sent. (2.1)
"Async makes my code run faster / use more CPU." It overlaps waiting, on one thread. CPU-bound work gets nothing from it. (1.2)
"await pauses the whole program." It pauses only that coroutine; the event loop runs other ready tasks.
"time.sleep and asyncio.sleep are interchangeable." time.sleep freezes the entire loop; await asyncio.sleep yields only that task.
"asyncio.gather limits how many tasks run at once." It doesn't — every awaitable becomes a task immediately. Bound fan-out with Semaphore. (3.3)
"If one task fails, gather cancels the others." No — the first exception propagates but siblings keep running (orphans). TaskGroup is the one that cancels.
"A timeout cancels the server-side work." It cancels your wait; the request may still complete and bill. Idempotency decides retry safety. (01B.9)
"CancelledError is an Exception, so except Exception is fine." It inherits BaseException since 3.8 — and you must re-raise it anyway. (4.1)
"Breaking out of async for closes the stream." No — call await gen.aclose() or use async with, or cleanup never runs. (5.2)
"Async clients are always better than sync ones." For a single call or a sync script, the sync client is simpler and just as fast. Match client to context. (6.3)
"Free-threaded Python makes asyncio faster." It removes the GIL for threads; asyncio was never GIL-bound. Different problem. (6.4)

Key takeaways#

  • Async is for overlapping waits. An LLM call is ~99% waiting; async lets hundreds of those waits share one thread. It does nothing for CPU-bound work.
  • async def returns a coroutine object; it doesn't run. await is the pause point that yields control to the event loop, the single-threaded scheduler that runs tasks cooperatively.
  • asyncio.run(main()) once at the top level; create_task schedules independently (keep a reference!); gather fans out and preserves input order; TaskGroup gives structured concurrency that cancels siblings on failure.
  • Timeouts are mandatory on network waits: async with asyncio.timeout(...) is the modern form; wait_for wraps a single awaitable. Both raise builtin TimeoutError.
  • as_completed/wait(FIRST_COMPLETED) for completion-order work; Event/Lock/Semaphore/Queue for task coordination (patterns in 01B.4).
  • await asyncio.to_thread(fn) is the escape hatch for blocking sync code; never time.sleep or a sync SDK inside async def.
  • Cancellation is a first-class signal: task.cancel() → CancelledError at the next await; clean up in finally, always re-raise, and know that shield is a deliberate "keep paying" choice.
  • Async generators (yield in async def) + async for/async with are the shape of every streaming API — including ScriptedBackend.stream() and the real SDK streams in 03.3.
  • Mixing is the skill: asyncio.run from sync (once!), to_thread from async, top-level await in notebooks, async def endpoints in FastAPI — and the "function colouring" rule that async infects everything above it.
  • ScriptedBackend (async def complete(), async def stream(), calls log, fail_first) is the fake every later lesson in this module reuses.

Where you'll use this in the AI path#

You'll meet it in... What async does there
03.9: Async, Concurrency and Batch The refresher you just read becomes AsyncOpenAI/AsyncAnthropic/genai.aio clients, bounded fan-out over real calls, and batch-job orchestration — 2.1, 2.2, 3.1
03.3: Streaming Responses async for over token streams, async with around streams, several streams merged through an asyncio.Queue — Part 10
08A.2: The Tool Loop Parallel tool calls bounded by a Semaphore, the canonical async agent loop — 4.1, 4.2
07.11: Production RAG A FastAPI service whose async def handlers fan out to embed/rewrite/generate concurrently under caps — 1.3, 4.9
11C.3: Fallbacks and Reliability Deadlines propagated as asyncio.timeout, cancellation reaching upstream streams — 5.1, 5.2
11C.1: Deploying LLM Services Streaming endpoints and background jobs on the same event loop — 2.8, 2.9

Terms introduced in this lesson#

Term One-line definition
Coroutine function / coroutine object An async def function / the paused computation calling it returns, before anything runs
await Pause this coroutine until the awaited thing finishes; only legal inside async def
Event loop The single-threaded scheduler that runs ready tasks and parks them at each await
Cooperative scheduling Tasks yield control voluntarily at await; the loop can't preempt
Task A coroutine scheduled independently on the loop (asyncio.create_task, TaskGroup)
Future An object representing a result that doesn't exist yet; Task is one
asyncio.run Create a loop, run a coroutine to completion, close the loop — once per program
asyncio.gather Fan out awaitables concurrently; results in input order; return_exceptions collects failures
TaskGroup Structured concurrency: tasks live/die together; first failure cancels siblings
ExceptionGroup / except* One exception bundling several failures / the handler that matches types inside it
asyncio.timeout / wait_for Deadline context manager / single-awaitable timeout; both raise TimeoutError
as_completed / wait Completion-order iterator / (done, pending) sets with FIRST_COMPLETED
asyncio.Event/Lock/Semaphore/Queue Task coordination primitives: signal, mutual exclusion, bounded slots, producer-consumer
asyncio.to_thread / run_in_executor Run a blocking function on a worker thread / the lower-level executor API
contextvars Per-task context (request IDs, tracing) propagated automatically, including into threads
asyncio.Runner Reusable context manager for running async code from sync code
Async generator async def with yield; consumed by async for; aclose() cleans up early exit
async for / async with / __aiter__/__anext__/__aenter__/__aexit__ The async versions of iteration and context management
contextlib.asynccontextmanager Decorator turning an async generator into an async context manager
CancelledError Raised inside a task at its next await after task.cancel(); inherits BaseException
asyncio.shield Protect an inner awaitable from the outer cancellation
I/O-bound / CPU-bound Time dominated by waiting on external I/O / by local computation
Function colouring Once you await, everything above must be async def — async infects callers
uvloop A faster drop-in asyncio event loop (libuv-based), used via server config
Free-threaded Python The no-GIL CPython build; officially supported from 3.14, still non-default

All terms are also collected in the glossary.


Exercises#

  1. Coroutines (2.1): modify coroutine_basics.py so fetch_ticket has no await at all. What happens when you call coro.send(None)? Why does an async def without await still return a coroutine?
  2. Ordering (2.4): in interleave_demo.py, give each worker a different step count (A=2, B=4, C=3). Predict the output order before running; explain any surprise.
  3. gather order (3.3): in gather_demo.py, add a fourth label ("z-fast", 0.0) at the end of labels (it finishes before every other task). Verify the results still come back in input order, with z-fast last.
  4. TaskGroup vs gather (3.4): rewrite the TaskGroup demo with asyncio.gather (no return_exceptions). What prints instead of the except* line, and which tasks keep running?
  5. Timeout (3.5): wrap two await slow() calls inside one async with asyncio.timeout(0.08) — does the deadline cover both? Then use wait_for and explain why it can't.
  6. Blocking (8.1): change time.sleep(0.15) to await asyncio.sleep(0.15) in blocking_demo.py. Predict the "during block" count, run it, and explain why the result differs.
  7. to_thread (3.8): in to_thread_demo.py, replace asyncio.to_thread(blocking_work) with a direct blocking_work() call. Which line of output changes and why?
  8. Cancellation (4.1): remove the raise after except asyncio.CancelledError in cancel_demo.py's worker. What does t.cancelled() report, and why is swallowing cancellation dangerous?
  9. Async generator (5.2): write a summarize(stream) coroutine that consumes backend.stream("tell me a joke") from Part 7 and returns the joined text without printing each chunk. Then break out of the async for after 3 chunks and confirm aclose() is needed.
  10. ScriptedBackend concurrency: using Part 7's ScriptedBackend, asyncio.gather 10 complete() calls with latency=0.05 and time the total. Compare with the same calls made sequentially (for + await). Roughly what speed-up do you get, and why isn't it exactly 10×?
  11. Never-retrieved (4.2): in never_retrieved.py, add print(t.exception()) after the sleep. Does the warning disappear? Explain the mechanism.
  12. contextvars (3.9): change handle() in runner_ctx.py to take a name argument, call request_id.set(name) and return request_id.get(); create two tasks with different names, and print request_id.get() in main() after the gather. What does main() see, and why?
Solutions
  1. send(None) runs the whole body and raises StopIteration immediately — an async def is a coroutine function regardless of whether it awaits; await only marks pause points, it doesn't make the function async.
  2. Output (verified on Python 3.14): A1 B1 C1 A2 B2 C2 then A done — A's two steps are spent, so it exits right after its last sleep(0) resolves — then B3 C3 B4, C done, B done. B finishes last. Each await asyncio.sleep(0) requeues the task at the back of the ready queue, so steps interleave round-robin; the surprise is that done prints as soon as a worker's own loop ends, not at the end of the whole run. (Exact interleave may vary by version, but steps always alternate and B always finishes last.)
  3. results still lists them in labels order — "z-fast" (submitted last) appears last even though it finished first. gather maps results to inputs positionally.
  4. gather raises the RuntimeError from bad; "good-1"/"good-2" print their remaining steps and finish anyway (no cancellation), and you never see an except* group. Their return values are discarded.
  5. The deadline covers the whole async with block, not each await separately. With the 10-second slow() the timeout fires during the first call and the second never starts; to see the shared budget, use a coroutine that sleeps 0.05 s and await it twice: the two waits add up to 0.10 s, which passes the 0.08 s deadline during the second one, so TimeoutError is raised there. wait_for wraps exactly one awaitable, so covering both would need two calls and two separate budgets (or one wrapper coroutine that awaits both, passed to a single wait_for).
  6. "during block" becomes about 14 beats instead of 0 (a run of this change printed 14) — the heartbeat keeps beating through the whole 0.15 s window (0.15 s ÷ 0.01 s per beat, minus scheduling slack; it cannot exceed 15). await asyncio.sleep yields instead of blocking, so the loop never notices the "wait". That's the whole point of async sleep.
  7. "heartbeats during the thread call" becomes 0 (or near it): the direct call blocks the loop inside main, freezing the heartbeat task too.
  8. t.cancelled() returns False — the task finished "normally" after swallowing. Dangerous because timeouts/TaskGroup/server shutdown rely on cancellation propagating; a swallowed CancelledError can leave half-finished work looking successful.
  9. text = "".join([c async for c in backend.stream(prompt)]) consumes it; after break, await gen.aclose() (or async with contextlib.aclosing(gen)) runs the generator's cleanup.
  10. About 9–10× (the concurrent total is roughly one latency, ≈ 0.05 s; the sequential total is roughly ten). It is not exactly 10× because ScriptedBackend adds ±10% seeded jitter to each call, so the concurrent run takes as long as its slowest call (up to about 0.055 s) while the sequential run pays the average, and the loop adds a little scheduling overhead. The waits themselves genuinely overlap.
  11. Yes — calling task.exception() marks the exception as retrieved, so the "never retrieved" warning doesn't fire. The exception object itself still exists; you just told the loop you handled it.
  12. main() still prints req-42, and each task returns its own name. Every task runs in a copy of the context taken when create_task was called, so a set inside a task is invisible to main() and to its siblings, while a value set in main() before create_task is inherited by every task. Rule of thumb: set before create_task to share one value with all tasks; set inside a task (or pass an argument) when each task needs its own.

Check yourself#

  1. What does calling an async def function actually return, and when does the body run?
  2. Why is asyncio.sleep safe inside async def but time.sleep dangerous?
  3. What does await asyncio.gather(a, b, c) return, and in what order?
  4. What's the difference between gather and TaskGroup when one task fails?
  5. Which exception does asyncio.timeout raise, and what does it cancel first?
  6. When would you use as_completed instead of gather?
  7. Name the four asyncio coordination primitives and one use for each.
  8. What does await asyncio.to_thread(fn) do, and when is it the right fix?
  9. Why must CancelledError be re-raised rather than swallowed?
  10. What's the difference between async for/async with and their sync counterparts?
  11. Why does asyncio.run() fail inside a Jupyter cell, and what's the fix?
  12. What three things does ScriptedBackend provide that a real SDK also provides?

Further resources#


← 01B.2 — Environment Variables, Configuration and Secrets | Module 01B overview | 01B.4 — Concurrency Patterns for I/O-Heavy Work →

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