# sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) server closed the connection unexpectedly

- **ID:** `python/sqlalchemy-session-closed-connection`
- **Domain:** python
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

The database connection was closed by the server, often due to a timeout or network issue, and the session is still using the stale connection.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **Recreate the session using a fresh engine connection** (95% success)
   ```
   from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://user:pass@localhost/db', pool_pre_ping=True)
Session = sessionmaker(bind=engine)
session = Session()
# Use session for queries
   ```
2. **Enable pool_pre_ping to check connection health** (90% success)
   ```
   engine = create_engine('postgresql://user:pass@localhost/db', pool_pre_ping=True)
   ```

## Dead Ends

- **Restarting the database server** — Restarting the server does not fix the underlying issue of connection pooling or timeout settings. (75% fail)
- **Using session.commit() to retry** — Commit does not reset the connection; it only flushes pending changes. (85% fail)
