DEV Community

AutoLab Systems
AutoLab Systems

Posted on

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

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. Standardize Error Payloads (RFC 7807)

Return consistent JSON problem details (title, status, detail) via a central exception handler rather than leaking raw tracebacks.


Want Production-Ready .cursorrules & Boilerplates?

I'm a student developer in Japan funding my upcoming new life next spring by packaging strict, battle-tested AI coding setups:

Top comments (0)