fix: use try/finally in get_db to prevent PostgreSQL connection leaks#3
Closed
Vacbo wants to merge 1 commit into
Closed
fix: use try/finally in get_db to prevent PostgreSQL connection leaks#3Vacbo wants to merge 1 commit into
Vacbo wants to merge 1 commit into
Conversation
There was a problem hiding this comment.
Pull request overview
Updates the FastAPI DB-session dependency to ensure the SQLModel Session is always closed via an explicit try/finally, aiming to prevent pooled PostgreSQL connections from remaining checked out under exceptional request flows.
Changes:
- Replaced the
with Session(engine) as session: yield sessionpattern withsession = Session(engine)+try: yield+finally: session.close()in theget_db()dependency.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
Summary by cubic
Prevents PostgreSQL connection leaks by changing
get_dbto a try/finally pattern that always closes the session. Stopsidle in transactionbuildup and pool exhaustion under load.with Session(engine) as session: yield sessionwithsession = Session(engine)andfinally: session.close()to ensure cleanup on success and errors.Written for commit 02a36a9. Summary will update on new commits.