Menu

FastAPI + Async SQLAlchemy 2.0: Eliminating N+1 Queries and Blocking Event Loops
📰

FastAPI + Async SQLAlchemy 2.0: Eliminating N+1 Queries and Blocking Event Loops

DEV Community: fastapi·AutoLab Systems·17 days ago
#ds5XEObN
#devtofastapi#devto#dev#sqlalchemy#async
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.