Difficulty: Intermediate
When should a FastAPI route handler be async def and when should it be plain def? What happens if you get it wrong?
Use async def when everything slow inside the handler is awaitable, such as httpx.AsyncClient, asyncpg or SQLAlchemy's async session. Use plain def when you call blocking libraries like requests, psycopg2 or most SDKs, because FastAPI runs def handlers in a threadpool so they do not block the event loop. The worst case is a blocking call inside async def: it freezes the event loop and every other request on that worker waits.
async def: called directly on the event loop. While it is awaiting I/O, the loop serves other requests. One worker can hold thousands of idle connections this way.def: FastAPI wraps it with Starlette's run_in_threadpool, which runs it in an AnyIO worker thread. The default thread limit is 40, so roughly 40 sync handlers can block at the same time per worker before new ones queue.| Handler | Library | Result |
|---|---|---|
async def | await httpx.AsyncClient().get() | Good: non-blocking |
def | requests.get() | Good: blocks only a pool thread |
async def | requests.get() or time.sleep() | Bad: whole worker stalls |
async def | Heavy CPU loop (image resize, ML inference) | Bad: loop starved, even though no I/O |
With the bad case, a single slow third-party call (say a 3 second KYC API) makes health checks and unrelated requests on that worker hang for 3 seconds. Under load this looks like random latency spikes and timeouts.
async def, offload blocking calls with await run_in_threadpool(func, args) (from fastapi.concurrency) or await asyncio.to_thread(func, args).ProcessPoolExecutor, a task queue like Celery, or a separate service.asyncio.run() inside a handler; the loop is already running.async def avoids a thread hop.async def and await them.def, or offload it explicitly.Async shines for I/O fan-out, such as calling payment, inventory and pricing services concurrently with asyncio.gather. It does not make a single database query faster. Many production teams run sync SQLAlchemy with def handlers successfully; the important thing is consistency and never blocking the loop.
| async def | def | |
|---|---|---|
| Runs on | The event loop | A threadpool worker thread |
| Safe libraries | httpx async, asyncpg, aioredis | requests, psycopg2, boto3 |
| Blocking call effect | Stalls every request on the worker | Occupies one pool thread |
| Concurrency limit | Thousands of awaiting tasks | About 40 threads by default |
import asyncio
import time
import httpx
import requests
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
app = FastAPI()
@app.get("/good-async")
async def good_async():
async with httpx.AsyncClient(timeout=5) as client:
r = await client.get("https://api.example.com/data") # yields to the loop
return r.json()
@app.get("/good-sync")
def good_sync():
r = requests.get("https://api.example.com/data", timeout=5) # runs in threadpool
return r.json()
@app.get("/bad")
async def bad():
time.sleep(3) # BLOCKS the event loop for every request
return {"ok": True}
@app.get("/offloaded")
async def offloaded():
await run_in_threadpool(time.sleep, 3) # blocking work moved to a thread
return {"ok": True}
@app.get("/fan-out")
async def fan_out():
async with httpx.AsyncClient(timeout=5) as client:
pay, stock = await asyncio.gather(
client.get("https://payments.internal/status"),
client.get("https://inventory.internal/stock"),
)
return {"payments": pay.status_code, "inventory": stock.status_code}
The /bad route makes all requests on that worker wait three seconds. The fan-out route shows the real win of async: concurrent I/O in one request.
async def vs def, event loop, threadpool, blocking I/O, run_in_threadpool