fix: use try/finally in get_db to prevent PostgreSQL connection leaks#2320
Open
andersou wants to merge 1 commit into
Open
fix: use try/finally in get_db to prevent PostgreSQL connection leaks#2320andersou wants to merge 1 commit into
andersou wants to merge 1 commit into
Conversation
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.