Trung BìnhPython iconPython

Async vs sync endpoints trong FastAPI — khi nào dùng def hay async def?

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 user

def (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 OK

Khô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.

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python