Jump to solution
Verify

The Fix

pip install fastapi==0.118.0

Based on closed fastapi/fastapi issue #11143 · PR/commit linked

Production note: Watch p95/p99 latency and retry volume; timeouts can turn into retry storms and duplicate side-effects.

Jump to Verify Open PR/Commit
@@ -63,3 +63,91 @@ In the chapters about security, there are utility functions that are implemented /// + +## Dependencies with `yield`, `HTTPException`, `except` and Background Tasks { #dependencies-with-yield-httpexception-except-and-background-tasks } +
repro.py
from fastapi import Depends, FastAPI, Request app = FastAPI() class Session: def __init__(self): print("creating session") async def __aenter__(self): print("opening session") return self async def __aexit__(self, exc_type, exc, tb): print("closing session") async def commit(self): print("committing session") async def rollback(self): print("rolling back session") @app.middleware("http") async def commit_session(request: Request, call_next): # minimalistic middleware for example, my code uses ASGI middleware response = await call_next(request) db_session = request.scope.get("db_session") if not db_session: return response if response.status_code // 200 != 1: await db_session.rollback() else: await db_session.commit() return response async def get_db_session(request: Request): async with Session() as session: request.scope["db_session"] = session yield session @app.get("/") async def root(session: Session = Depends(get_db_session)): return {"message": "Hello World"} # Pre 0.106 behaviour: # creating session # opening session # committing session # closing session # Post 0.106 behaviour: # creating session # opening session # closing session # committing session # The session is not committed, because it's closed before the middleware is called.
verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
fix.md
Option A — Upgrade to fixed release\npip install fastapi==0.118.0\nWhen NOT to use: This fix should not be used if the application relies on the previous behavior of early resource closure.\n\nOption C — Workaround\nfor now is to use our connection pool directly in each endpoint doing streaming. Annoying, but works.\nWhen NOT to use: This fix should not be used if the application relies on the previous behavior of early resource closure.\n\n

Why This Fix Works in Production

  • Trigger: Context managers in `Depends` are broken after 0.106
  • Mechanism: The behavior of context managers in Depends changed, causing premature closure of resources
  • Why the fix works: Fix support for `StreamingResponse`s with dependencies with `yield` or `UploadFile`s, ensuring proper closure after the response is done. (first fixed release: 0.118.0).
Production impact:
  • If left unfixed, tail latency can spike under load and surface as timeouts/retries (amplifying incident impact).

Why This Breaks in Prod

  • Shows up under Python 3.12 in real deployments (not just unit tests).
  • The behavior of context managers in Depends changed, causing premature closure of resources
  • Surfaces as: Traceback (most recent call last):\n File "starlette/responses.py", line 264, in wrap\n await func()\n File "starlette/responses.py", line 245, in stream_response\n async for…

Proof / Evidence

Verified Execution

We executed the runnable minimal repro in a temporary environment and captured exit codes + logs.

  • Status: PASS
  • Ran: 2026-02-11T16:52:29Z
  • Package: fastapi
  • Fixed: 0.118.0
  • Mode: fixed_only
  • Outcome: ok
Logs
affected (exit=None)
fixed (exit=0)

Discussion

High-signal excerpts from the issue thread (symptoms, repros, edge-cases).

“> I think Depends should accept a flag where you can specify when the dependency should be closed, before or after the response”
@RamiAwar · 2024-08-07 · confirmation · source
“I think Depends should accept a flag where you can specify when the dependency should be closed, before or after the response”
@truh · 2024-08-06 · confirmation · source
“Support for StreamingResponses using dependencies with yield should be fixed by this: https://github.com/fastapi/fastapi/pull/14099 (once it's merged and released). 🚀”
@tiangolo · 2025-09-21 · confirmation · source
“FastAPI 0.118.0 was just released with the fix in https://github.com/fastapi/fastapi/pull/14099. 🐛 🚀 🎉”
@tiangolo · 2025-09-29 · confirmation · source

Failure Signature (Search String)

  • Context managers in `Depends` are broken after 0.106

Error Message

Stack trace
error.txt
Error Message ------------- Traceback (most recent call last):\n File "starlette/responses.py", line 264, in wrap\n await func()\n File "starlette/responses.py", line 245, in stream_response\n async for chunk in self.body_iterator:\n File "test.py", line 27, in _stream\n await cursor.execute("SELECT 42")\n File "psycopg/cursor_async.py", line 97, in execute\n raise ex.with_traceback(None)

Minimal Reproduction

repro.py
from fastapi import Depends, FastAPI, Request app = FastAPI() class Session: def __init__(self): print("creating session") async def __aenter__(self): print("opening session") return self async def __aexit__(self, exc_type, exc, tb): print("closing session") async def commit(self): print("committing session") async def rollback(self): print("rolling back session") @app.middleware("http") async def commit_session(request: Request, call_next): # minimalistic middleware for example, my code uses ASGI middleware response = await call_next(request) db_session = request.scope.get("db_session") if not db_session: return response if response.status_code // 200 != 1: await db_session.rollback() else: await db_session.commit() return response async def get_db_session(request: Request): async with Session() as session: request.scope["db_session"] = session yield session @app.get("/") async def root(session: Session = Depends(get_db_session)): return {"message": "Hello World"} # Pre 0.106 behaviour: # creating session # opening session # committing session # closing session # Post 0.106 behaviour: # creating session # opening session # closing session # committing session # The session is not committed, because it's closed before the middleware is called.

Environment

  • Python: 3.12

What Broke

Streaming responses fail to access necessary resources due to early closure of dependencies.

Why It Broke

The behavior of context managers in Depends changed, causing premature closure of resources

Fix Options (Details)

Option A — Upgrade to fixed release Safe default (recommended)

pip install fastapi==0.118.0

When NOT to use: This fix should not be used if the application relies on the previous behavior of early resource closure.

Use when you can deploy the upstream fix. It is usually lower-risk than long-lived workarounds.

Option C — Workaround Temporary workaround

for now is to use our connection pool directly in each endpoint doing streaming. Annoying, but works.

When NOT to use: This fix should not be used if the application relies on the previous behavior of early resource closure.

Use only if you cannot change versions today. Treat this as a stopgap and remove once upgraded.

Fix reference: https://github.com/fastapi/fastapi/pull/14099

First fixed release: 0.118.0

Last verified: 2026-02-08. Validate in your environment.

Get updates

We publish verified fixes weekly. No spam.

Subscribe

When NOT to Use This Fix

  • This fix should not be used if the application relies on the previous behavior of early resource closure.

Verify Fix

verify
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.

Did This Fix Work in Your Case?

Quick signal helps us prioritize which fixes to verify and improve.

Prevention

  • Capture the exact failing error string in logs and tests so you can reproduce via a minimal script.
  • Pin production dependencies and upgrade only with a reproducible test that hits the failing path.

Version Compatibility Table

VersionStatus
0.118.0 Fixed

Related Issues

No related fixes found.

Sources

We don’t republish the full GitHub discussion text. Use the links above for context.