Pool: prevent trimming the last idle connection under load #1271
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.
Related To #1268
Under heavy load, or when max_inactive_connection_lifetime exceeds the pool’s configured connection lifetime (like after inactivity for few minutes when lifetime is set to 300),
the inactivity timer may deactivate idle connections too aggressively.
In rare cases this leaves the pool empty, forcing new connections to be created just as clients are waiting. Since connection setup is expensive, this can result in extra overhead and even TimeoutErrors when acquiring a connection.
This change adds a guard to PoolConnectionHolder._deactivate_inactive_connection so that idle deactivation only happens when it is safe:
1- never below min_size
2- never if there are waiters in the pool queue
3- never removing the last idle connection
With these rules, the pool always keeps at least one ready connection, avoiding spurious churn and reducing the risk of TimeoutErrors under load.
The implementation only uses existing private fields (_holders, _queue, _minsize, etc.), so it doesn’t introduce new API surface.
This makes the pool’s behavior more predictable under load without changing existing configuration knobs.