Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4791 pages
Databases and Redis

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 show

Fix it fast

Most common cause, 1 of 3

The 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.

Fix
from sqlalchemy import create_engine

engine = create_engine(
    "postgresql://app:secret@db/app",
    pool_pre_ping=True,
    pool_recycle=3600,
)
Did this fix it?
Full steps for this cause: check, fix, verify

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).

  • Applies to SQLAlchemy 2.1.9, FastAPI 0.165.0, PostgreSQL and MySQL drivers
  • Updated
  • By Maaz Zindani, Senior Software Engineer

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.

Run this first
grep -rnE "SessionLocal\(\)|Session\(engine\)|sessionmaker\(" --include=*.py .

Then find the line you see in this list and open its fix:

  1. 1The database dropped the connection while a transaction was openAn OperationalError or InterfaceError from the driver appears just before the first 8s2b error, often after idle time or a database restart
  2. 2One Session object is shared by every requestThe grep finds db = SessionLocal() at module level, and after the first failure every request keeps failing until the process restarts
  3. 3An exception was caught but the Session was never rolled back8s2b 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 proceeding
  • Can'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.

Check
grep -nE "OperationalError|InterfaceError|8s2b" app.log | head -20

Fix

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.

Fix
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.

Verify
curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8000/items/1

Confirmed by docs.sqlalchemy.org

Did this fix it?

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.

Check
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.

Fix
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.

Verify
grep -rnE "^[a-z_]+ *= *SessionLocal\(\)" --include=*.py . || echo 'no shared session left'

Confirmed by docs.sqlalchemy.org

Did this fix it?

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.

Check
grep -rn -A3 "except" --include=*.py app/ | grep -v rollback

Fix

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.

Fix
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.

Verify
grep -c 8s2b app.log

Confirmed by docs.sqlalchemy.org

Did this fix it?

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.

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.