Async Python
Most programs spend a lot of time waiting: for a web API to respond, a database query to finish, a file to download. Asynchronous code lets one program do other useful work during those waits, so 100 slow network requests take about as long as the slowest one, instead of the sum of all of them.
The problem: waiting in line
Three one-second waits, done one after another: 3 seconds. The CPU did nothing while waiting.
The async version
All three start immediately and wait at the same time: about 1 second in total.
The vocabulary
| Term | Meaning |
|---|---|
async def |
Defines a coroutine function. Calling it returns a coroutine object, without running it yet. |
await x |
Pause this coroutine until x is finished; the event loop runs other coroutines meanwhile. |
| event loop | The scheduler that switches between coroutines whenever one is waiting. |
asyncio.run(main()) |
Starts the event loop and runs main to completion: the entry point of an async program. |
asyncio.gather(...) |
Runs several awaitables concurrently and collects all their results. |
| task | A coroutine scheduled to run in the background: asyncio.create_task(...). |
await only works inside async def. Forgetting await is the classic mistake: you get a coroutine object instead of a result:
Tasks: start now, wait later
Results in completion order, and timeouts
Limiting concurrency with a semaphore
Firing 10,000 requests at once will get you rate-limited or banned. A semaphore allows only N at a time:
Producer and consumer with a queue
(:= is the "walrus operator": it assigns and tests in one expression.)
Real async libraries
Async only helps if the slow parts are async too. Use libraries built for it:
import asyncio
import httpx # pip install httpx
async def main():
async with httpx.AsyncClient() as client:
urls = [f"https://api.github.com/users/{u}" for u in ["torvalds", "gvanrossum"]]
responses = await asyncio.gather(*(client.get(u) for u in urls))
for r in responses:
print(r.json()["name"])
asyncio.run(main())| Need | Async library |
|---|---|
| HTTP requests | httpx, aiohttp |
| Web APIs | FastAPI, Starlette |
| PostgreSQL | asyncpg, SQLAlchemy (async mode) |
| Redis | redis.asyncio |
Async vs threads vs processes
| Tool | Best for |
|---|---|
| asyncio | Lots of waiting on the network (thousands of connections) |
threads (concurrent.futures.ThreadPoolExecutor) |
Waiting on blocking libraries that aren't async |
processes (multiprocessing, ProcessPoolExecutor) |
Heavy CPU work (number crunching) across several cores |
Async does not make CPU-heavy code faster: while a coroutine computes, nothing else runs. And never call a blocking function like time.sleep() or requests.get() inside a coroutine, because it freezes the whole event loop.
Practice
- Write
async def countdown(name, n)that printsname: nevery 0.1 s down to 1, and run two countdowns concurrently withgather. - Simulate fetching 5 URLs with random delays (
random.uniform(0.1, 0.5)), print them as they finish withas_completed, and the total time. - Add a timeout of 0.3 s to each fetch and count how many timed out.
1.What does calling an async def function return?
2.Three async calls each wait 1 second. Run with asyncio.gather, about how long does it take?
3.Which is the best fit for speeding up heavy CPU-bound number crunching?