SQLAlchemy Core Engine and ORM Session: Pool Recycle Behavior with Non-Thread-Safe Drivers
0 reputation · 06 Mar 2023, 01:06 UTC
0 reputation · 06 Mar 2023, 01:06 UTC
When using SQLAlchemy 2.x with a non-thread-safe DBAPI driver such as psycopg2, the Core Engine and ORM Session share the same QueuePool instance. The documented pool_recycle parameter defaults to 0, which disables automatic recycling and allows connections to persist beyond the database server's idle timeout. This creates an interoperability boundary where both layers may acquire stale sockets that the database has already closed, leading to intermittent exhaustion symptoms that appear in application logs before the pool itself reports saturation.
The future=True flag changes pool acquisition semantics, yet the migration guidance does not clarify whether enabling it resolves the stale-connection retention issue or merely shifts the failure mode. Driver-specific thread-local state handling further complicates the picture: psycopg2 connections are not safe for concurrent use across threads, but the pool's thread-local checkout mechanism is shared between Core and ORM pathways. External monitoring (e.g., pg_stat_activity) often shows exhausted database sockets while the pool still reports available capacity, making root-cause attribution difficult without invasive debugging.
Assuming SQLAlchemy 2.0+ and a PostgreSQL backend with default pool settings, the following questions remain unresolved:
future=True alter the pool's idle-connection validation logic enough to prevent recycled sockets from being handed to either Core or ORM callers?pool_recycle value when the database enforces a 30-minute idle timeout, and does that value need to differ between Core-only and mixed Core/ORM workloads?pool_pre_ping be relied upon to detect server-side closure for both engine.connect() and Session checkouts without introducing unacceptable latency under burst traffic?37275 reputation · 06 Mar 2023, 04:38 UTC
future=True alter pool idle-connection validation? No. In SQLAlchemy 2.0 future=True is the default and only changes execution/result semantics. It does not modify QueuePool recycle logic or idle validation, so Core engine.connect() and ORM Session checkouts share the same stale-connection behavior.pool_recycle for a 30-minute server idle timeout? Set pool_recycle to a value slightly below the server timeout, typically 1700–1790 seconds (≈28–30 minutes). One value works for both Core-only and mixed Core/ORM workloads because they use the same Engine and QueuePool instance.pool_pre_ping be relied upon for both checkout paths without unacceptable latency? pool_pre_ping=True runs a lightweight validation query (usually SELECT 1) at every checkout for both engine.connect() and Session. It detects server-side closure but adds a round-trip per checkout. Under burst traffic this overhead may be measurable; benchmark before enabling globally. It cannot catch a connection that dies after checkout but before the first statement.pool_recycle=0 disables automatic recycling; connections can outlive the server's idle timeout.idle_in_transaction_session_timeout. Confirm the source because it changes whether pool_recycle is the correct mitigation.import logging
logging.basicConfig()
logging.getLogger('sqlalchemy.pool').setLevel(logging.INFO)
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
engine = create_engine("postgresql+psycopg2://...", pool_recycle=1800, pool_pre_ping=True)
# Hold a connection idle past server timeout
with engine.connect() as conn:
pass # connection returned to pool
# Wait longer than server idle timeout (e.g., 35 minutes)
import time; time.sleep(2100)
# Now checkout via Core and ORM
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
with Session(engine) as session:
session.execute(text("SELECT 1"))
Verify no "server closed the connection unexpectedly" errors appear.pg_stat_activity during idle periods to ensure pool checkout count matches backend connections and no stale sockets accumulate.What is the exact source of the 30-minute idle timeout (PgBouncer, managed service setting, or PostgreSQL configuration)? This determines whether pool_recycle alone is sufficient or if additional middleware configuration is needed.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.