Skip to content

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; timeout includes waiting for a session.
  • async with pool.connection() as db: holds one session across multiple statements (required for TEMP tables and prepare()); timeout bounds 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 with block 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, or PREPARE, hit an error, or left an explicit statement open — in which case it runs DISCARD ALL.
  • Returning a session with an unfinished raw BEGIN rolls it back and raises InterfaceError.
  • 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 reports dispatch_state == 'not_sent').
  • Gres cannot detect PREPARE inside a function or (before PostgreSQL 18) search_path modified via set_config(); run those on a dedicated connection or issue DISCARD ALL before release.

Size the pool

  • max_size caps total physical sessions (including connecting, resetting, and closing). Across all worker processes, keep total max_size below PostgreSQL's max_connections with headroom for admin and migrations.
  • max_waiters caps the checkout queue; excess callers fail immediately with PoolBusyError.
  • min_size keeps a baseline of idle sessions; max_idle expires surplus idle sessions (None disables 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 and SET LOCAL for transaction-scoped settings.
  • On return, Gres rolls back any unfinished transaction without sending DISCARD ALL.
  • LISTEN requires pool_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=True only 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 SQL PREPARE or session settings portable.
  • For fresh parameter inference on every call, set auto_prepare=False (or pass prepare=False per call). After schema changes, call invalidate_types() and follow PgBouncer's max_prepared_statements guidance.