asyncio is Python’s way of doing many things that wait — network requests, database calls, timers — at the same time on a single thread. While one task waits for a response, others run. It does not make code that computes faster; it makes code that waits stop wasting time. This article explains the model, shows a real example that fetches ten pages in the time of one, and covers the handful of mistakes that make async code slower than the synchronous version.
The problem it solves#
import requests, time
urls = ["https://example.com/page/" + str(i) for i in range(10)]
start = time.perf_counter()
for url in urls:
requests.get(url) # each one waits for the network, one after another
print(time.perf_counter() - start) # roughly ten times one request
Nearly all of that time is spent waiting for servers. The CPU is idle. Threads are one answer; asyncio is the other, and for large numbers of connections it is the lighter one.
The same thing with asyncio#
import asyncio, httpx, time
async def fetch(client, url):
response = await client.get(url) # while this waits, other fetches run
return response.status_code
async def main():
urls = ["https://example.com/page/" + str(i) for i in range(10)]
async with httpx.AsyncClient() as client:
results = await asyncio.gather(*(fetch(client, u) for u in urls))
print(results)
start = time.perf_counter()
asyncio.run(main())
print(time.perf_counter() - start) # roughly the time of the slowest single request
Ten requests, total time about one request. That is the whole promise, and the three keywords that deliver it are explained next.
The three pieces#
A coroutine is a function defined with async def. Calling it does not run it; it returns a coroutine object that the event loop can run.
await pauses the coroutine until the thing it is waiting on completes, and hands control back to the event loop so something else can run. You can only await inside an async def, and you can only await things that are awaitable: other coroutines, tasks, and library calls designed for asyncio.
The event loop is the scheduler. asyncio.run(main()) starts one, runs main until it finishes, and shuts it down. Inside, every await is a point where the loop may switch to another task.
Running things concurrently#
Awaiting coroutines one after another runs them one after another. Concurrency comes from starting several before waiting:
# Sequential: no faster than synchronous code
a = await fetch(client, url1)
b = await fetch(client, url2)
# Concurrent: both in flight at once
a, b = await asyncio.gather(fetch(client, url1), fetch(client, url2))
# Concurrent, with structured cancellation on error (Python 3.11+)
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(fetch(client, url1))
t2 = tg.create_task(fetch(client, url2))
print(t1.result(), t2.result())
gather returns results in order. TaskGroup is newer and stricter: if one task fails, the others are cancelled and the exception propagates, which is usually what you want.
Limiting concurrency#
A thousand simultaneous requests will get you rate-limited or banned. A semaphore caps how many run at once:
limit = asyncio.Semaphore(10)
async def fetch(client, url):
async with limit: # at most 10 inside this block at a time
response = await client.get(url)
return response.status_code
Async libraries#
Only calls that are built for asyncio give control back while waiting. A synchronous library called inside a coroutine blocks the whole loop: nothing else runs until it returns, and the async version becomes no faster than the sync one. Use the async counterparts:
| Synchronous | Async equivalent |
|---|---|
| requests | httpx (async client) or aiohttp |
| time.sleep | asyncio.sleep |
| psycopg2, sqlite3 | asyncpg, aiosqlite, or SQLAlchemy’s async engine |
| open() and file reads | aiofiles, or run in a thread |
| subprocess.run | asyncio.create_subprocess_exec |
For a synchronous call you cannot replace, hand it to a thread so the loop stays free:
result = await asyncio.to_thread(slow_sync_function, arg)
The mistakes#
async def bad():
time.sleep(1) # blocks the loop for a second: use asyncio.sleep
requests.get(url) # blocks: use httpx
fetch(client, url) # forgot await: creates a coroutine and never runs it
for u in urls:
await fetch(client, u) # sequential: use gather or TaskGroup
The forgotten await produces a warning, “coroutine was never awaited”, and no result. The blocking calls produce no warning at all; the code simply is not concurrent. If an async program is no faster than the sync version, one of these is why.
When not to use it#
- CPU-bound work. Computing does not wait, so there is nothing to overlap. Use multiprocessing, or a library that releases the GIL.
- A handful of requests. Three sequential calls do not justify restructuring a program.
- Code that must call many sync libraries. If most of the work is in threads anyway, use threads.
asyncio is for I/O at scale: web servers, scrapers, API clients, anything holding many open connections.
Questions people ask#
Is asyncio faster than threads?
For many connections, it uses far less memory and avoids locking. For a few, threads are simpler and just as fast. Both are I/O concurrency; neither speeds up computation.
Does async use multiple cores?
No. One thread, one core. Multiprocessing is for parallel computation.
Do I need asyncio for FastAPI?
Not to start; plain def endpoints run in a thread pool. Use async def when the endpoint awaits an async database or HTTP call.
What is a Task?
A coroutine that the loop has been asked to run, wrapped so you can cancel it, check whether it is done, and get its result. create_task and TaskGroup make them; gather does it for you.
Where to go next#
- Concurrency and multithreading — the concepts underneath.
- FastAPI vs Flask — where async web code lives.
- Generators and iterators — the mechanism coroutines are built on.