asyncpg icon indicating copy to clipboard operation
asyncpg copied to clipboard

Pool: prevent trimming the last idle connection under load

Open mamfyou opened this issue 4 months ago • 0 comments

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.

mamfyou avatar Aug 18 '25 16:08 mamfyou