Skip to content

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.

18 min read0/5 questions

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.
Three tasks that each wait on the network
t1t2t3t4t5t6
Task Arunwaitwait
Task B
Task C

Sequential: A runs, then sits idle waiting for the network. Nothing else happens meanwhile.

1/4
Quick check
An asyncio program runs on one thread. How can it be faster than a plain loop for 100 HTTP requests?
Need a nudge? A hint rules out a wrong answer.

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.

Python
async def add(a, b): print(" running add") return a + b coro = add(2, 3) # nothing runs yetprint(type(coro).__name__) # An event loop drives coroutines by calling send(). We can do it by hand:try: coro.send(None)except StopIteration as done: print("result:", done.value)
Output
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.

One event loop, two tasks fetching data
event looptask Atask Bnetworkrunsend requestawait (pause)runA's replyresume

The loop starts task A.

1/6

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.

Python
from collections import deque def download(name, chunks): for i in range(1, chunks + 1): print(f"{name}: got chunk {i}/{chunks}") yield # "waiting for the network", let others run print(f"{name}: done") def run(tasks): ready = deque(tasks) while ready: task = ready.popleft() try: next(task) # run until it pauses ready.append(task) except StopIteration: pass # finished, drop it run([download("A", 2), download("B", 3), download("C", 1)])
Output
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.

Predict the outputPython

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()
Need a nudge? Hints walk you through it.

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.

fetch_all.py
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.

Quick check
Ten tasks each run time.sleep(1) inside async def, gathered together. Roughly how long does it take?
Need a nudge? A hint rules out a wrong answer.

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 it in order5 steps

Put the life of an asyncio program in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.)

asyncioThreads (threading, ThreadPoolExecutor)Processes (multiprocessing, ProcessPoolExecutor)
Best forLots of I/O waitsSome I/O, or blocking librariesCPU-heavy work
Runs onOne threadMany threads, one processMany processes, many cores
Real parallelism for Python codeNoNo (GIL), in the default buildYes
Cost per taskTiny (thousands are fine)Medium (MBs per thread)High (a whole interpreter)
SwitchingAt each await, explicitAnywhere, by the OSSeparate memory, no sharing
Typical useFastAPI, httpx, websocketsCalling requests concurrentlyImage processing, ML preprocessing
Match the pairs0/4 matched

Pick the best tool for each job.

Choose an item, then its match on the other side.
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.

ChallengeMedium

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.

Python
def total_time(durations: list[int], limit: int) -> int: # Track when each running "slot" becomes free. pass
Key terms
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 def function; 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.