DEV Community

Cover image for Two Depends(get_session), One Session: FastAPI's Dependency Cache and Its Order Trap
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

Two Depends(get_session), One Session: FastAPI's Dependency Cache and Its Order Trap


Your endpoint asks for a session. Your repository asks for a session. Both write Depends(get_session). It is easy to picture two sessions, two transactions, two connections checked out of the pool. FastAPI hands both parameters the same object, and it does so on purpose: the sub-dependencies docs say a dependency declared several times for one path operation is called "only once per request", and the value is saved in a "cache" for every dependant that needs it.

Most of the time that is exactly what you want. Sometimes it quietly merges two transactions you meant to keep apart. And the escape hatch, use_cache=False, has a behaviour that depends on the order of your parameters. That last part is not in the docs. It is in about twenty lines of fastapi/dependencies/utils.py, so start there.

Where the cache lives

The code below is from the master branch of fastapi/fastapi as of this writing (latest release: 0.165.0). The function is solve_dependencies in fastapi/dependencies/utils.py. It walks the dependency tree depth-first. Each sub-dependency is solved recursively first, so its own dependencies run before it. Then comes the cache check. Here is that part, trimmed and re-wrapped to fit, with sub_dependant_cache_key renamed to key and the coroutine and threadpool branches folded into one:

# fastapi/dependencies/utils.py, inside solve_dependencies()
for sub_dependant in dependant.dependencies:
    ...  # apply overrides, recurse into its own deps
    key = _get_cache_key(
        dependant=sub_dependant,
        uses_scopes_cache=_uses_scopes_cache,
    )
    if sub_dependant.use_cache and key in dependency_cache:
        solved = dependency_cache[key]
    elif _is_gen_callable(...) or _is_async_gen_callable(...):
        solved = await _solve_generator(...)  # yield deps
    else:
        solved = await call(**solved_result.values)
    if sub_dependant.name is not None:
        values[sub_dependant.name] = solved
    if key not in dependency_cache:
        dependency_cache[key] = solved
Enter fullscreen mode Exit fullscreen mode

Three facts fall out of this. First, dependency_cache is a plain dict, created inside solve_dependencies when none is passed in, and the request handler in fastapi/routing.py calls it without one. So the cache lives for one request and dies with it. Second, use_cache gates only the read. Third, the write at the bottom runs for every dependency, cached or not, and only if the key is still free. Hold on to that third one.

The key comes from _get_cache_key in fastapi/dependencies/models.py (type hints dropped here):

def _get_cache_key(*, dependant, uses_scopes_cache=None):
    scopes_for_cache = (
        tuple(sorted(set(_get_oauth_scopes(dependant=dependant))))
        if _uses_scopes(dependant=dependant, cache=uses_scopes_cache)
        else ()
    )
    return (
        dependant.call,
        scopes_for_cache,
        _get_computed_scope(dependant=dependant) or "",
    )
Enter fullscreen mode Exit fullscreen mode

The key is a tuple of the callable itself, the OAuth scopes (only when the dependency uses security scopes), and the dependency's scope. use_cache is not in it. The return type annotation is not in it either: two different functions that both return an AsyncSession get two cache entries, even with identical bodies. One function object referenced from five places gets one.

A request enters a branching tree of dependency nodes; two branches reach for the same function and converge on one shared object
Every branch that names the same callable gets the one value stored under its key.

The shared case, reproduced

You can see this without a database. The fake session below counts how many times it was built, and the endpoint reports which instance each parameter received. You need fastapi and httpx (for TestClient) installed.

import itertools
from typing import Annotated

from fastapi import Depends, FastAPI

_ids = itertools.count(1)

class FakeSession:
    def __init__(self) -> None:
        self.id = next(_ids)

def get_session():
    session = FakeSession()
    try:
        yield session
    finally:
        pass  # a real one would close here
Enter fullscreen mode Exit fullscreen mode

The repository asks for the same dependency through a shared Annotated alias, and so does the endpoint:

SessionDep = Annotated[FakeSession, Depends(get_session)]

class OrderRepo:
    def __init__(self, session: SessionDep) -> None:
        self.session = session

RepoDep = Annotated[OrderRepo, Depends()]
app = FastAPI()

@app.get("/shared")
def shared(repo: RepoDep, session: SessionDep):
    return {"repo": repo.session.id, "endpoint": session.id}
Enter fullscreen mode Exit fullscreen mode

Depends() with no argument inside Annotated uses the annotated class as the dependency, so FastAPI builds OrderRepo and resolves its session parameter first. That call to get_session stores its session under the key (get_session, (), "request"). When the endpoint's own session parameter comes up, the key is already there and use_cache is true, so it gets the same instance. A test states what the source predicts:

from fastapi.testclient import TestClient

client = TestClient(app)

def test_repo_and_endpoint_share_one_session():
    body = client.get("/shared").json()
    assert body["repo"] == body["endpoint"]
Enter fullscreen mode Exit fullscreen mode

use_cache=False, and the order trap

The documented fix for "I want a fresh one" is Depends(get_session, use_cache=False). The Depends docstring says it makes sure "the dependency is called again". That is true for the parameter that carries the flag. Now add two endpoints that differ only in parameter order. get_dependant collects sub-dependencies by looping over the signature in order, so parameter order is resolution order.

FreshDep = Annotated[
    FakeSession, Depends(get_session, use_cache=False)
]

@app.get("/fresh-last")
def fresh_last(repo: RepoDep, audit: FreshDep):
    return {"repo": repo.session.id, "audit": audit.id}

@app.get("/fresh-first")
def fresh_first(audit: FreshDep, repo: RepoDep):
    return {"repo": repo.session.id, "audit": audit.id}
Enter fullscreen mode Exit fullscreen mode

In /fresh-last, the repo resolves first and stores its session. The audit parameter skips the read, builds a new session, and the write is skipped because the key is taken. Two sessions. In /fresh-first, audit builds a new session first, and the unconditional write stores it, because the key was free. Then the repo's get_session finds the key and reuses the audit session. One session, even though you wrote use_cache=False.

def test_fresh_last_gets_its_own_session():
    body = client.get("/fresh-last").json()
    assert body["repo"] != body["audit"]

def test_fresh_first_leaks_into_the_cache():
    body = client.get("/fresh-first").json()
    assert body["repo"] == body["audit"]
Enter fullscreen mode Exit fullscreen mode

These assertions come from reading the code above; I haven't run them myself, so run them against your FastAPI version before you rely on them. The rule they encode: use_cache=False means "this parameter gets a fresh value", not "this value stays private". If it resolves first, everyone after it shares it.

The scope part of the key has its own surprise. FastAPI 0.121.0 added dependency scopes, a scope parameter on Depends for yield dependencies; scope="function" closes the dependency before the response is sent. _get_computed_scope returns "request" for any generator that sets no scope, so Depends(get_session) and Depends(get_session, scope="function") produce different keys and two sessions. Mix them across a repository and an endpoint and you have split a transaction without touching use_cache.

When sharing is the point, and when it is a bug

Here is a real session dependency with SQLAlchemy 2.0's asyncio extension:

from sqlalchemy.ext.asyncio import (
    async_sessionmaker,
    create_async_engine,
)

engine = create_async_engine("sqlite+aiosqlite:///app.db")
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)

async def get_session():
    async with SessionLocal() as session:
        async with session.begin():
            yield session
Enter fullscreen mode Exit fullscreen mode

session.begin() commits when the block exits cleanly and rolls back when an exception reaches it. With the cache, a repository and a unit of work that both ask for get_session write inside one transaction, and that is what you want for "insert the order and its lines, or neither". You get it without passing the session around by hand.

It turns into a bug in two common shapes. The first is an audit or outbox record that must survive a rollback. If the audit adapter also asks for Depends(get_session), it joins the same transaction; when the endpoint raises, the rollback erases the audit row along with the order. The second is concurrency. Two repositories that you believe hold separate sessions, run under asyncio.gather, are driving one AsyncSession from two tasks. SQLAlchemy's docs say a single AsyncSession "is not safe for use in multiple, concurrent tasks" and that concurrent tasks should use a separate session each.

One more timing detail. The yield-dependency docs say the exit code of a yield dependency normally runs after the response is sent. With the get_session above, the commit happens after the client already has its response. scope="function" moves the exit to before the response, which is often what a commit wants. Change it on every Depends(get_session) at once, though, or the key mismatch from the last section gives you two sessions.

Two sealed jars on either side of a thin wall, one holding a stack of order documents and the other a ledger strip, each with its own lid
The audit log gets its own transaction because one function at the edge says so.

Keep Depends at the edge

All of the above is wiring. The cache decides which objects end up sharing a session, and it decides by callable identity, scope and parameter order. That is fine for the HTTP layer and a poor thing to bake into your business logic. The fix is to let one function at the edge make the sharing decision out loud, and hand the use case plain ports that know nothing about Depends:

from typing import Protocol

class OrderRepository(Protocol):
    async def add(self, order: "Order") -> None: ...

class AuditLog(Protocol):
    async def record(self, event: str) -> None: ...

class PlaceOrder:
    def __init__(
        self, orders: OrderRepository, audit: AuditLog
    ) -> None:
        self._orders = orders
        self._audit = audit

    async def __call__(self, order: "Order") -> None:
        await self._audit.record(f"place {order.id}")
        await self._orders.add(order)
Enter fullscreen mode Exit fullscreen mode
from typing import Annotated

from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession

async def get_place_order(
    session: Annotated[AsyncSession, Depends(get_session)],
) -> PlaceOrder:
    return PlaceOrder(
        orders=SqlOrderRepository(session),
        audit=SqlAuditLog(SessionLocal),  # opens its own
    )
Enter fullscreen mode Exit fullscreen mode

Order and the two SQL adapters are left out; get_session and SessionLocal are the ones from the previous section. The point is the shape. The endpoint depends on get_place_order and nothing else. The repository gets the request's session; the audit log gets the session factory and opens its own transaction per record, so it survives a rollback of the order. You can read that choice in four lines instead of reconstructing it from parameter order. And PlaceOrder can be tested with two in-memory fakes, no TestClient and no dependency cache, so "which session did I get" never comes up.

If you do test through HTTP, app.dependency_overrides is keyed by the original function, and the cache key is computed from the original too, so overriding get_session keeps the same sharing pattern you have in production.


If this was useful

The move in the last section, one composition function at the framework edge and a core that only sees ports, is the backbone of Hexagonal Architecture in Python. The book builds one async FastAPI + SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice) and then measures them, so you can see what each style does to exactly this kind of wiring. Every listing runs from the free companion repo, and the book itself is on Amazon.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)