SQLAlchemy connection pool: pool_recycle vs pool_pre_ping for stale connections
0 reputation · 02 Dec 2021, 15:36 UTC
0 reputation · 02 Dec 2021, 15:36 UTC
When managing database connections in SQLAlchemy (version 1.4 or 2.0), ensuring that the engine does not attempt to use a stale or closed connection is critical for deployment stability. Two primary mechanisms exist for handling connection longevity: pool_recycle and pool_pre_ping.
The pool_recycle parameter closes and replaces connections that have reached a specific age, which helps prevent timeouts imposed by the database server. Conversely, pool_pre_ping performs a lightweight test (such as SELECT 1) upon every connection checkout to verify viability before the application attempts a real query.
Relying solely on a timer-based recycle may still result in OperationalError exceptions if the server closes the connection unexpectedly before the recycle threshold is met. However, enabling pre-ping introduces a small amount of overhead for every checkout operation.
pool_pre_ping render pool_recycle redundant for most client-server database deployments?34775 reputation · 02 Dec 2021, 21:16 UTC
No – enabling pool_pre_ping does not make pool_recycle redundant in every deployment. It eliminates most stale‑connection errors at checkout, but a timer‑based recycle is still useful when the database forces connections to close after a short idle period that is shorter than the typical time between checkouts.
pool_pre_ping runs a lightweight validation query (e.g., SELECT 1) on every connection checkout and raises no error if the query succeeds.pool_recycle discards and recreates any connection that has lived longer than the configured number of seconds, regardless of its current state.wait_timeout) that is shorter than the application’s typical checkout interval, pool_recycle guarantees the connection is refreshed before the server‑side limit is reached.pool_recycle with a suitably tuned interval can avoid the per‑checkout overhead of pool_pre_ping.The pre‑ping mechanism catches connections that have already been closed by the server, but it cannot prevent the server from closing a connection while it is idle in the pool. A recycle timer proactively replaces aging connections, reducing the chance that a pre‑ping will fail and thus lowering the frequency of costly reconnects.
from sqlalchemy import create_engine
engine = create_engine(
"postgresql+psycopg2://user:pwd@host/dbname",
pool_pre_ping=True, # validate on checkout
pool_recycle=300, # recycle connections older than 5 min
pool_size=10,
max_overflow=20
)
Adjust pool_recycle to be somewhat lower than the database’s idle timeout (e.g., if wait_timeout=600 seconds, set pool_recycle=500).
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.