How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
FastAPI · Python

Fix OperationalError: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) SSL connection has been closed unexpectedly in FastAPI

This error occurs when the database connection in the session pool becomes stale or is closed by the server, but SQLAlchemy tries to reuse it. Fix it by configuring pool_pre_ping=True on your engine so SQLAlchemy tests each connection before using it, and ensure you properly close sessions after each request with a dependency that uses a finally block.

Reading the Stack Trace

Traceback (most recent call last): File "/app/venv/lib/python3.11/site-packages/uvicorn/protocols/http/h11_impl.py", line 406, in run_asgi result = await app(scope, receive, send) File "/app/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1967, in _exec_single_context self._handle_dbapi_exception(e, statement, parameters, cursor, context) File "/app/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 2348, in _handle_dbapi_exception raise sqlalchemy_exception File "/app/venv/lib/python3.11/site-packages/sqlalchemy/engine/base.py", line 1924, in _exec_single_context self.dialect.do_execute(cursor, statement, parameters, context) File "/app/venv/lib/python3.11/site-packages/sqlalchemy/engine/default.py", line 736, in do_execute cursor.execute(statement, parameters) File "/app/src/routes/users.py", line 15, in list_users users = db.query(User).all() sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) SSL connection has been closed unexpectedly

Here's what each line means:

Common Causes

1. Stale connections in the pool

The database server closed idle connections, but SQLAlchemy's pool still holds references to them and tries to reuse them.

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

2. Session not properly closed after request

The database session dependency does not use a try/finally block, so sessions leak when exceptions occur mid-request.

def get_db():
    db = SessionLocal()
    yield db
    db.close()  # Never reached if an exception is raised

3. Global session shared across requests

A single session is created at module level and shared across all requests, leading to connection state corruption.

db = SessionLocal()  # Global session, shared across all requests

@app.get("/users")
def list_users():
    return db.query(User).all()

The Fix

Enable pool_pre_ping=True so SQLAlchemy tests each connection with a lightweight ping before using it, automatically discarding stale connections. Set pool_recycle to proactively replace connections before the database server's idle timeout. Wrap the yield in try/finally to ensure sessions are always closed.

Before (broken)
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)

def get_db():
    db = SessionLocal()
    yield db
    db.close()
After (fixed)
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(
    DATABASE_URL,
    pool_pre_ping=True,
    pool_size=5,
    max_overflow=10,
    pool_recycle=300,
)
SessionLocal = sessionmaker(bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

Testing the Fix

import pytest
from unittest.mock import patch, MagicMock
from fastapi.testclient import TestClient
from app.main import app
from app.database import get_db


def test_db_session_closes_on_success():
    mock_session = MagicMock()

    def override_get_db():
        try:
            yield mock_session
        finally:
            mock_session.close()

    app.dependency_overrides[get_db] = override_get_db
    client = TestClient(app)
    response = client.get("/users")
    mock_session.close.assert_called_once()
    app.dependency_overrides.clear()


def test_db_session_closes_on_error():
    mock_session = MagicMock()
    mock_session.query.side_effect = Exception("DB error")

    def override_get_db():
        try:
            yield mock_session
        finally:
            mock_session.close()

    app.dependency_overrides[get_db] = override_get_db
    client = TestClient(app)
    response = client.get("/users")
    assert response.status_code == 500
    mock_session.close.assert_called_once()
    app.dependency_overrides.clear()


def test_list_users_returns_data():
    client = TestClient(app)
    response = client.get("/users")
    assert response.status_code == 200

Run your tests:

pytest tests/test_database.py -v

Pushing Through CI/CD

git checkout -b fix/fastapi-database-session,git add src/database.py tests/test_database.py,git commit -m "fix: add pool_pre_ping and proper session cleanup",git push origin fix/fastapi-database-session

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_DB: testdb
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'
      - run: pip install -r requirements.txt
      - run: pytest --tb=short -q
        env:
          DATABASE_URL: postgresql://postgres:postgres@localhost:5432/testdb

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

pip install bugstack

Step 2: Initialize

import bugstack

bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the test suite locally to confirm database sessions are properly managed.
  2. Open a pull request with the pool configuration and session cleanup fix.
  3. Wait for CI checks including database integration tests to pass.
  4. Have a teammate review and approve the PR.
  5. Merge to main and monitor database connection pool metrics in staging.

Frequently Asked Questions

BugStack validates the connection pool configuration, simulates stale connection scenarios, runs your test suite, and confirms sessions are properly closed after both successful and failed requests.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review the database configuration before merging.

Database servers close idle connections after a timeout. The error only appears when SQLAlchemy picks a stale connection from the pool, which depends on traffic patterns and idle time.

It adds one lightweight query (SELECT 1) per connection checkout. The overhead is negligible compared to the cost of a failed request from a dead connection.