Pools and PgBouncer¶
Pool shares a bounded set of PostgreSQL sessions across concurrent tasks. It accepts every Connection option except sequential and implements the same Executor methods.
Share sessions across tasks¶
import asyncio
from gres import Pool, scalar
async def main() -> None:
async with Pool(max_size=10) as pool:
await pool.execute(
'CREATE TABLE station(id int PRIMARY KEY, name text NOT NULL)'
)
try:
# A transaction keeps one session until commit or rollback.
async with pool.transaction() as tx:
await tx.execute_many(
'INSERT INTO station VALUES ($1, $2)',
[(1, 'Harbour'), (2, 'Airport')],
)
# Each statement on the pool borrows a session and returns it.
async def name(station: int) -> str:
return await pool.fetch_one(
'SELECT name FROM station WHERE id = $1',
(station,),
row=scalar(str),
)
async with asyncio.TaskGroup() as group:
names = [group.create_task(name(station)) for station in (1, 2)]
print([task.result() for task in names]) # ['Harbour', 'Airport']
finally:
await pool.execute('DROP TABLE IF EXISTS station')
asyncio.run(main())
Session lease scopes:
- Direct pool call (
pool.fetch_one, etc.): borrows a session for that statement;timeoutincludes waiting for a session. async with pool.connection() as db: holds one session across multiple statements (required forTEMPtables andprepare());timeoutbounds only checkout wait.async with pool.transaction() as tx: holds one session through commit or rollback.- Streams and listeners: hold their session until the
async withblock exits.
async with Pool() as pool opens and authenticates at least one session (max(1, min_size)) before returning. A failed open() cleans up partial sessions and can be retried; aclose() is terminal.
Reset on return¶
Returning a session to the pool resets session settings, role, temporary objects, listeners, cursors, session advisory locks, and explicit PREPARE/prepare() statements before the next borrower uses it.
- Gres retains its own automatically prepared statements unless the borrower ran DDL,
SET,DO,CALL, orPREPARE, hit an error, or left an explicit statement open — in which case it runsDISCARD ALL. - Returning a session with an unfinished raw
BEGINrolls it back and raisesInterfaceError. - Single-operation pool calls queue reset after the result returns; if the next borrower waits for that reset, the wait counts against its
timeout(and a lost session reportsdispatch_state == 'not_sent'). - Gres cannot detect
PREPAREinside a function or (before PostgreSQL 18)search_pathmodified viaset_config(); run those on a dedicated connection or issueDISCARD ALLbefore release.
Size the pool¶
max_sizecaps total physical sessions (including connecting, resetting, and closing). Across all worker processes, keep totalmax_sizebelow PostgreSQL'smax_connectionswith headroom for admin and migrations.max_waiterscaps the checkout queue; excess callers fail immediately withPoolBusyError.min_sizekeeps a baseline of idle sessions;max_idleexpires surplus idle sessions (Nonedisables expiry).- A pool bounds database sessions, not client CPU; see the eight-process timings when sizing multi-worker deployments.
See the Pool reference for defaults.
Monitor the pool¶
pool.stats returns a PoolStats snapshot without borrowing a session. Unclaimed sessions mid-reset count as resetting rather than idle; once claimed they count as in_use. Sessions still closing after a cleanup timeout still hold capacity until aclose() observes completion. See Observability for matching OpenTelemetry metrics.
PgBouncer transaction pooling¶
Set pool_mode='transaction' on Pool or Connection behind PgBouncer pool_mode = transaction or any hosted transaction pooler (the default 'session' is for direct connections and session poolers):
# Partial: configuration; the host name is a placeholder.
from gres import Pool
pool = Pool(
'postgresql://api@pgbouncer.internal:6432/inventory',
pool_mode='transaction',
)
- A checked-out session is a proxy connection, not a pinned PostgreSQL backend. Use
transaction()for backend affinity andSET LOCALfor transaction-scoped settings. - On return, Gres rolls back any unfinished transaction without sending
DISCARD ALL. LISTENrequirespool_mode='session'.- Behind a pooler that drops connections on PostgreSQL protocol 3.2 startup packets, set
max_protocol_version='3.0'(see Lifecycle and timeouts).
Prepared statements behind a transaction pooler¶
- By default, Gres creates no named statements in transaction mode; repeated
execute()calls outside a transaction can still reuse built-in parameter types locally, while fetches verify result columns against the backend. - Pass
auto_prepare=Trueonly when every pooler endpoint tracks protocol-level prepared statements (max_prepared_statements > 0). Without tracking, backend reassignment will fail the query without replay. Tracking does not make SQLPREPAREor session settings portable. - For fresh parameter inference on every call, set
auto_prepare=False(or passprepare=Falseper call). After schema changes, callinvalidate_types()and follow PgBouncer'smax_prepared_statementsguidance.