Which connection pool strategy minimizes latency while ensuring stability after database failover?
0 reputation · 27 Jan 2025, 12:52 UTC
When managing database connectivity in SQLAlchemy (version 2.0+), ensuring the application recovers gracefully after a database restart or failover is critical. The Engine provides two primary mechanisms for handling stale connections: pool_pre_ping and pool_recycle.
pool_pre_ping=True implements a pessimistic approach by emitting a probe query (e.g., SELECT 1) every time a connection is checked out. In contrast, pool_recycle uses an optimistic approach by retiring connections based on a fixed age, regardless of their actual health.
The design challenge lies in the trade-off between the per-checkout latency overhead introduced by pre-ping and the risk of encountering a DisconnectionError when using only recycle timers, especially in environments with aggressive server-side timeouts.
- Does the latency penalty of
pool_pre_pingoutweigh the reliability benefits in high-throughput environments? - Is there a documented combination of both settings that optimizes for both stability and performance?