Async FastAPI scales effortlessly—until an accidental blocking call or lazy relationship load freezes the entire Uvicorn worker.
1. Prevent N+1 Queries Explicitly
In Async SQLAlchemy 2.0, implicit lazy loading raises MissingGreenlet errors in async sessions. Always declare selectinload() or joinedload() :
from sqlalchemy import select from sqlalchemy . orm import selectinload
stmt = select ( Order ) . options ( selectinload ( Order . items ) ) . where ( Order . user_id == user_id ) result = await session . execute ( stmt ) orders = result . scalars ( ) . all ( )
Enter fullscreen mode
Exit fullscreen mode
2. Separate Routers, Services, and Repositories
Keep HTTP parsing in FastAPI routers, pure business logic in services, and raw SQLAlchemy queries in repositories. That way unit tests don't require spinning up an HTTP server for every edge case.
3.…