Careeroza
async def vs def
When to Use async
| Write | When | How FastAPI runs it |
|---|---|---|
async def | you await async libraries (httpx.AsyncClient, asyncpg, aiofiles) | on the event loop |
def | you call blocking code (requests, most DB drivers, file I/O) | in a thread pool, so the loop stays free |
Note: Never call blocking code (like time.sleep or requests.get) inside async def: it freezes every other request on that worker.
Concurrent Awaits
Example
asyncio.gather runs independent I/O at the same time. Three 0.2 s "requests" finish in about 0.2 s, not 0.6 s:
import asyncio, time
async def fetch(name: str, delay: float) -> str:
await asyncio.sleep(delay) # stands in for a network call
return f"{name} done"
async def main():
start = time.perf_counter()
results = await asyncio.gather(fetch("users", 0.2), fetch("orders", 0.2), fetch("stock", 0.2))
print(results)
print("took about", round(time.perf_counter() - start, 1), "seconds")
asyncio.run(main())Output
['users done', 'orders done', 'stock done'] took about 0.2 seconds