FastAPI chạy trên Starlette (ASGI), hỗ trợ cả sync và async endpoints:
async def: dùng khi endpoint thực hiện I/O async (database queries async, HTTP calls async):
python
@app.get("/users/{id}")
async def get_user(id: int, db: AsyncSession = Depends(get_db)):
user = await db.get(User, id) # Async I/O
return userdef (sync): khi dùng blocking operations không thể async.
FastAPI tự động chạy sync endpoint trong ThreadPoolExecutor để không block event loop:
python
@app.get("/compute")
def cpu_task(data: list):
return [x**2 for x in data] # CPU-bound — sync OKKhông được làm: gọi blocking I/O trong async def — block toàn bộ event loop:
python
@app.get("/wrong")
async def bad_endpoint():
time.sleep(1) # BLOCKING! Sai!
requests.get("...") # BLOCKING! Sai!
# Dùng asyncio.sleep() và httpx.AsyncClient() thay- Rule: I/O async →
async def. - CPU-bound hoặc blocking library →
def. - Không bao giờ dùng blocking I/O trong
async def.