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()
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:
-
Free Starter
.cursorrules& Reviewer Prompts ($0+): Download Free Starter Pack (or GitHub Repo) - FastAPI & Python Microservices Toolkit ($19): Get Stack Kit
- All 10 Production Stacks Bundled ($99): 10-in-1 Ultimate Developer Suite
Top comments (0)