asyncio vs threads in FastAPI
In FastAPI, when should an endpoint be async def vs def, and what goes wrong if you block the event loop?
Answers use simple, clear English.
Quick interview answer
Use async def when awaiting I/O (DB drivers, HTTP). Use plain def for sync CPU or blocking libraries — FastAPI runs them in a threadpool. Never call time.sleep or sync requests inside async def; it blocks the whole event loop and stalls other requests.
Detailed answer
Use async def when awaiting I/O (DB drivers, HTTP). Use plain def for sync CPU or blocking libraries — FastAPI runs them in a threadpool. Never call time.sleep or sync requests inside async def; it blocks the whole event loop and stalls other requests. Prefer asyncio.to_thread or ProcessPool for heavy CPU.
Real example & use case
async endpoint awaits asyncpg; sync pandas transform runs in def endpoint or to_thread.
Pros & cons
Pros: high concurrency for I/O. Cons: one blocking call ruins latency for all.