skip to content

In a FastAPI app, how does a yield dependency give each request its own database Session, and why is the engine created only once?

level: juniorimportance: must knowfreq 70%

answer

  1. two objects, two lifetimes
  2. pool lives in one object
  3. generator dependency around a with block
  4. Annotated alias in every signature

basics

~20 s

Create the engine once per process, write get_session() that yields a Session inside a with block, and alias it as SessionDep = Annotated[Session, Depends(get_session)]. FastAPI calls it once per request and closes the session afterwards.

solid answer

~40 s

The engine owns the connection pool, so it is created once, at import or in the `lifespan`, and shared. `get_session()` runs `with Session(engine) as session: yield session`: FastAPI executes the code up to `yield` before the endpoint, injects the session, and by default resumes the generator after the response is sent, which closes the session and returns its connection to the pool. `SessionDep = Annotated[Session, Depends(get_session)]` lets each endpoint write `session: SessionDep`. Within one request FastAPI caches the dependency, so the endpoint and a `get_current_customer` dependency that both declare `SessionDep` share one session; the next request gets a new one. Calling `create_engine` inside the dependency would build a new pool per request and defeat pooling.

code

python · 34 lines
python
from typing import Annotated

from fastapi import Depends, FastAPI
from sqlmodel import Field, Session, SQLModel, create_engine


class Order(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    sku: str
    quantity: int


# One engine per process, created at import; in production the URL points at PostgreSQL.
engine = create_engine("sqlite:///orders.db", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)


def get_session():
    with Session(engine) as session:
        yield session


SessionDep = Annotated[Session, Depends(get_session)]

app = FastAPI()


@app.post("/orders")
def place_order(sku: str, quantity: int, session: SessionDep) -> Order:
    order = Order(sku=sku, quantity=quantity)
    session.add(order)
    session.commit()
    session.refresh(order)
    return order

go deeper

for a junior

Recall the three pieces: one engine, a get_session generator that yields inside a with block, and the SessionDep alias declared on each endpoint.

for a middle

Explain when each part of get_session runs relative to the endpoint and the response, and why the per-request cache makes nested dependencies share one session.

for a senior

Show you know what the engine owns, why building it per request destroys pooling, and why SQLite needs check_same_thread disabled when a request hops threads.

for a principal

Treat SessionDep as a team convention: one place that decides session lifetime, which tests can override and which keeps transaction boundaries uniform across endpoints.

## Two objects with different lifetimes A database-backed FastAPI app built on SQLModel or SQLAlchemy works with two objects, and the whole recipe is about giving each the right lifetime. | Object | What it holds | How many | Created where | |---|---|---|---| | **Engine** (`create_engine(...)`) | The connection pool and the database URL | One per process | At import, or in the app's `lifespan` | | **Session** (`Session(engine)`) | Loaded objects, pending changes, the current transaction | One per request | Inside the session dependency | The **engine** is expensive and shared: it owns the pool of open connections. The **session** is cheap and private: it tracks the objects one request loaded or added and borrows a connection from the engine's pool when it first talks to the database. ## Writing the dependency ```python from typing import Annotated from fastapi import Depends from sqlmodel import Session, create_engine engine = create_engine("sqlite:///orders.db", connect_args={"check_same_thread": False}) def get_session(): with Session(engine) as session: yield session SessionDep = Annotated[Session, Depends(get_session)] ``` `get_session` is a **dependency with `yield`**: a generator function FastAPI turns into a context manager. `SessionDep` is an `Annotated` alias, so every path operation writes `session: SessionDep` instead of repeating `Depends(get_session)`. In production the URL points at PostgreSQL; SQLite keeps the example self-contained. ## What FastAPI does on each request 1. While resolving the endpoint's parameters it finds `SessionDep` and calls `get_session()`. Because it is a plain `def` generator, FastAPI enters it in its thread pool. 2. The code up to `yield` runs: `Session(engine)` is created. No connection is taken yet; the session checks one out on its first query. 3. The yielded session is injected into the endpoint, and into any other dependency in the same request that declares `SessionDep`, because FastAPI caches a dependency's value for the duration of one request. 4. The endpoint adds, queries and commits through it. 5. After the response is sent (the default `scope="request"`), FastAPI resumes the generator. The `with` block ends, the session closes, and its connection goes back to the engine's pool. The next request repeats the whole sequence with a brand-new session, so no two requests ever share pending changes or a transaction. ## Why the engine is never built per request - `create_engine` builds a **new pool**. Calling it inside `get_session` means every request opens fresh connections and discards them, which throws away pooling entirely. - Many engines also means many pools that each think they own the connection budget, so the total number of open connections stops being something you configured. - The engine is safe to share across threads and requests; a session is not meant to be shared, which is exactly why it lives inside the dependency. ## The SQLite `check_same_thread` argument Python's `sqlite3` driver refuses, by default, to use a connection from a thread other than the one that created it. One FastAPI request can touch its session from more than one thread: the `def` dependency is entered in the thread pool, a `def` endpoint runs on a worker thread, and teardown may run on yet another. The FastAPI tutorial therefore passes `connect_args={"check_same_thread": False}`. That is safe here because the session-per-request pattern keeps one request on a session at a time. SQLAlchemy 2 already sets the flag to `False` for file databases; it still matters for an in-memory database, which tests often use. ## Variations you will meet The recipe above is the one in FastAPI's own SQL databases tutorial, but codebases dress it differently. All of these keep the same lifetime, one session per request closed in teardown: - **No alias**: `session: Session = Depends(get_session)` behaves the same; the `Annotated` alias is the form FastAPI's docs now use, and it keeps signatures short and consistent. - **A session factory**: `SessionLocal = sessionmaker(engine)` at module level and `with SessionLocal() as session: yield session` in the dependency, which lets session options live in one place. - **An engine built in the `lifespan`**: the dependency then takes `request: Request` and reads the engine from `request.app.state` instead of a module global, which makes it easier to point at a different database in tests. - **An async variant**: an `async def` generator that yields an `AsyncSession`, used by `async def` endpoints that await every query. Whatever the shape, the review question is the same: is the pool created once, and does exactly one place open and close each request's session? ## Mistakes interviewers listen for - A **module-level session** shared by all requests: concurrent requests then interleave their changes and transactions. - A dependency that **returns** `Session(engine)` instead of yielding it: a plain `return` dependency has no teardown, so nothing closes the session. - Calling `session.close()` by hand in every endpoint: the `with` block in the dependency already does it, and the manual call is easy to skip on an error path. - Expecting two declarations of `SessionDep` in one request to give two sessions: they share one unless a declaration passes `use_cache=False`.

  • Why does the FastAPI tutorial pass connect_args={"check_same_thread": False} when the database is SQLite?
    Python's `sqlite3` driver rejects use of a connection from a thread other than its creator, and one FastAPI request can use its session from several threads: the `def` dependency is entered in the thread pool, a `def` endpoint runs on a worker thread, and teardown may run on yet another. Because only one request uses a session at a time, disabling the check is safe. SQLAlchemy 2 already disables it for file databases; it still matters for in-memory ones.
  • If an endpoint and its get_current_customer dependency both declare session: SessionDep, how many sessions does one request open?
    One. FastAPI caches each dependency's value for the duration of the request, so `get_session` runs once and both receive the same `Session`, which also means they share one transaction. Declaring `Depends(get_session, use_cache=False)` in one place would open a second, independent session in the same request.

  • Create the engine inside get_session so each request gets fresh connections.
  • One module-level Session can safely be shared by every request.
  • A dependency that returns Session(engine) is closed automatically after the request.
  • Each endpoint must call session.close() itself or the connection leaks.
  • Two parameters typed SessionDep in one request get two separate sessions.