Tech Verse Logo
Enable dark mode
FastAPI Dependency Injection Scope Leaks in Production

FastAPI Dependency Injection Scope Leaks in Production

•Updated •9 min read

FastAPI creates a dependency's return value once per request, but anything kept outside it lives for the whole process and is shared by concurrent requests. Don't write request data to self on a callable-instance dependency, don't put lru_cache on functions that take request input, and don't keep context in threading.local. Return request data instead, and test with concurrent requests.

FastAPI's dependency injection looks stateless. You write a function, wrap it in Depends(), and FastAPI calls it for every request. So when a report shows one customer's ID in another customer's audit log, the DI system is the last place people look. But the leak is nearly always there: some object built for one request ended up living for the whole process.

The fix starts with a precise picture of what FastAPI creates per request and what it doesn't. Get that right and most of these bugs become obvious just from reading the code.

The three lifetimes in FastAPI DI

Every value your route touches has one of three lifetimes, whether or not you chose it on purpose.

  • Process lifetime. Anything created at import time or in the lifespan handler: module-level objects, class instances you pass to Depends(), anything behind functools.lru_cache, and thread-locals in the worker threads FastAPI reuses. Every request in that worker process shares it.
  • Request lifetime. The return value of a dependency. FastAPI calls each dependency at most once per request and caches the result for that request only. A yield dependency's cleanup runs after the response has been sent.
  • Function lifetime. A yield dependency declared with Depends(dep, scope="function"). Its cleanup runs as soon as the path operation function returns, before the response goes out.

A scope leak is request data stored in something with process lifetime. In an async app the overlap is guaranteed: while one request awaits the database, the event loop runs others, so two requests can be halfway through the same handler at the same moment.

Leak one: state on a callable instance

FastAPI's docs show parameterized dependencies: a class with __call__, one instance created at module level, and Depends(instance) in the route. FastAPI calls __call__ on every request, but __init__ ran exactly once, when the module was imported. Store anything on self inside __call__ and every request writes to the same object.

import asyncio
from typing import Annotated

from fastapi import Depends, FastAPI


class AuditTrail:
    def __init__(self) -> None:
        self.user_id: str | None = None

    async def __call__(self, user_id: str) -> "AuditTrail":
        self.user_id = user_id
        return self


audit = AuditTrail()
app = FastAPI()


@app.get("/orders")
async def list_orders(trail: Annotated[AuditTrail, Depends(audit)], user_id: str):
    await asyncio.sleep(0.05)  # stands in for a database call
    return {"asked_by": user_id, "logged_as": trail.user_id}

Fire three requests at once with users u0, u1 and u2 and all three responses report "logged_as": "u2". Each request set self.user_id and then gave up control at the await, and the last write won. Run one request at a time, which is what most manual testing does, and you'll never see it.

There are two fixes. If the class needs request data, pass the class itself, Depends(AuditTrail), with user_id as an __init__ parameter. FastAPI then builds a new instance per request. If you want a configured instance (thresholds, a feature name), keep configuration on self and have __call__ return a new object holding the request data. Configuration on self is fine. Writing to self during a request never is.

import asyncio
from typing import Annotated

from fastapi import Depends, FastAPI


class AuditTrail:
    def __init__(self, user_id: str) -> None:
        self.user_id = user_id


app = FastAPI()


@app.get("/orders")
async def list_orders(trail: Annotated[AuditTrail, Depends(AuditTrail)], user_id: str):
    await asyncio.sleep(0.05)
    return {"asked_by": user_id, "logged_as": trail.user_id}

Shared clients in the lifespan handler leak in the same way. A single httpx.AsyncClient for the whole app is right, because its connection pool is meant to be shared. Then someone sets client.headers["Authorization"] inside a dependency to call a downstream API as the current user, and concurrent requests start sending each other's tokens. Per-request values belong in the call, as client.get(url, headers=...), never on the shared object.

Leak two: lru_cache on anything that takes request input

The FastAPI settings docs recommend @lru_cache on get_settings(), and that's correct: the function takes no arguments and the settings never change. People then copy the decorator onto other dependencies to save a database call.

from functools import lru_cache
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.testclient import TestClient

REVOKED: set[str] = set()


@lru_cache
def get_current_user(authorization: Annotated[str, Header()]) -> dict:
    if authorization in REVOKED:
        raise HTTPException(status_code=401, detail="Token revoked")
    return {"token": authorization, "plan": "pro"}


app = FastAPI()


@app.get("/me")
def me(user: Annotated[dict, Depends(get_current_user)]):
    return user


with TestClient(app) as client:
    print(client.get("/me", headers={"authorization": "t1"}).status_code)  # 200
    REVOKED.add("t1")
    print(client.get("/me", headers={"authorization": "t1"}).status_code)  # still 200
    print(get_current_user.cache_info())  # hits=1, misses=1

FastAPI passes the header value as a plain string, so lru_cache works. That's the trouble. The revoked token keeps returning 200 because the second request never reaches the function body, and the cached dict is the same object for everyone holding that token. If a handler modifies it, the change shows up in every later request that hits the cache. Plan changes, role changes and deleted accounts all go unnoticed until the process restarts or the entry is evicted.

If a lookup really is too slow to run per request, use a cache with a TTL and an explicit invalidation path (Redis, or an in-process TTL cache keyed on something you can purge), and return a copy. Keep lru_cache for functions whose output depends only on deployment configuration.

Leak three: thread-locals and context variables in sync dependencies

FastAPI runs def dependencies and def routes in a thread pool, and those threads are reused. A threading.local set during one request is still there when the next request lands on that thread. Context variables fail the opposite way: a sync dependency runs in a copy of the request's context, so a ContextVar it sets is thrown away when it returns.

import threading
from contextvars import ContextVar
from typing import Annotated

from fastapi import Depends, FastAPI, Header
from fastapi.testclient import TestClient

_local = threading.local()
tenant_var: ContextVar[str | None] = ContextVar("tenant", default=None)


def set_tenant(x_tenant: Annotated[str | None, Header()] = None) -> None:
    if x_tenant is not None:
        _local.tenant = x_tenant
    tenant_var.set(x_tenant)


app = FastAPI()


@app.get("/whoami", dependencies=[Depends(set_tenant)])
def whoami():
    return {"thread_local": getattr(_local, "tenant", None), "contextvar": tenant_var.get()}


with TestClient(app) as client:
    print(client.get("/whoami", headers={"x-tenant": "acme"}).json())
    print(client.get("/whoami").json())  # no header, still sees "acme"

Both calls print {"thread_local": "acme", "contextvar": None}. The second request sent no tenant header and still got the first tenant from the thread-local. The context variable never reached the route at all, not even on the first request. Code written this way passes a single-request test and then serves the wrong tenant in production, with no predictable pattern, because it depends on which pool thread picks up the request.

The simplest fix is to stop using ambient state: return the tenant from the dependency and declare it as a parameter wherever you need it. If you need ambient context for logging or a library that reads it, set the ContextVar from an async def dependency. That runs in the request's own task context, which both async routes and sync routes (whose thread pool calls copy the context) can see, and a request that sends no header gets the default back. The contextvars documentation covers the copy semantics that make this work.

from contextvars import ContextVar
from typing import Annotated

from fastapi import Depends, FastAPI, Header

tenant_var: ContextVar[str | None] = ContextVar("tenant", default=None)


async def set_tenant(x_tenant: Annotated[str | None, Header()] = None) -> None:
    tenant_var.set(x_tenant)


app = FastAPI(dependencies=[Depends(set_tenant)])


@app.get("/report")
def report():
    return {"tenant": tenant_var.get()}

The per-request cache shares objects too

The sub-dependencies docs explain that when several dependencies in one request need the same sub-dependency, FastAPI calls it once and hands the same value to all of them. That's what you want for a database session: one session, one transaction. It's a leak inside a single request when the value is mutable and one consumer changes it.

from typing import Annotated

from fastapi import Depends, FastAPI


def get_filters() -> dict[str, str]:
    return {"status": "active"}


def admin_filters(f: Annotated[dict[str, str], Depends(get_filters)]) -> dict[str, str]:
    f.pop("status")  # admins see every status
    return f


def public_filters(
    f: Annotated[dict[str, str], Depends(get_filters, use_cache=False)],
) -> dict[str, str]:
    return f


app = FastAPI()


@app.get("/report")
def report(
    admin: Annotated[dict[str, str], Depends(admin_filters)],
    public: Annotated[dict[str, str], Depends(public_filters)],
):
    return {"admin": admin, "public": public}

With plain Depends(get_filters) in both places, the public filter comes back empty, because the admin dependency removed the key from the shared dict. use_cache=False makes FastAPI call get_filters again for that consumer, and the public side keeps {"status": "active"}. A better fix is not to mutate a dependency's return value at all, so copy it before changing it. Save use_cache=False for values that really must be computed fresh on every call.

When yield dependencies clean up

Resource lifetime is the other kind of scope bug: something gets closed too early, or held open too long. The cleanup timing has changed several times across releases, which is why so many older answers contradict each other. The current behaviour is documented on the dependencies with yield page. By default the code after yield runs after the response has been sent. Since 0.121.0 you can pass scope="function" to run it right after the path operation returns.

The default is what makes a StreamingResponse safe. With a fake session that records events, a streaming route reads open, chunk, chunk, chunk, close: the session stays open until the last chunk. Switch that dependency to scope="function" and the session is closed before the generator runs. The client gets a 200 with an empty or truncated body, and the server logs the exception from the first query inside the generator. That's the bug the 0.118.0 change fixed, and it's how you can bring it back.

So when is scope="function" right? When a dependency holds something scarce that the response itself doesn't need, such as a pooled database connection used only to load the current user before a slow stream starts, or a lock. Releasing it before the response is sent frees it for other requests sooner. Use it only after checking that nothing in the response body touches the resource.

Background tasks follow the default too. In our test a request-scoped session was still open when the task ran, and closed after the task finished. That works, but your connection is now held for the length of the task, and the task's work sits inside the request's transaction. The advanced dependencies page recommends passing IDs to the task and opening a new session inside it, and I'd follow that. For async SQLAlchemy, unclosed sessions and engines produce their own kind of leak; tracking down unclosed async sessions covers that side.

Testing for leaks

Every leak above passes a test that sends one request. The test that catches them sends many requests at once with different identities and checks each response against its own input. With httpx.ASGITransport it runs in-process, so it's fast enough for every CI run:

import asyncio

import httpx
import pytest

from main import app


@pytest.mark.anyio
async def test_concurrent_requests_do_not_share_state() -> None:
    transport = httpx.ASGITransport(app=app)
    async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
        responses = await asyncio.gather(
            *(client.get("/orders", params={"user_id": f"u{i}"}) for i in range(20))
        )

    for response in responses:
        body = response.json()
        assert body["logged_as"] == body["asked_by"]

Pointed at the callable-instance version of /orders, this fails; against the Depends(AuditTrail) version, it passes. The anyio marker comes from the pytest plugin that ships with AnyIO, which FastAPI already depends on. For thread-local bugs, use TestClient and send a request with the header followed by one without it, as in the example above. Two requests are enough because the pool reuses threads.

Tests can leak scope as well. app.dependency_overrides is a plain dict on the app object, so an override set in one test stays active for every test after it. The testing dependencies guide says to reset it, and a fixture makes that automatic:

from collections.abc import Iterator

import pytest
from fastapi.testclient import TestClient

from main import app


@pytest.fixture
def client() -> Iterator[TestClient]:
    with TestClient(app) as test_client:
        yield test_client
    app.dependency_overrides.clear()

A review checklist

Reviewing a FastAPI codebase for this class of bug comes down to a few greps, then reading every hit with one question in mind: which lifetime is this?

  • Depends( followed by a lowercase name that turns out to be an instance rather than a function or class. Check its __call__ for writes to self.
  • lru_cache and cache on anything other than settings loaders.
  • threading.local, and ContextVar.set inside def (not async def) dependencies.
  • Writes to attributes of objects stored on app.state or created in the lifespan, especially client headers and cookies.
  • Mutation of dependency return values.
  • scope="function" on dependencies whose resource is used by a streaming body.

If you're coming from Laravel, this is the same discipline Octane forces on singletons bound in the container, and the Octane shared-state trade-offs map almost one-to-one. The broader mapping between the two frameworks' request models is in FastAPI concepts for PHP developers.

WRITTEN BY

Full Stack Software Engineer | Laravel · Next.js · AWS

Full Stack Software Engineer with 7+ years of experience building scalable, secure web applications with Laravel, PHP, React, Next.js, and AWS for SaaS, CRM, telecom, and e-commerce companies. Specialized in cloud telephony (FreeSWITCH, SMPP, WebRTC): increased concurrent call capacity by 40% and cut report queries to under 500 ms. Author of open-source Laravel packages with 10K+ downloads on Packagist. Led a team of 4 engineers and shipped production systems for clients in the UAE, USA, India, Saudi Arabia, and Bangladesh.

How we research, write and check articles

    Latest Posts

    View All

    Next.js Middleware Authentication and Token Refresh Flows

    Next.js Middleware Authentication and Token Refresh Flows

    Livewire Performance Optimization Under High Load

    Livewire Performance Optimization Under High Load

    Configuring Nginx Upstream Keepalive for Node Backends

    Configuring Nginx Upstream Keepalive for Node Backends

    Enforcing Immutable State Patterns in React

    Enforcing Immutable State Patterns in React

    FastAPI Dependency Overrides for Integration Testing

    FastAPI Dependency Overrides for Integration Testing

    Stopping Layout Shifts in Next.js Dynamic Imports

    Stopping Layout Shifts in Next.js Dynamic Imports

    Optimizing Agentic Tool Calling Latency

    Optimizing Agentic Tool Calling Latency

    Fixing React Server Component Serialization Errors

    Fixing React Server Component Serialization Errors

    Next.js Route Handler Streaming with ReadableStream

    Next.js Route Handler Streaming with ReadableStream

    React Form Performance: Uncontrolled Inputs and FormData

    React Form Performance: Uncontrolled Inputs and FormData