Async Python, explained for backend developers
I'm building the WebSocket layer for CodifyLive with
FastAPI, which means most of my code right now is async def. It's also the
part of Python I see junior backend engineers get wrong most often. Usually
not because the syntax is hard, but because the mental model is off.
This post is that mental model, the two mistakes that come from getting it wrong, and how it all maps to FastAPI.
Async is not faster, and it is not parallel
Async doesn't make your code faster, and it doesn't run things in parallel. asyncio is one thread. What it does is stop that thread from sitting idle while it waits on I/O.
Think of a waiter with 10 tables. A bad waiter takes an order, walks it to the kitchen, and stands there until the food is ready. Then they serve it and go to the next table. A good waiter takes the order, hands it to the kitchen, and goes to take the next table's order while the first meal cooks. Same single waiter, same kitchen speed, but far more tables served per hour.
The kitchen is your database, the HTTP API you're calling, Redis, the disk. The waiter is your one thread.
So async helps when your code spends its time waiting:
- Database queries
- HTTP calls to other services
- Redis reads and writes
- File and network I/O
It does nothing for work that keeps the CPU busy: hashing passwords, parsing a 50MB JSON payload, resizing images. There's no waiting to fill. The waiter is cooking the meal themselves, and nobody else gets served until they're done.
The vocabulary
Coroutine function. Anything defined with async def.
Coroutine object. What you get when you call a coroutine function. Calling it doesn't run it. It hands you an object that describes work to be done later.
import asyncio
async def fetch_user(user_id: int) -> dict:
await asyncio.sleep(0.1) # stand-in for a DB query
return {"id": user_id}
fetch_user(1) # nothing runs
# RuntimeWarning: coroutine 'fetch_user' was never awaited
print(asyncio.run(fetch_user(1))) # {'id': 1}If you've seen coroutine ... was never awaited in your logs, this is why.
Somewhere you called an async function and forgot the await, so the work
silently never happened.
await. Runs a coroutine and pauses the current one until the result is
ready. More importantly, it's the point where your code says "I'm waiting, go
do something else". That's the only place a switch can happen.
The event loop. The scheduler. It keeps track of every paused coroutine and
what each one is waiting on. Under the hood it asks the OS (epoll on Linux,
kqueue on macOS) "which of these sockets are ready?", and resumes the
coroutines whose data has arrived. asyncio.run() starts a loop, runs your
coroutine, and closes it.
Task. A coroutine wrapped and handed to the event loop so it runs in the
background. await on its own runs one thing. asyncio.create_task() starts
it and lets you keep going.
import asyncio
async def fetch_user(user_id: int) -> dict:
await asyncio.sleep(1)
return {"id": user_id}
async def main():
task = asyncio.create_task(fetch_user(1)) # scheduled, starts at our next await
print("doing other work while the user loads")
user = await task
print(user)
asyncio.run(main())Mistake 1: awaiting one by one and expecting concurrency
Writing async def everywhere doesn't make anything concurrent. This code is
fully async and fully sequential:
import asyncio
import time
async def get(name: str, delay: float) -> str:
await asyncio.sleep(delay) # pretend this is an HTTP call
return name
async def main():
start = time.perf_counter()
users = await get("users", 1)
orders = await get("orders", 2)
print(users, orders, f"{time.perf_counter() - start:.1f}s")
asyncio.run(main()) # users orders 3.0sEach await waits for its result before the next line starts. 1 second plus
2 seconds is 3 seconds. The loop was free to do other work during those waits,
but you didn't give it any.
To run them at the same time, hand both to the loop up front:
async def main():
start = time.perf_counter()
users, orders = await asyncio.gather(
get("users", 1),
get("orders", 2),
)
print(users, orders, f"{time.perf_counter() - start:.1f}s")
asyncio.run(main()) # users orders 2.0sTwo seconds, the length of the slowest call. That's the whole win.
On Python 3.11+ I reach for asyncio.TaskGroup instead. If one task raises,
it cancels the others and re-raises, so you don't end up with orphaned tasks
running after a failure:
async def main():
async with asyncio.TaskGroup() as tg:
users = tg.create_task(get("users", 1))
orders = tg.create_task(get("orders", 2))
# the block exits only once both tasks are done
print(users.result(), orders.result())
asyncio.run(main()) # users ordersMistake 2: blocking the loop
This one is worse because nothing errors. Everything just gets slow.
There's one thread. If a coroutine runs code that blocks without await, the
whole loop freezes. Every other request, every other WebSocket, all of it waits.
The usual offenders inside an async def:
time.sleep(1) # blocks the thread
requests.get("https://...") # sync HTTP client, blocks
User.objects.get(id=1) # sync Django ORM (Django raises SynchronousOnlyOperation here)The async versions:
import asyncio
import hashlib
import httpx
def legacy_sync_call(data: bytes) -> str:
# some sync library you can't replace
return hashlib.sha256(data).hexdigest()
async def main():
await asyncio.sleep(1)
async with httpx.AsyncClient() as client:
response = await client.get("https://example.com")
print(response.status_code)
# run sync code in a worker thread so the loop stays free
digest = await asyncio.to_thread(legacy_sync_call, b"hello")
print(digest)
asyncio.run(main())asyncio.to_thread is the escape hatch for sync libraries. It runs the
function in a thread and gives you something to await. It works well for
blocking I/O. It won't help much with heavy CPU work, because of the GIL.
How this maps to FastAPI
FastAPI looks at how you defined the route and runs it differently:
async defroutes run directly on the event loop. Only use async libraries inside them:httpx,asyncpg, async SQLAlchemy.defroutes run in a threadpool (40 threads by default). Blocking code is fine here, it only ties up one thread.async defwith blocking code inside is the worst combination. It runs on the loop and blocks it, so one slow request stalls every other one.
import asyncio
import time
from fastapi import FastAPI
app = FastAPI()
@app.get("/async-ok")
async def async_ok():
await asyncio.sleep(1) # loop serves other requests meanwhile
return {"ok": True}
@app.get("/sync-ok")
def sync_ok():
time.sleep(1) # runs in the threadpool, loop unaffected
return {"ok": True}
@app.get("/broken")
async def broken():
time.sleep(1) # on the loop, blocks every request in the app
return {"ok": True}If you aren't sure whether a library is async, use def. You'll leave a bit
of throughput on the table, but you won't freeze the server.
Connection pools belong in lifespan, not in your route. Opening a database
connection is slow (TCP handshake, TLS, auth). Doing it on every request
throws away most of what async buys you. Create the pool once at startup and
close it at shutdown:
import os
from contextlib import asynccontextmanager
import asyncpg
from fastapi import FastAPI, HTTPException, Request
DATABASE_URL = os.environ["DATABASE_URL"]
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = await asyncpg.create_pool(DATABASE_URL, min_size=1, max_size=10)
yield
await app.state.pool.close()
app = FastAPI(lifespan=lifespan)
@app.get("/users/{user_id}")
async def get_user(user_id: int, request: Request):
async with request.app.state.pool.acquire() as conn:
row = await conn.fetchrow("SELECT id, email FROM users WHERE id = $1", user_id)
if row is None:
raise HTTPException(status_code=404)
return dict(row)The same goes for httpx.AsyncClient. Create one in lifespan and reuse it,
rather than opening a new one per request.
Async vs classic Django on WSGI
Classic Django on WSGI (gunicorn, uWSGI) handles one request per thread or process. While a request waits 200ms on Postgres, that worker does nothing. To handle 100 requests in flight, you need about 100 workers or threads, each with its own memory.
An async server runs one event loop with many requests in flight. While one waits on Postgres, the loop moves on to the next. A single process can hold thousands of open requests, as long as they spend most of their time waiting.
That's why async is great for I/O-heavy APIs, the kind that mostly calls a database and other services and stitches the results together. It's the wrong tool for CPU work. If an endpoint needs to process an image or crunch a report, push that to a process pool or to a Celery worker:
import asyncio
from concurrent.futures import ProcessPoolExecutor
def crunch(n: int) -> int:
return sum(i * i for i in range(n))
async def main():
loop = asyncio.get_running_loop()
with ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, crunch, 10_000_000)
print(result)
if __name__ == "__main__":
asyncio.run(main())A separate process has its own GIL, so the work actually runs in parallel and the loop stays responsive. For anything slow enough that the user shouldn't wait on it at all, use Celery and return right away.
Why it fits WebSockets
A WebSocket connection is long-lived and mostly idle. A user connects, and then the connection sits there for minutes waiting for the next message.
With a thread per connection, 5,000 users means 5,000 threads doing nothing.
With asyncio, each connection is a coroutine paused on await websocket.receive_text(). A paused coroutine costs a few KB of memory and no
CPU. The loop only wakes it when a message actually arrives.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
app = FastAPI()
@app.websocket("/ws")
async def ws(websocket: WebSocket):
await websocket.accept()
try:
while True:
message = await websocket.receive_text() # paused here almost all the time
await websocket.send_text(f"echo: {message}")
except WebSocketDisconnect:
passThat's the shape of every WebSocket handler I write for CodifyLive. The rules from earlier matter even more here. One blocking call inside that loop doesn't slow down one request, it freezes every connected user at once.
Exercises to make it stick
Reading this won't make it stick. Breaking it on purpose will.
-
Time the gather example. Run
gather.pyand confirm about 2 seconds. Change it back to two sequential awaits and watch it go to 3. -
Kill the concurrency. Inside
get(), swapawait asyncio.sleep(delay)fortime.sleep(delay). Keep thegather. It now takes 3 seconds, because nothing ever hands control back to the loop. -
Freeze a FastAPI app. Add an
async defroute withtime.sleep(5). Run it withuvicorn main:app, open it in two browser tabs at once, and watch the second tab wait about 10 seconds. Change it toawait asyncio.sleep(5)and both finish in about 5. (Some browsers hold back a second request to the same URL, so add a query string like?a=1and?a=2.) -
Fetch 20 URLs, then cap concurrency. Fetch them all at once in a
TaskGroup, then limit it to 5 at a time with a semaphore. This is what you do in real code so you don't hammer someone else's API or exhaust your connection pool. Public test APIs rate-limit you fast, so point it at a route on the app from exercise 3:
@app.get("/slow")
async def slow():
await asyncio.sleep(1)
return {"ok": True}import asyncio
import time
import httpx
URLS = [f"http://127.0.0.1:8000/slow?i={i}" for i in range(20)]
async def fetch(client: httpx.AsyncClient, sem: asyncio.Semaphore, url: str) -> int:
async with sem: # at most 5 requests in flight
response = await client.get(url)
return response.status_code
async def main():
sem = asyncio.Semaphore(5)
start = time.perf_counter()
async with httpx.AsyncClient(timeout=30) as client:
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(client, sem, url)) for url in URLS]
codes = [t.result() for t in tasks]
print(codes.count(200), "ok in", f"{time.perf_counter() - start:.1f}s")
asyncio.run(main())With Semaphore(20) it takes about 1 second. With 5 it takes about 4: four
batches of five.
Wrapping up
The model is small. One thread, one loop, and await is the only place the
loop gets to switch. Concurrency only happens when you give the loop more than
one thing to do, with gather or a TaskGroup. And one blocking call stalls
everything.
Once that clicks, most async bugs are easy to spot in review. Look for blocking
calls inside async def, and look for awaits in a row that could have run
together.