SQLAlchemy refuses to reconnect in FastAPI until you roll back
Your error
sqlalchemy.exc.PendingRollbackError: Can't reconnect until invalid transaction is rolled back. Please rollback() fully before proceeding1 more line it can showFix it fast
Most common cause, 1 of 3The database dropped the connection while a transaction was open
Test each pooled connection before it is handed out, and retire old ones before the server's own idle limit closes them.
from sqlalchemy import create_engine
engine = create_engine(
"postgresql://app:secret@db/app",
pool_pre_ping=True,
pool_recycle=3600,
)Short answer
PendingRollbackError "Can't reconnect until invalid transaction is rolled back" (code 8s2b) means the database connection died while a Session still had a transaction open. SQLAlchemy will not swap in a new connection until that transaction is rolled back. In FastAPI, give each request its own Session, call rollback() on errors, and set pool_pre_ping=True (SQLAlchemy 2.1).
Which cause do you have?
Find every place a Session is created. A Session built at module level (no indent, outside any function) is shared by all requests, which is cause 2. If sessions are created per request, read the log just before the first 8s2b line: a driver disconnect error there points to cause 1, and an exception your code caught points to cause 3.
grep -rnE "SessionLocal\(\)|Session\(engine\)|sessionmaker\(" --include=*.py .Then find the line you see in this list and open its fix:
- 1The database dropped the connection while a transaction was open
An OperationalError or InterfaceError from the driver appears just before the first 8s2b error, often after idle time or a database restart - 2One Session object is shared by every request
The grep finds db = SessionLocal() at module level, and after the first failure every request keeps failing until the process restarts - 3An exception was caught but the Session was never rolled back
8s2b shows up in the same request, right after a try/except around a query or commit that logged the error and carried on
What does the error look like?
sqlalchemy.exc.PendingRollbackError: Can't reconnect until invalid transaction is rolled back. Please rollback() fully before proceedingCan't reconnect until invalid savepoint transaction is rolled back. Please rollback() fully before proceeding
Cause 1 of 3
The database dropped the connection while a transaction was open
You seeAn OperationalError or InterfaceError from the driver appears just before the first 8s2b error, often after idle time or a database restart
Check
SQLAlchemy raises 8s2b when a Connection was invalidated, by disconnect detection or an explicit invalidate() call, while a transaction it began was still in progress. In 2.x a transaction starts automatically with the first statement, so almost any request can be holding one when the server goes away.
grep -nE "OperationalError|InterfaceError|8s2b" app.log | head -20Fix
Test each pooled connection before it is handed out, and retire old ones before the server's own idle limit closes them. Pre-ping cannot rescue a transaction that was cut off midway, so the request that hit the drop still has to roll back and can be retried.
from sqlalchemy import create_engine
engine = create_engine(
"postgresql://app:secret@db/app",
pool_pre_ping=True,
pool_recycle=3600,
)Verify
Restart the database while the API is idle, then send a request. It succeeds on a fresh connection instead of raising 8s2b.
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8000/items/1Confirmed by docs.sqlalchemy.org
Cause 2 of 3
One Session object is shared by every request
You seeThe grep finds db = SessionLocal() at module level, and after the first failure every request keeps failing until the process restarts
Check
A shared Session carries the broken transaction from one request into the next, so a single disconnect turns into an endless run of 8s2b errors. SQLAlchemy's session guide says a web app should open a Session at the start of each request and close it at the end, and that one Session must not be used by several threads or tasks at once.
grep -rnE "^[a-z_]+ *= *SessionLocal\(\)" --include=*.py .Fix
Delete the global session and hand out a new one per request through a dependency with yield. FastAPI's SQL tutorial uses this pattern, and the with block closes the Session when the response is done.
from typing import Annotated
from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session
def get_session():
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int, session: SessionDep):
return session.get(Item, item_id)Verify
Force one request to fail, then call another endpoint. The second request works because it got its own Session.
grep -rnE "^[a-z_]+ *= *SessionLocal\(\)" --include=*.py . || echo 'no shared session left'Confirmed by docs.sqlalchemy.org
Cause 3 of 3
An exception was caught but the Session was never rolled back
You see8s2b shows up in the same request, right after a try/except around a query or commit that logged the error and carried on
Check
Once its connection is invalidated, the transaction stays in an invalid state until you call rollback() explicitly, as the 8s2b entry in SQLAlchemy's error guide explains. Code that swallows the first exception and keeps using the Session meets PendingRollbackError on the next statement.
grep -rn -A3 "except" --include=*.py app/ | grep -v rollbackFix
Roll back inside the dependency before the Session closes, then raise the exception again. FastAPI's guide on dependencies with yield warns that an except block that does not re-raise hides the error from the framework.
def get_session():
session = Session(engine)
try:
yield session
except Exception:
session.rollback()
raise
finally:
session.close()Verify
The failing request returns its own error once, and the next statement on a new request runs without PendingRollbackError.
grep -c 8s2b app.logConfirmed by docs.sqlalchemy.org
How do I stop it coming back?
- Set pool_pre_ping=True and a pool_recycle shorter than the idle timeout of the database, proxy or load balancer on every engine you create.
- Create sessions only inside a FastAPI dependency; add a lint or review check that rejects SessionLocal() at module level.
- Wrap write paths in with session.begin(): so commit and rollback happen at one clear boundary instead of in scattered try blocks.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine on the same stack: TaxiDex, QistLock, ShopGo.