fix: use try/finally in get_db to prevent PostgreSQL connection leaks#1
fix: use try/finally in get_db to prevent PostgreSQL connection leaks#1Vacbo wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Pull request overview
This PR updates the FastAPI DB-session dependency (get_db) to guarantee SQLModel Session cleanup by explicitly closing the session in a finally block, reducing the risk of PostgreSQL connections being held longer than intended under exception-heavy / high-concurrency request patterns.
Changes:
- Replaced
with Session(engine) as session: yield sessionwith an explicittry/finallyaroundyield. - Ensures
session.close()is always executed when the dependency scope ends (success or exception).
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| session = Session(engine) | ||
| try: | ||
| yield session | ||
| finally: | ||
| session.close() |
There was a problem hiding this comment.
📝 Info: Functional equivalence of context manager vs try/finally for Session
The old code used with Session(engine) as session: yield session, which relies on Session.__enter__ (returns self) and Session.__exit__ (calls self.close()). The new code manually creates the session, yields it, and calls session.close() in a finally block. These are functionally equivalent because SQLAlchemy's Session.__exit__ does nothing beyond calling close() — it does not auto-commit or auto-rollback based on exception status (unlike Session.begin() which does). However, the with statement pattern is more idiomatic and slightly more concise. The refactor doesn't appear to have a clear motivation — both patterns behave identically for this use case.
Was this helpful? React with 👍 or 👎 to provide feedback.
Code Review SummaryStatus: No Issues Found | Recommendation: Merge OverviewThis is a well-executed fix for a critical PostgreSQL connection leak issue. The change from context manager ( Why this fix works:
Safety considerations verified:
Files Reviewed (1 file)
Reviewed by laguna-m.1-20260312:free · 909,506 tokens |
Problem
The current
get_db()implementation useswith Session(engine) as session: yield session. Under high load with concurrent requests that raise exceptions, this pattern causes PostgreSQL connections to leak into anidle in transactionstate, eventually exhausting the connection pool and resulting in:This happens because:
yieldpauses execution in the route handlerwithcontext manager's cleanup depends on garbage collection timingidle in transactionstateRoot Cause
The
with Session(engine) as sessioncontext manager relies on__exit__being called when control flow exits thewithblock. However, with generator-based dependency injection:When the route handler raises an exception after
yield, the__exit__cleanup is deferred until Python's garbage collector runs. Under load, this deferral causes connections to accumulate faster than they can be cleaned up.Verification
Load testing with bombardier (300 concurrent connections, 30 seconds):
with Session(engine) as session: yield session/error(raises)with Session(engine) as session: yield session/ok(success)try/finally+session.close()/error(raises)try/finally+session.close()/ok(success)Solution
The
try/finallypattern ensuressession.close()is always called immediately when the generator finishes, regardless of whether the route raised an exception. This guarantees connections are returned to the pool promptly.Example Routes Used in Testing
Load Test Command
I used bombardier to make a simple load test and reproduce the scenario:
Post-Test Connection Inspection
idle_in_transaction > 0: Connection leak - sessions not properly closedidle_in_transaction = 0: All connections properly returned to pool ✅Additional Context
This issue was reproduced consistently with
pool_size=2, max_overflow=10. With smaller pools or higher concurrency, thetoo many clients alreadyerror appears faster. Thetry/finallypattern eliminates the leak entirely.Recreated from upstream fastapi/full-stack-fastapi-template#2320 by @andersou, for a MAS-Ops Pipeline 2 (PR review) demonstration.
Note
Medium Risk
Touches shared DB dependency injection used by all API routes; behavior is a safer lifecycle fix with no API contract change, but mis-handling could still affect every request.
Overview
Replaces the
with Session(engine)pattern inget_dbwith an explicittry/finallythat always callssession.close()after the dependency generator finishes.Under concurrent load—especially when route handlers raise—deferred context-manager cleanup was leaving PostgreSQL sessions in
idle in transactionand exhausting the pool. This change guarantees the SQLModel session is closed as soon as FastAPI tears down the dependency, for every route that usesSessionDep.Reviewed by Cursor Bugbot for commit 02a36a9. Bugbot is set up for automated code reviews on this repo. Configure here.
Summary by cubic
Prevented PostgreSQL connection leaks by switching
get_db()to a try/finally pattern that always closes sessions. This avoids idle-in-transaction buildup and “too many clients” errors under exceptions and high load.with Session(engine): yield sessionwithsession = Session(engine); try: yield session; finally: session.close().Written for commit 02a36a9. Summary will update on new commits.