Jump to solution
Verify

The Fix

Upgrade to version 0.13.4 or later.

Based on closed Kludex/starlette issue #370 · PR/commit linked

Jump to Verify Open PR/Commit
@@ -1,4 +1,5 @@ @@ -1,4 +1,5 @@ *.pyc +test.db .coverage .pytest_cache/
repro.py
from fastapi import FastAPI from sqlalchemy import Boolean, Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy.orm import sessionmaker from starlette.requests import Request # SQLAlchemy specific code, as with any other app SQLALCHEMY_DATABASE_URI = "sqlite:///./test.db" # SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db" engine = create_engine( SQLALCHEMY_DATABASE_URI, connect_args={"check_same_thread": False} ) Session = sessionmaker(autocommit=False, autoflush=False, bind=engine) class CustomBase: # Generate __tablename__ automatically @declared_attr def __tablename__(cls): return cls.__name__.lower() Base = declarative_base(cls=CustomBase) class User(Base): id = Column(Integer, primary_key=True, index=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean(), default=True) Base.metadata.create_all(bind=engine) db_session = Session() first_user = db_session.query(User).first() if not first_user: u = User(email="[email protected]", hashed_password="notreallyhashed") db_session.add(u) db_session.commit() db_session.close() # Utility def get_user(db_session, user_id: int): return db_session.query(User).filter(User.id == user_id).first() # FastAPI specific code app = FastAPI() @app.get("/users/{user_id}") def read_user(request: Request, user_id: int): user = get_user(request._scope["db"], user_id=user_id) return user @app.middleware("http") async def close_db(request, call_next): request._scope["db"] = Session() response = await call_next(request) request._scope["db"].close() return response
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\nUpgrade to version 0.13.4 or later.\nWhen NOT to use: This fix is not suitable if the application relies on the built-in DatabaseMiddleware.\n\n

Why This Fix Works in Production

  • Trigger: * Change the interfaces so that `fetchone` and `fetchall` return Record instances.
  • Mechanism: The built-in DatabaseMiddleware is pending deprecation in favor of the standalone databases package
  • Why the fix works: Moves to recommending the stand-alone package 'databases' instead of the built-in 'DatabaseMiddleware'. (first fixed release: 0.13.4).

Why This Breaks in Prod

  • The built-in DatabaseMiddleware is pending deprecation in favor of the standalone databases package
  • Production symptom (often without a traceback): * Change the interfaces so that `fetchone` and `fetchall` return Record instances.

Proof / Evidence

  • GitHub issue: #370
  • Fix PR: https://github.com/encode/starlette/pull/390
  • First fixed release: 0.13.4
  • Reproduced locally: No (not executed)
  • Last verified: 2026-02-09
  • Confidence: 0.85
  • Did this fix it?: Yes (upstream fix exists)
  • Own content ratio: 0.45

Discussion

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

“Closing this off now, in favor of http://github.com/encode/databases”
@lovelydinosaur · 2019-02-14 · confirmation · source
“Oh - one other caveat”
@lovelydinosaur · 2019-02-14 · source
“Awesome, thanks. I hope to add a PR with a simple example using SQLAlchemy models to the docs here, after request.state is there... unless I…”
@tiangolo · 2019-02-14 · source
“Probably let’s not over complicate things. request.state.db is good enough to get started with.”
@lovelydinosaur · 2019-02-14 · source

Failure Signature (Search String)

  • * Change the interfaces so that `fetchone` and `fetchall` return Record instances.
Copy-friendly signature
signature.txt
Failure Signature ----------------- * Change the interfaces so that `fetchone` and `fetchall` return Record instances.

Error Message

Signature-only (no traceback captured)
error.txt
Error Message ------------- * Change the interfaces so that `fetchone` and `fetchall` return Record instances.

Minimal Reproduction

repro.py
from fastapi import FastAPI from sqlalchemy import Boolean, Column, Integer, String, create_engine from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy.orm import sessionmaker from starlette.requests import Request # SQLAlchemy specific code, as with any other app SQLALCHEMY_DATABASE_URI = "sqlite:///./test.db" # SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db" engine = create_engine( SQLALCHEMY_DATABASE_URI, connect_args={"check_same_thread": False} ) Session = sessionmaker(autocommit=False, autoflush=False, bind=engine) class CustomBase: # Generate __tablename__ automatically @declared_attr def __tablename__(cls): return cls.__name__.lower() Base = declarative_base(cls=CustomBase) class User(Base): id = Column(Integer, primary_key=True, index=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) is_active = Column(Boolean(), default=True) Base.metadata.create_all(bind=engine) db_session = Session() first_user = db_session.query(User).first() if not first_user: u = User(email="[email protected]", hashed_password="notreallyhashed") db_session.add(u) db_session.commit() db_session.close() # Utility def get_user(db_session, user_id: int): return db_session.query(User).filter(User.id == user_id).first() # FastAPI specific code app = FastAPI() @app.get("/users/{user_id}") def read_user(request: Request, user_id: int): user = get_user(request._scope["db"], user_id=user_id) return user @app.middleware("http") async def close_db(request, call_next): request._scope["db"] = Session() response = await call_next(request) request._scope["db"].close() return response

What Broke

Users may experience issues with database connection management and middleware functionality.

Why It Broke

The built-in DatabaseMiddleware is pending deprecation in favor of the standalone databases package

Fix Options (Details)

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

Upgrade to version 0.13.4 or later.

When NOT to use: This fix is not suitable if the application relies on the built-in DatabaseMiddleware.

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

Fix reference: https://github.com/encode/starlette/pull/390

First fixed release: 0.13.4

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

Get updates

We publish verified fixes weekly. No spam.

Subscribe

When NOT to Use This Fix

  • This fix is not suitable if the application relies on the built-in DatabaseMiddleware.

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.13.4 Fixed

Related Issues

No related fixes found.

Sources

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