Database connection pooling
suggest changeEstablishing a new relational database connection involves multiple network round-trips: TCP handshakes, TLS negotiation, user authentication, and server-side process allocation. In web applications and microservices, creating a new connection per HTTP request introduces significant latency and can quickly exhaust database connection limits.
Connection pooling maintains a cache of warm, reusable database connections. Worker threads or coroutines borrow a connection from the pool, execute queries, and return it to the pool when finished.
SQLAlchemy Connection Pooling
SQLAlchemy automatically manages connection pools via its Engine. For multi-threaded applications, it uses QueuePool by default:
from sqlalchemy import create_engine, text
# Configure connection pool settings
engine = create_engine(
"postgresql+psycopg2://user:password@localhost:5432/app_db",
pool_size=10, # Number of connections to keep open permanently
max_overflow=20, # Max extra connections allowed during traffic spikes
pool_timeout=30, # Seconds to wait before raising TimeoutError if pool is empty
pool_recycle=1800, # Recycle connections older than 30 mins to avoid dropped sockets
pool_pre_ping=True # Automatically test connection validity before handing it out
)
# Borrow connection from pool and return it automatically when block exits
with engine.connect() as conn:
result = conn.execute(text("SELECT id, username FROM users WHERE active = :status"), {"status": True})
for row in result:
print(f"User {row.id}: {row.username}")
Serverless and Lambda (NullPool)
In ephemeral serverless environments (like AWS Lambda), long-lived connection pools can leak connections. Use NullPool so connections close immediately upon block exit, or connect through a proxy like PgBouncer:
from sqlalchemy.pool import NullPool
serverless_engine = create_engine(
"postgresql+psycopg2://user:password@localhost:5432/app_db",
poolclass=NullPool
)
PostgreSQL Pooling with psycopg_pool (Psycopg 3)
In modern Psycopg 3, use the dedicated psycopg_pool package:
pip install "psycopg[binary,pool]"
from psycopg_pool import ConnectionPool
conninfo = "dbname=app_db user=postgres password=secret host=localhost port=5432"
# Initialize pool with minimum and maximum connections
with ConnectionPool(conninfo, min_size=4, max_size=20) as pool:
# Acquire a connection from the pool
with pool.connection() as conn:
with conn.cursor() as cur:
cur.execute("SELECT COUNT(*) FROM orders")
total = cur.fetchone()[0]
print(f"Total orders: {total}")
Asynchronous Pooling with asyncpg
For high-concurrency asyncio applications (such as FastAPI, Sanic, or AIOHTTP), asyncpg provides an asynchronous connection pool:
import asyncio
import asyncpg
async def main():
# Create an async connection pool
pool = await asyncpg.create_pool(
dsn="postgresql://postgres:secret@localhost:5432/app_db",
min_size=5,
max_size=25,
max_inactive_connection_lifetime=300
)
# Acquire connection from pool concurrently
async with pool.acquire() as conn:
users = await conn.fetch("SELECT id, email FROM users LIMIT 5")
for u in users:
print(f"{u['id']}: {u['email']}")
await pool.close()
asyncio.run(main())
Best Practices
- Always configure
pool_pre_ping=True(or a validation query): Firewalls and cloud load balancers terminate idle TCP connections silently. Pre-pinging checks whether a borrowed connection is alive and transparently reconnects if stale. - Match pool size to database limits: Total pool sizes across all application instances must not exceed PostgreSQL's
max_connectionsor MySQL'smax_connections. - Keep loan duration short: Never perform slow external HTTP calls or compute-heavy tasks while holding an open database connection; acquire the connection only for the database query and release it immediately.