Lesson 29 of 52Pythonic Python
Async and Await
Understand the event loop, write asyncio code with async/await and gather, and know when async helps and when it does not.
A web server spends most of its time waiting: for the database, for another API, for the network. If each request blocked a whole thread while it waited, a server could handle only a few hundred users. async and await let one Python process juggle thousands of waiting tasks at once. It is how FastAPI gets its speed, and "explain the event loop" is a standard backend interview question.
Concurrency is not parallelism
Two words that sound alike and mean different things:
- Concurrency is dealing with many things at once: making progress on several tasks by switching between them while each one waits. One cook, three pans.
- Parallelism is doing many things at the same instant, on several CPU cores. Three cooks.
Sequential: A runs, then sits idle waiting for the network. Nothing else happens meanwhile.
Coroutines: async def and await
A function defined with async def is a coroutine function. Calling it does not run it. It returns a coroutine object, a paused computation, much like calling a generator function returns a generator.
await something means: "pause this coroutine until something finishes, and let the event loop run other work meanwhile". You can only use await inside an async def.
Press Run (⌘ Enter) to see what happens.You will never call send yourself in real code; the event loop does it. But this shows what is underneath: coroutines are resumable functions, built on the same machinery as generators.
The event loop
The event loop is a scheduler. It keeps a queue of coroutines that are ready to run. It runs one until it hits an await on something that is not ready (a network reply, a timer), parks it, and runs the next ready one. When the reply arrives, the parked coroutine goes back in the ready queue.
The loop starts task A.
Here is a tiny event loop made from generators, to see the scheduling with your own eyes. Each task yields whenever it would wait, which is exactly the role await plays in asyncio.
Press Run (⌘ Enter) to see what happens.The output interleaves A, B and C even though only one runs at any moment. That is concurrency.
What does this print?
from collections import deque
def task(name, steps):
for _ in range(steps):
print(name, end="")
yield
ready = deque([task("x", 3), task("y", 1)])
while ready:
t = ready.popleft()
try:
next(t)
ready.append(t)
except StopIteration:
pass
print()Real asyncio: run, gather, sleep
Real code uses the asyncio module. asyncio.run(main()) creates the loop, runs main until it finishes, and closes the loop. You call it once, at the entry point of your program. asyncio.gather runs several coroutines concurrently and returns all their results, in order.
import asyncio
import time
async def fetch(name: str, seconds: float) -> str:
await asyncio.sleep(seconds) # stands in for a network call
return f"{name} ({seconds}s)"
async def main() -> None:
start = time.perf_counter()
results = await asyncio.gather(
fetch("users", 1.0),
fetch("orders", 1.5),
fetch("prices", 0.5),
)
print(results)
print(f"took {time.perf_counter() - start:.1f}s") # about 1.5s, not 3.0s
asyncio.run(main())Total time is the longest wait (1.5 s), not the sum (3 s). Awaiting them one after another (await fetch(...) three times) would take the full 3 seconds, because each await waits before the next call even starts.
time.sleep(1) inside async def, gathered together. Roughly how long does it take?Tasks and timeouts
asyncio.create_task(coro) schedules a coroutine to start running in the background right away, and gives you a Task you can await later. Python 3.11's asyncio.TaskGroup is the safer modern way: it waits for every task, and if one fails, it cancels the others and raises an ExceptionGroup.
async def main() -> None:
async with asyncio.TaskGroup() as tg:
users = tg.create_task(fetch("users", 1.0))
orders = tg.create_task(fetch("orders", 1.5))
# both are done here
print(users.result(), orders.result())
try:
async with asyncio.timeout(0.2): # Python 3.11+
await fetch("slow-api", 5.0)
except TimeoutError:
print("gave up after 0.2s")Always put a timeout on network calls. Without one, a single hung server can pile up waiting tasks until your service falls over.
Put the life of an asyncio program in order.
- Tap the steps below in the right order.
When async helps, and when it does not
Async shines for I/O-bound work: anything that mostly waits on the network, disk or database. Web servers, scrapers, chat apps and API gateways fit perfectly.
It does nothing for CPU-bound work: resizing images, crunching numbers, parsing huge files. There is no waiting to overlap; the CPU is busy the whole time. In CPython, the GIL (global interpreter lock) also lets only one thread run Python bytecode at a time, so threads do not speed up pure-Python number crunching either. For that, use separate processes. (Python 3.13+ offers an experimental free-threaded build without the GIL, but the default build still has it.)
asyncio | Threads (threading, ThreadPoolExecutor) | Processes (multiprocessing, ProcessPoolExecutor) | |
|---|---|---|---|
| Best for | Lots of I/O waits | Some I/O, or blocking libraries | CPU-heavy work |
| Runs on | One thread | Many threads, one process | Many processes, many cores |
| Real parallelism for Python code | No | No (GIL), in the default build | Yes |
| Cost per task | Tiny (thousands are fine) | Medium (MBs per thread) | High (a whole interpreter) |
| Switching | At each await, explicit | Anywhere, by the OS | Separate memory, no sharing |
| Typical use | FastAPI, httpx, websockets | Calling requests concurrently | Image processing, ML preprocessing |
Pick the best tool for each job.
Running asyncio in the browser on this site
The runnable code windows on RazorCode use Pyodide, Python compiled to WebAssembly, which shares the browser's own event loop. Real asyncio.run(...) and asyncio.sleep timing do not behave the same way inside our synchronous runner, so the asyncio examples above are shown as static code. Copy them into a .py file and run them locally with python fetch_all.py (or uv run fetch_all.py) to see the timings.
How long with a concurrency limit?
In real async code you often cap how many requests run at once (with asyncio.Semaphore), so you do not overload a server. Let's model the timing without an event loop.
You get a list of task durations (in seconds) and a limit: at most limit tasks run at the same time. Tasks start in list order: at time 0 the first limit tasks start, and whenever one finishes, the next waiting task starts immediately. Return the time at which all tasks have finished.
total_time([3, 1, 2], 1) # 6 (one at a time: 3 + 1 + 2)
total_time([3, 1, 2], 3) # 3 (all together: the longest)
total_time([3, 1, 2], 2) # 3 (3 and 1 start; at t=1 the 2 starts, ends at t=3)limit is at least 1. An empty list takes 0 seconds.
- concurrency
- Making progress on many tasks by switching between them while they wait; one thread is enough.
- parallelism
- Running several computations at the same instant on multiple CPU cores.
- coroutine
- The paused computation returned by calling an
async deffunction; the event loop runs it. - event loop
- The scheduler that runs ready coroutines and parks them while they await I/O.
- asyncio.gather
- Runs several awaitables concurrently and returns their results in order.
- GIL
- CPython's global interpreter lock: only one thread runs Python bytecode at a time in the default build.