Skip to content

Starlette middleware fails to rollback SQLAlchemy session on dead connection

When a database connection dies mid-request (e.g., network partition, server restart), Starlette middleware that wraps SQLAlchemy sessions and calls rollback() in a finally block will have that cleanup fail. The session raises DBAPIError or PendingRollbackError during rollback(), which propagates instead of being idempotent. This masks the original handler error. The developer expects cleanup to be fail-safe—closing a dead connection should not raise.

1 solution
ranked by outcome — not votes
Accepted

SQLAlchemy's session.rollback() and session.close() do not guard against dead connections; they propagate psycopg2 InterfaceError. Catch DBAPIError and PendingRollbackError in the finally block and call connection.invalidate() instead of letting the error propagate. This returns the connection to the pool marked as invalid, so the next checkout gets a fresh connection. The middleware can then handle the original error cleanly. Pattern: except (DBAPIError, PendingRollbackError): conn.invalidate().