← Back to FastAPI, page 4

fastapi-0072 · Medium mid

How do you avoid the N+1 query problem with SQLAlchemy relationships in FastAPI, and how do nested response models interact with lazy loading?

By default SQLAlchemy loads related rows lazily: touching student.class_room inside a list loop issues one query per row. When a response model reads those attributes during serialisation, the hidden queries multiply. Fix it by choosing a loader strategy in the query: selectinload (a second query using IN, best for collections), joinedload (a JOIN, good for many-to-one), or lazy="raise" to catch accidental lazy loads. Always verify with a query counter.

Full answer

The problem in FastAPI: your endpoint returns ORM objects and the response model includes class_room: ClassRoomOut. Serialisation touches student.class_room for each student after your function returned, so each access lazy-loads. 100 students become 101 queries. With async sessions it is worse: lazy loading raises MissingGreenlet.

Fixes (sqlalchemy.orm):

  • selectinload(Student.marks): runs one extra SELECT ... WHERE student_id IN (...), avoiding row multiplication. Best for one-to-many and many-to-many collections.
  • joinedload(Student.class_room): adds a LEFT OUTER JOIN to the main query. Good for many-to-one and one-to-one; with collections it multiplies rows (use .unique() on results).
  • subqueryload (older), contains_eager (when you already joined and filtered), raiseload("*") or lazy="raise" to turn accidental lazy loads into errors during development.
  • Load only needed columns with load_only(...) when rows are wide.

Practice:

  1. Decide per endpoint which relations the response needs; put the options in the query in the repository or service, not in model defaults (a global lazy="joined" hurts other queries).
  2. Return a response model matching what you loaded; do not include relations you did not load.
  3. Count queries in tests: SQLAlchemy's before_cursor_execute event, or a fixture that asserts at most N statements, protects against regressions.
  4. Paginate before joining collections; a LIMIT with a joined collection applies to joined rows unless SQLAlchemy wraps it in a subquery (it does for joinedload with limits, at some cost).
  5. Use from_attributes=True models so Pydantic reads loaded attributes.
  6. Know the identity map: a lazy many-to-one load first checks the session's identity map, so repeated parents are fetched once (the snippet shows 2 room queries for 6 students), while collection lazy loads such as student.marks always query once per parent.

For aggregates (counts per class) use SQL GROUP BY instead of loading collections.

python
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, ConfigDict
from sqlalchemy import ForeignKey, create_engine, event, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, joinedload, mapped_column, relationship, selectinload, sessionmaker
from sqlalchemy.pool import StaticPool


class Base(DeclarativeBase):
    pass


class ClassRoom(Base):
    __tablename__ = "class_room"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    students: Mapped[list["Student"]] = relationship(back_populates="class_room")


class Student(Base):
    __tablename__ = "student"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]
    class_room_id: Mapped[int] = mapped_column(ForeignKey("class_room.id"))
    class_room: Mapped[ClassRoom] = relationship(back_populates="students")
    marks: Mapped[list["Mark"]] = relationship()


class Mark(Base):
    __tablename__ = "mark"
    id: Mapped[int] = mapped_column(primary_key=True)
    student_id: Mapped[int] = mapped_column(ForeignKey("student.id"))
    score: Mapped[int]


engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
SessionLocal = sessionmaker(engine)
statements = []
event.listen(engine, "before_cursor_execute", lambda conn, cur, stmt, *a: statements.append(stmt))

with SessionLocal() as s:
    rooms = [ClassRoom(name="10A"), ClassRoom(name="10B")]
    s.add_all(rooms)
    s.flush()
    for i in range(6):
        st = Student(name=f"S{i}", class_room_id=rooms[i % 2].id)
        st.marks = [Mark(score=50 + i), Mark(score=60 + i)]
        s.add(st)
    s.commit()


class RoomOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    name: str


class MarkOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    score: int


class StudentOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    name: str
    class_room: RoomOut
    marks: list[MarkOut]


def get_db():
    with SessionLocal() as db:
        yield db


DB = Annotated[Session, Depends(get_db)]
app = FastAPI()


@app.get("/lazy", response_model=list[StudentOut])
def lazy(db: DB):
    return db.scalars(select(Student)).all()                      # class_room is loaded per row while serialising


@app.get("/eager", response_model=list[StudentOut])
def eager(db: DB):
    return db.scalars(select(Student).options(joinedload(Student.class_room), selectinload(Student.marks))).unique().all()


c = TestClient(app)
for path in ("lazy", "eager"):
    statements.clear()
    r = c.get(f"/{path}")
    selects = [s for s in statements if s.lstrip().upper().startswith("SELECT")]
    print(path, r.status_code, len(r.json()), "students ->", len(selects), "SELECT statements")

Standalone script. Run it with `python file.py`; it uses an in-memory SQLite database through a shared StaticPool. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): lazy 200 6 students -> 9 SELECT statements eager 200 6 students -> 2 SELECT statements

Key points

  • Lazy loading during serialisation causes N+1 queries
  • selectinload for collections; joinedload for many-to-one
  • lazy='raise' turns accidental lazy loads into errors
  • Set loader options per query, not globally
  • Count queries in tests

Common mistakes

  • Letting the response model lazy-load relations during serialisation
  • Setting lazy='joined' on a relationship globally
  • Using joinedload on collections without unique()
  • Never counting queries in tests
  • Loading whole collections just to count them

Follow-ups

  • How do you detect N+1 queries in production?
  • Why does lazy loading fail in async sessions?
  • When is joinedload better than selectinload?

Tips

  • Explain why serialisation triggers lazy loads
  • Name three loader options
  • Mention query counting in tests