Connection pooling
A connection pool keeps a set of open database connections and lends them out, so each request does not pay for a new TCP handshake, TLS, and authentication.
Detailed Explanation
Opening a Postgres connection is expensive: network, SSL, auth, session setup. A web worker that opens a connection per request will spend more time connecting than querying under load. A pool holds N live connections. checkout takes one; checkin returns it. If all are busy, the caller waits or errors, which is backpressure.
SQLAlchemy's create_engine includes QueuePool by default. pool_size, max_overflow, pool_timeout, and pool_pre_ping are the knobs. pool_pre_ping issues a cheap SELECT 1 (or equivalent) so you do not hand a request a connection the load balancer already closed.
Django's CONN_MAX_AGE keeps a connection for a worker across requests. Gunicorn with 8 workers and CONN_MAX_AGE non-zero means up to 8 connections idle. Multiply by process count before you hit the database's max_connections.
Async drivers (asyncpg, SQLAlchemy async) have their own pools. Do not use a sync pool from many asyncio tasks without a thread wrapper; you will block the loop. Do not share one sqlite connection across threads unless you asked for it.
A pool is not a session cache. Return the connection as soon as the request's transaction ends. Holding a connection while you call HTTP is how you exhaust the pool. The symptom is timeouts on checkout, not on SQL.
In tests, a pool can keep the in-memory sqlite database alive longer than you think, or leak connections if you forget to dispose() the engine. Dispose in fixture teardown.
PgBouncer and similar live in front of the database and are another pool. Application pool plus server pool is normal; size them so you do not multiply to a thousand connections.
Code Examples
from sqlalchemy import create_engine, text
engine = create_engine(
"sqlite+pysqlite:///:memory:",
pool_pre_ping=True,
pool_size=5,
max_overflow=2,
)
with engine.connect() as conn:
print(conn.execute(text("select 1")).scalar()) # 1
engine.dispose()# Size: workers * pool_size must fit in the database max_connections
# 4 gunicorn workers * pool_size=10 = 40 connections, plus overflowCommon Gotchas
Connection per query in a loop
you thrash the pool and the database. Reuse one connection for the request.
Holding a connection across `await` HTTP
pool waiters pile up. Close or return first.
`max_connections` on Postgres is small
100 is common. Count workers × pool_size.