01B.3 Async Python: async/await and the Event Loop
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,
awaitas a pause point, the event loop as a scheduler, tasks, and cooperative scheduling - The core
asyncioAPI:asyncio.run,create_task,gather(result order andreturn_exceptions),TaskGroupwithExceptionGroup/except*,asyncio.timeoutvswait_for,as_completedandwait(FIRST_COMPLETED),asyncio.sleep - The coordination primitives (
Event,Lock,Semaphore,Queue) — enough to recognise them; the full patterns are lesson 01B.4 asyncio.to_threadfor blocking code,run_in_executorawareness,contextvars,asyncio.Runner, and asyncio debug mode- Cancellation and errors:
task.cancel(),CancelledError(and why you never swallow it),try/finallycleanup,asyncio.shield, "Task exception was never retrieved", partial results - Async iterators and context managers:
async for,async with,__aiter__/__anext__, async generators andaclose,contextlib.asynccontextmanager - Mixing sync and async code:
asyncio.runfrom sync,to_threadfrom async, why you can't nestasyncio.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.allin JavaScript orCompletableFuturecode 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:
python3 --versionSave 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:
# 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())sequential : 1.00 s
concurrent : 0.20 sFive 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.runworks, 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
asyncioyourself (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.
# 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):
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 tracebackRead that carefully — it contains the three facts everything else builds on:
- Calling an
async deffunction 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.iscoroutineconfirms it. - A coroutine only runs when driven.
coro.send(None)started it; it printed its line, hitawait asyncio.sleep(0), and paused, handing control back. The secondsendfinished it, and its return value arrived inside theStopIterationexception (done.value— that's just how generators and coroutines report a return value). - Creating a coroutine and dropping it is a bug.
fetch_ticket(99)was never awaited, so it never ran — and Python warnscoroutine 'fetch_ticket' was never awaitedwhen 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:
awaitis only legal insideasync def. Try it in a plain function and you getSyntaxError: 'await' outside async function.- Only awaitables can be awaited: coroutines, tasks, and futures.
await 42givesTypeError: 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 --> loopKey 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.
# 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())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 doneWatch 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:
>>> 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#
async def main() -> None:
...
asyncio.run(main()) # create a loop, run main() to the end, close the loopRules 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: anycreate_taskyou forgot to await is cancelled, not leaked. Convenient — but it also means fire-and-forget tasks silently die at the end ofmain()(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#
task = asyncio.create_task(coro(), name="fetch-ticket-7")- The coroutine starts at the next loop iteration, concurrently with the caller.
- The returned
Taskis aFuture:await taskgives 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 andasyncio.all_tasks().asyncio.current_task()returns your ownTask— 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.
# 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())== 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 downThree facts to memorise:
- Order is preserved.
results[i]is the answer for inputi— "slow" is first even though it finished last. Same guarantee asPromise.all. return_exceptions=Trueturns failures into values. TheValueErrorsits 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 properResulttype on it).- Without it, the first exception propagates — and the other tasks keep running.
gatherraisesValueError, 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:gatherinstalls a done-callback on every child that marks late-finishing exceptions as retrieved. (That warning is real for rawcreate_taskfire-and-forget — 4.2.) Whatgathercan't give you is cancellation: the orphans run to completion regardless, which is exactly whatTaskGroupprevents.
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.
# 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())== 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:
badraisedRuntimeErrorat step 3.- The TaskGroup cancelled its siblings —
good-1andgood-2gotCancelledErrorat their nextawait(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 (aBaseExceptionGroupwhen a failure is aBaseExceptionrather than anException;except*matches both). except* RuntimeError as groupis the matching handler (except-star): it catches only theRuntimeErrors inside the group;group.exceptionsis 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:
# 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())== 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 ==
Trueasync with asyncio.timeout(seconds)(3.11+) wraps any block of code — several awaits, a whole pipeline stage — and raises builtinTimeoutErrorwhen the deadline passes. It cancels the code inside, then converts the resultingCancelledErrorintoTimeoutError. 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 ofasyncio.timeout, so behaviour matches; the context-manager form is more flexible (it can cover multiple awaits and non-task code).asyncio.TimeoutErrorisTimeoutError(same object since 3.11) —except TimeoutErrorcatches 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.
# 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())== 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 isALL_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 whyTaskGroup/gatherare 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.
# 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()) 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:
# 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())thread returned: sync result
heartbeats during the thread call: 8 <- loop never frozeThe 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):
# 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()['handling request req-42', 'handling request req-42']
NoneTwo things in that demo worth noting:
contextvars.ContextVaris 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_threadcopies 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 freshmain()-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:
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:
import asyncio
async def main() -> None:
print("loop debug mode:", asyncio.get_running_loop().get_debug())
asyncio.run(main())loop debug mode: TrueUse 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.
# 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())== 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: NoneThe rules:
CancelledErrorinherits fromBaseException, notException(since 3.8) — a bareexcept Exceptionwon't catch it, which is deliberate: cancellation must propagate.- Never swallow it. If you catch
CancelledError, clean up andraiseagain (orraisea different exception only if you truly mean to convert it). Swallowing cancellation breaks timeouts,TaskGroupshutdown and server disconnect handling. try/finallyis your cleanup guarantee. Thefinallyran even though the task was cancelled mid-await— close files, release locks, write "cancelled" status there.await ton a cancelled task raisesCancelledErrorin the awaiting code too; checkt.cancelled()to distinguish "was cancelled" from "failed".asyncio.shield(inner)protectsinnerfrom the outer cancellation: cancelling the shielded await stops waiting but letsinnerfinish. 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.
4.2 The exception gallery: real messages#
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:
# 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):
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 retrievedThe 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:
# 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 warningTask 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.
# 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())== 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: endRules of the road:
- Consume with
async for chunk in gen:or manually withawait gen.__anext__()(StopAsyncIterationends it, likeStopIterationfor sync generators). await gen.aclose()when you stop early — it throwsGeneratorExitinside at the currentyield, running the generator'sfinallyblocks (closing the upstream HTTP stream, in real SDKs). Breaking out ofasync fordoes not close it automatically; useasync withor callaclose().@contextlib.asynccontextmanagerturns an async generator into an async context manager:yieldonce insidetry/finallyand you getasync withfor 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 |
# 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):
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 loopRead 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
awaitin 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 defandawaitinside it (01B.7); never callasyncio.runthere. - Nested
asyncio.runin sync code — ifmain()itself callsasyncio.run, you get this error. Fix:awaitthe inner coroutine instead, or restructure so only the outermost call usesrun. - 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()(orasync 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 defservice (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 insideasync def— it blocks the loop (Part 8 shows the freeze). awaitthe async methods.await client.responses.create(...),await client.messages.create(...),await genai_client.aio.models.generate_content_stream(...)— forgetting theawaitgives 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_threadequivalents) that works on bothasyncioandtrio. It's whathttpx,starlette/fastapi's test utilities andtrio-style libraries standardise on. If a library's docs mentionanyio, it's telling you its primitives are loop-agnostic.trio— an alternative async library with stricter semantics (structured concurrency by default, nocall_soonfootguns). Excellent, but a different ecosystem;asynciois 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 writeuvloopcode — 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.
# 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())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: 2Why it's shaped this way — every choice maps to a real SDK behaviour you'll meet later:
async def complete()mirrorsawait client.chat.completions.create(...)/await client.responses.create(...): one call, one result object. Later lessons swapScriptedBackendfor a realAsyncOpenAIbehind the same signature.stream()is an async generator —async for chunk in backend.stream(prompt)is the same consumption pattern asasync for event in streamin 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.latencyusesasyncio.sleep, nottime.sleep— deliberately, so concurrentcomplete()calls genuinely overlap in demos (01B.4's bounded fan-out gets a real speed-up).fail_firstinjects failures so retry/timeout lessons (01B.9) have something deterministic to retry against — the same trick asScriptedModel's canned turns in 08A.2 (that one is for the agent loop; this one is for raw completion calls — different layers, same idea).callsrecords every call attempt — the append runs beforefail_firstcan raise, solen(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:
# 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())beats before block : 4
beats during block : 0 <- the loop was frozen
beats after resume : 5 <- and it recoveredZero 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:
- Use the async version of the library (
AsyncOpenAI,httpx.AsyncClient,asyncpg— the async twin exists for almost everything). - Wrap the unavoidable sync call in
await asyncio.to_thread(fn, ...)(3.8) — proven above in to_thread_demo.py. - If it's CPU-bound, it doesn't belong on the loop at all — a
ProcessPoolExecutor(01B.4).
8.2 The gallery#
| 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) runsasync def test_functions on a loop;ScriptedBackendfrom Part 7 is the fake you inject — no network, deterministic, andbackend.callsproves 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 defendpoints 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'sdefendpoints 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 defreturns a coroutine object; it doesn't run.awaitis 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_taskschedules independently (keep a reference!);gatherfans out and preserves input order;TaskGroupgives structured concurrency that cancels siblings on failure.- Timeouts are mandatory on network waits:
async with asyncio.timeout(...)is the modern form;wait_forwraps a single awaitable. Both raise builtinTimeoutError. as_completed/wait(FIRST_COMPLETED)for completion-order work;Event/Lock/Semaphore/Queuefor task coordination (patterns in 01B.4).await asyncio.to_thread(fn)is the escape hatch for blocking sync code; nevertime.sleepor a sync SDK insideasync def.- Cancellation is a first-class signal:
task.cancel()→CancelledErrorat the nextawait; clean up infinally, always re-raise, and know thatshieldis a deliberate "keep paying" choice. - Async generators (
yieldinasync def) +async for/async withare the shape of every streaming API — includingScriptedBackend.stream()and the real SDK streams in 03.3. - Mixing is the skill:
asyncio.runfrom sync (once!),to_threadfrom async, top-levelawaitin notebooks,async defendpoints in FastAPI — and the "function colouring" rule that async infects everything above it. ScriptedBackend(async def complete(),async def stream(),callslog,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#
- Coroutines (2.1): modify
coroutine_basics.pysofetch_tickethas noawaitat all. What happens when you callcoro.send(None)? Why does anasync defwithoutawaitstill return a coroutine? - 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. - gather order (3.3): in
gather_demo.py, add a fourth label("z-fast", 0.0)at the end oflabels(it finishes before every other task). Verify the results still come back in input order, withz-fastlast. - TaskGroup vs gather (3.4): rewrite the TaskGroup demo with
asyncio.gather(noreturn_exceptions). What prints instead of theexcept*line, and which tasks keep running? - Timeout (3.5): wrap two
await slow()calls inside oneasync with asyncio.timeout(0.08)— does the deadline cover both? Then usewait_forand explain why it can't. - Blocking (8.1): change
time.sleep(0.15)toawait asyncio.sleep(0.15)inblocking_demo.py. Predict the "during block" count, run it, and explain why the result differs. - to_thread (3.8): in
to_thread_demo.py, replaceasyncio.to_thread(blocking_work)with a directblocking_work()call. Which line of output changes and why? - Cancellation (4.1): remove the
raiseafterexcept asyncio.CancelledErrorincancel_demo.py'sworker. What doest.cancelled()report, and why is swallowing cancellation dangerous? - Async generator (5.2): write a
summarize(stream)coroutine that consumesbackend.stream("tell me a joke")from Part 7 and returns the joined text without printing each chunk. Then break out of theasync forafter 3 chunks and confirmaclose()is needed. - ScriptedBackend concurrency: using Part 7's
ScriptedBackend,asyncio.gather10complete()calls withlatency=0.05and 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×? - Never-retrieved (4.2): in
never_retrieved.py, addprint(t.exception())after the sleep. Does the warning disappear? Explain the mechanism. - contextvars (3.9): change
handle()inrunner_ctx.pyto take anameargument, callrequest_id.set(name)and returnrequest_id.get(); create two tasks with different names, and printrequest_id.get()inmain()after thegather. What doesmain()see, and why?
Solutions
send(None)runs the whole body and raisesStopIterationimmediately — anasync defis a coroutine function regardless of whether it awaits;awaitonly marks pause points, it doesn't make the function async.- Output (verified on Python 3.14):
A1 B1 C1 A2 B2 C2thenA done— A's two steps are spent, so it exits right after its lastsleep(0)resolves — thenB3 C3 B4,C done,B done. B finishes last. Eachawait asyncio.sleep(0)requeues the task at the back of the ready queue, so steps interleave round-robin; the surprise is thatdoneprints 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.) resultsstill lists them inlabelsorder — "z-fast" (submitted last) appears last even though it finished first.gathermaps results to inputs positionally.gatherraises theRuntimeErrorfrombad; "good-1"/"good-2" print their remaining steps and finish anyway (no cancellation), and you never see anexcept*group. Their return values are discarded.- The deadline covers the whole
async withblock, not eachawaitseparately. With the 10-secondslow()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, soTimeoutErroris raised there.wait_forwraps exactly one awaitable, so covering both would need two calls and two separate budgets (or one wrapper coroutine that awaits both, passed to a singlewait_for). - "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.sleepyields instead of blocking, so the loop never notices the "wait". That's the whole point of async sleep. - "heartbeats during the thread call" becomes 0 (or near it): the direct call blocks the loop inside
main, freezing the heartbeat task too. t.cancelled()returnsFalse— the task finished "normally" after swallowing. Dangerous because timeouts/TaskGroup/server shutdown rely on cancellation propagating; a swallowedCancelledErrorcan leave half-finished work looking successful.text = "".join([c async for c in backend.stream(prompt)])consumes it; afterbreak,await gen.aclose()(orasync with contextlib.aclosing(gen)) runs the generator's cleanup.- 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
ScriptedBackendadds ±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. - 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. main()still printsreq-42, and each task returns its own name. Every task runs in a copy of the context taken whencreate_taskwas called, so asetinside a task is invisible tomain()and to its siblings, while a value set inmain()beforecreate_taskis inherited by every task. Rule of thumb: set beforecreate_taskto share one value with all tasks; set inside a task (or pass an argument) when each task needs its own.
Check yourself#
- What does calling an
async deffunction actually return, and when does the body run?A coroutine object — a paused computation. The body runs only when the coroutine is awaited, scheduled as a task, or driven manually (send). - Why is
asyncio.sleepsafe insideasync defbuttime.sleepdangerous?asyncio.sleepsuspends only that coroutine and lets the loop run others;time.sleepblocks the whole thread, freezing every task on the loop. - What does
await asyncio.gather(a, b, c)return, and in what order?A list of the three results, in input order — not completion order. - What's the difference between
gatherandTaskGroupwhen one task fails?gatherpropagates the first exception but lets siblings finish;TaskGroupcancels siblings and raises anExceptionGroup(handle withexcept*). - Which exception does
asyncio.timeoutraise, and what does it cancel first?BuiltinTimeoutError. It cancels the code inside the block first (raisingCancelledErrorthere), then converts it toTimeoutError. - When would you use
as_completedinstead ofgather?When you want results as they complete (progress, first-success-wins) rather than all at once in input order. - Name the four
asynciocoordination primitives and one use for each.Event(signal readiness),Lock(mutual exclusion),Semaphore(bounded concurrency),Queue(producer/consumer). - What does
await asyncio.to_thread(fn)do, and when is it the right fix?It runs the blocking functionfnon a worker thread so the event loop stays responsive — the fix for sync-only libraries insideasync def. - Why must
CancelledErrorbe re-raised rather than swallowed?Because cancellation is how timeouts,TaskGroupshutdown and server disconnects propagate; swallowing it can leave half-finished work looking successful. - What's the difference between
async for/async withand their sync counterparts?async for/async withuse__aiter__/__anext__and__aenter__/__aexit__, and each step canawait— needed because getting the next item or entering/exiting may itself wait on I/O. - Why does
asyncio.run()fail inside a Jupyter cell, and what's the fix?The notebook kernel already runs an event loop, soasyncio.runrefuses to nest. Fix: top-levelawaitin the cell (IPython/Jupyter support it). - What three things does
ScriptedBackendprovide that a real SDK also provides?async def complete()(one call → result),stream()(an async generator of chunks), andcalls(a record of invocations for assertions) — plusfail_firstfor failure injection.
Further resources#
- Python docs,
asyncio— Coroutines and tasks andasyncio— Sync primitives: the authoritative API reference for everything in Parts 3–5, with "New in version" notes. - Python docs, Developing with asyncio (including its debug mode) and asyncio command-line introspection tools: common mistakes,
PYTHONASYNCIODEBUGand inspecting a running process. - PEP 492 — Coroutines with
asyncandawaitsyntax and PEP 654 — Exception Groups: the design documents behind the syntax andexcept*. - Python docs, What's new in Python 3.11 (
TaskGroup,asyncio.timeout,ExceptionGroup,Runner) and 3.12 (wait_foron top oftimeout). - uvloop on PyPI and MagicStack/uvloop on GitHub: the faster loop, current release and wheels.
- PEP 779 — Criteria for supported status for free-threaded Python and Python free-threading guide: the no-GIL build's status and how to detect it.
- anyio documentation and trio documentation: the loop-agnostic and alternative async ecosystems.
- Real Python — AsyncIO: The Complete Guide: a well-regarded long-form tutorial that complements this lesson's reference depth.
← 01B.2 — Environment Variables, Configuration and Secrets | Module 01B overview | 01B.4 — Concurrency Patterns for I/O-Heavy Work →