Python / FastAPI Interview Questions
When should you use async def vs def for route handlers in FastAPI?
FastAPI supports both async def and plain def route handlers. The choice has real performance implications because of how FastAPI's underlying ASGI server (Uvicorn + Starlette) handles concurrency.
| Handler type | How FastAPI runs it | When to use |
|---|---|---|
| async def | Runs directly on the event loop | I/O-bound async work: awaiting HTTP calls, async DB drivers (asyncpg, motor), async file I/O |
| def (sync) | Runs in a thread pool (executor) to avoid blocking the event loop | CPU-bound work, or libraries that are synchronous only (psycopg2, requests, pandas) |
import asyncio
import httpx
from fastapi import FastAPI
app = FastAPI()
# GOOD: truly async I/O — does not block the event loop
@app.get("/async-data")
async def get_data():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
return response.json()
# ALSO GOOD: synchronous — FastAPI runs this in a thread pool
@app.get("/sync-data")
def get_data_sync():
import requests # sync library
response = requests.get("https://api.example.com/data")
return response.json()
# DANGEROUS: blocking call inside async def without await
# This blocks the entire event loop, killing concurrency
@app.get("/bad")
async def bad_handler():
import time
time.sleep(5) # NEVER do this in async def
return {"message": "slow"}
# CORRECT: use asyncio.sleep in async context
@app.get("/good-async-wait")
async def good_handler():
await asyncio.sleep(5) # non-blocking
return {"message": "waited"}
Rule of thumb: if your route calls await somewhere, use async def. If your route only calls synchronous libraries, use plain def — FastAPI will correctly run it in a threadpool, keeping the event loop free.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
