FastAPI: How async def and def Routes Actually Execute
A frequent interview question, and a common cause of "one slow request takes down every endpoint" in production.
Core concepts
| Style | Where it runs | What it can do |
|---|---|---|
async def route | Directly on the event loop thread | Only call non-blocking code you can await (httpx.AsyncClient, asyncpg, AsyncOpenAI…) |
def route | Put into a thread pool; the event loop awaits its result | Can call blocking code (requests, sync SDKs, sync ORMs) |
The conclusion in the official FastAPI docs: you can mix them and FastAPI will "do the right thing"; if you're unsure, use a plain def. The same applies to dependencies (Depends).
How it works: the request handling chain
uvicorn (ASGI server, runs the event loop)
→ Starlette (routing, middleware, Request/Response)
→ FastAPI (parameter parsing, dependency injection, Pydantic validation, serialization)
→ your route function: async def is awaited directly; def is handed to the anyio thread pool (run_in_threadpool)- The event loop is single-threaded: as soon as an
async defmakes a blocking call (time.sleep, sync HTTP, CPU-heavy computation), every request in the process stalls. - The thread pool has a capacity limit (set by anyio's default limiter). Many slow
defroutes fill it up and requests queue. - CPU-bound tasks (large PDF parsing, OCR) suit neither style; put them in a process pool or a separate worker.
In practice
python
import asyncio, time
from fastapi import FastAPI
from fastapi.concurrency import run_in_threadpool
app = FastAPI()
@app.get("/bad")
async def bad():
time.sleep(2) # ❌ blocks the event loop: every request stalls for these 2 seconds
return {"ok": True}
@app.get("/ok-sync")
def ok_sync():
time.sleep(2) # ✅ runs in the thread pool
return {"ok": True}
@app.get("/ok-async")
async def ok_async():
await asyncio.sleep(2) # ✅ non-blocking
return {"ok": True}
@app.get("/mixed")
async def mixed():
data = await run_in_threadpool(legacy_sync_parse, "a.pdf") # ✅ calling an unavoidable sync function from async
return dataHow to verify: send a request to /bad and at the same time request /ok-async; the latter also waits about 2 seconds.
Common pitfalls
- Sync LLM SDKs / requests / sync database drivers inside async routes: the most common performance incident.
- Assuming
defsolves everything: a full thread pool queues just the same; long tasks belong in a task queue. - Multiple workers don't make async code use more cores per se: uvicorn
--workers Nstarts N processes, each with its own event loop. - CPU-bound computation inside async code: use a
ProcessPoolExecutoror a separate worker.
Common interview questions
- Where do
async defanddefroutes each run? - What happens if you call a blocking SDK from an async route? How do you fix it?
- What are FastAPI, Starlette and uvicorn each responsible for?
- What happens when the thread pool is full? How do you observe and tune it?
- Why can't long tasks run inside the request? (See Task State Machine)
Sources
- FastAPI Docs: Concurrency and async / await — mixing rules, "use def when unsure", thread pool execution
- FastAPI Docs: Dependencies (async and def dependencies)
- Starlette Docs: Thread Pool — the thread pool and its capacity limit
- Uvicorn Docs: Deployment (workers)
