Skip to content

Connections and pools

Constructor options follow libpq names. Connections and Pools and PgBouncer explain how they interact.

Connection

Connection(
    dsn: str | None = None,
    *,
    service: str | None = None,
    servicefile: str | Path | None = None,
    host: str | Sequence[str] | None = None,
    hostaddr: str | Sequence[str] | None = None,
    port: int | str | Sequence[int] | None = None,
    target_session_attrs: Literal[
        'any', 'read-write', 'read-only', 'primary', 'standby', 'prefer-standby'
    ]
    | None = None,
    load_balance_hosts: Literal['disable', 'random'] | None = None,
    connect_timeout: float | None = None,
    keepalives: bool | None = None,
    keepalives_idle: int | None = None,
    keepalives_interval: int | None = None,
    keepalives_count: int | None = None,
    tcp_user_timeout: int | None = None,
    user: str | None = None,
    dbname: str | None = None,
    password: str | PasswordProvider | None = None,
    oauth_token: str | OAuthProvider | None = None,
    krbsrvname: str | None = None,
    gsslib: Literal['gssapi', 'sspi'] | None = None,
    passfile: str | Path | None = None,
    sslmode: Literal[
        'disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full'
    ]
    | None = None,
    sslrootcert: str | Path | None = None,
    sslcert: str | Path | None = None,
    sslkey: str | Path | None = None,
    sslpassword: str | bytes | KeyPasswordProvider | None = None,
    sslcertmode: Literal['allow', 'disable', 'require'] | None = None,
    sslnegotiation: Literal['postgres', 'direct'] | None = None,
    sslsni: bool | None = None,
    ssl_min_protocol_version: Literal['TLSv1.2', 'TLSv1.3'] | None = None,
    ssl_max_protocol_version: Literal['TLSv1.2', 'TLSv1.3'] | None = None,
    sslcrl: str | Path | None = None,
    channel_binding: Literal['disable', 'prefer', 'require'] | None = None,
    require_auth: str | None = None,
    min_protocol_version: Literal['3.0', '3.2', 'latest'] | None = None,
    max_protocol_version: Literal['3.0', '3.2', 'latest'] | None = None,
    application_name: str | None = None,
    options: str | None = None,
    client_encoding: str | None = None,
    server_settings: Mapping[str, str] | None = None,
    pool_mode: PoolMode = 'session',
    auto_prepare: bool | None = None,
    sequential: bool = False,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] = (),
    open_timeout: float | None = None,
    operation_timeout: float | None = None,
    max_value_bytes: int | None = None,
    cleanup_timeout: float = 5.0,
    tracer_provider: TracerProvider | None = None,
    meter_provider: MeterProvider | None = None,
)

A dedicated PostgreSQL session. Construction does not open a socket.

Options use libpq names. For each one, an explicit argument overrides the connection string, which overrides the selected service section, then the PostgreSQL environment variable where one exists, then the default.

Parameters:

Name Type Description Default
dsn str | None

A PostgreSQL URI or keyword connection string. Unsupported parameters are errors.

None
service str | None

Service section to read (PGSERVICE).

None
servicefile str | Path | None

Service definitions file (PGSERVICEFILE); otherwise the per-user and system service files.

None
host str | Sequence[str] | None

Host name, or a Unix socket directory. A comma-separated string or a sequence lists hosts tried in order (PGHOST). Without one, the local Unix socket directories are tried.

None
hostaddr str | Sequence[str] | None

Numeric address to connect to, one per host. host remains the TLS certificate identity (PGHOSTADDR).

None
port int | str | Sequence[int] | None

One port for every host, or one per host (PGPORT). Defaults to 5432.

None
target_session_attrs Literal['any', 'read-write', 'read-only', 'primary', 'standby', 'prefer-standby'] | None

Session role required of an accepted host (PGTARGETSESSIONATTRS). prefer-standby falls back to any host.

None
load_balance_hosts Literal['disable', 'random'] | None

random shuffles hosts and resolved addresses for each new physical connection (PGLOADBALANCEHOSTS).

None
connect_timeout float | None

Seconds allowed for each host attempt (PGCONNECT_TIMEOUT).

None
keepalives bool | None

Enable TCP keepalives. Enabled by default.

None
keepalives_idle int | None

Idle seconds before the first keepalive probe.

None
keepalives_interval int | None

Seconds between keepalive probes.

None
keepalives_count int | None

Unanswered probes before the connection is dropped.

None
tcp_user_timeout int | None

Milliseconds transmitted data may stay unacknowledged. Linux only.

None
user str | None

Database role (PGUSER).

None
dbname str | None

Database name (PGDATABASE).

None
password str | PasswordProvider | None

Password, or an async provider called only when the server requests a password mechanism (PGPASSWORD).

None
oauth_token str | OAuthProvider | None

Bearer token, or an async provider that may first return None to request the server's discovery metadata.

None
krbsrvname str | None

Kerberos service name (PGKRBSRVNAME). Defaults to postgres.

None
gsslib Literal['gssapi', 'sspi'] | None

System authentication provider (PGGSSLIB). sspi is available on Windows only.

None
passfile str | Path | None

Password file consulted when no password is given (PGPASSFILE).

None
sslmode Literal['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full'] | None

Transport policy (PGSSLMODE). Defaults to verify-full: TLS with a verified certificate chain and host name.

None
sslrootcert str | Path | None

PEM CA file that verifies the server, or system (PGSSLROOTCERT).

None
sslcert str | Path | None

PEM client certificate chain, leaf first (PGSSLCERT).

None
sslkey str | Path | None

Private key for sslcert (PGSSLKEY).

None
sslpassword str | bytes | KeyPasswordProvider | None

Passphrase for an encrypted PKCS#8 sslkey, or an async provider called only for an encrypted key.

None
sslcertmode Literal['allow', 'disable', 'require'] | None

Whether to send a client certificate (PGSSLCERTMODE). disable also skips the conventional per-user certificate files.

None
sslnegotiation Literal['postgres', 'direct'] | None

direct starts TLS immediately with PostgreSQL ALPN and never falls back to plaintext (PGSSLNEGOTIATION).

None
sslsni bool | None

Send the host name in the TLS ClientHello (PGSSLSNI). Enabled by default; host name verification does not depend on it.

None
ssl_min_protocol_version Literal['TLSv1.2', 'TLSv1.3'] | None

Lowest TLS version accepted (PGSSLMINPROTOCOLVERSION).

None
ssl_max_protocol_version Literal['TLSv1.2', 'TLSv1.3'] | None

Highest TLS version accepted (PGSSLMAXPROTOCOLVERSION).

None
sslcrl str | Path | None

PEM certificate revocation list for a file CA (PGSSLCRL).

None
channel_binding Literal['disable', 'prefer', 'require'] | None

SCRAM channel binding policy (PGCHANNELBINDING). require refuses any authentication not bound to this TLS endpoint.

None
require_auth str | None

Allowed server authentication methods (PGREQUIREAUTH): comma-separated password, md5, gss, sspi, scram-sha-256, oauth, or none, or all prefixed with ! to list refused methods (such as !password,!md5). Any other method fails with ConfigurationError before credentials are sent.

None
min_protocol_version Literal['3.0', '3.2', 'latest'] | None

Lowest accepted PostgreSQL protocol version: 3.0, 3.2, or latest (PGMINPROTOCOLVERSION). Defaults to 3.0; 3.2 fails with ConfigurationError if the server negotiates down to 3.0.

None
max_protocol_version Literal['3.0', '3.2', 'latest'] | None

PostgreSQL protocol version requested at startup: 3.0, 3.2, or latest (PGMAXPROTOCOLVERSION). Defaults to latest (3.2, giving 256-bit cancel keys on PostgreSQL 18+ while older servers negotiate down to 3.0). Set 3.0 behind proxies that close the connection on a 3.2 startup packet.

None
application_name str | None

Name reported in pg_stat_activity (PGAPPNAME). Without one, a connection string's fallback_application_name, then gres.

None
options str | None

Server command-line options for the session (PGOPTIONS).

None
client_encoding str | None

Must resolve to UTF8 (PGCLIENTENCODING).

None
server_settings Mapping[str, str] | None

Session parameters set at startup. They override options and are restored when a pooled session is reset.

None
pool_mode PoolMode

'session' for a direct connection or a session pooler; 'transaction' behind a transaction pooler such as PgBouncer with pool_mode = transaction, which may run each transaction on a different server connection.

'session'
auto_prepare bool | None

Prepare repeated statements and reuse their inferred types. False infers types afresh. Direct sessions prepare automatically. Transaction pooling uses no named statements by default, but repeated execute() calls outside a transaction can reuse built-in parameter types. Set True there only if every pooler tracks named statements (PgBouncer's max_prepared_statements).

None
sequential bool

Run short individual lookups on the calling event loop instead of Gres's background I/O thread, over a Unix socket without a transaction pooler. Defaults to False. A managed transaction, bulk operation, or large transfer moves the connection to the background thread for the rest of its life; TCP always uses that thread.

False
decoding Decoding | None

Default result representations, overridable per call.

None
adapters Sequence[Binding]

Type bindings applied to every operation on this resource.

()
open_timeout float | None

Seconds allowed for opening, across all hosts. None leaves only connect_timeout.

None
operation_timeout float | None

Default budget in seconds for each operation. A call's timeout replaces it; None means no deadline.

None
max_value_bytes int | None

Largest encoded parameter, result field or typed COPY field accepted, in bytes. None is unlimited.

None
cleanup_timeout float

Seconds to wait for cancellation and close to finish before reporting them as still pending.

5.0
tracer_provider TracerProvider | None

OpenTelemetry tracer provider for operation spans.

None
meter_provider MeterProvider | None

OpenTelemetry meter provider for operation and pool metrics.

None

listen

listen(
    channel: str,
    *channels: str,
    buffer_bytes: int = 1024 * 1024,
    timeout: float | None = None,
) -> AbstractAsyncContextManager[AsyncIterator[Notification]]

Reserve a session for committed notifications on one or more channels.

Queue overflow (buffer_bytes exceeded) raises NotificationOverflowError; overflow or connection loss ends delivery without reconnecting. timeout limits the subscription lifetime in seconds; None (default) sets no deadline and does not inherit operation_timeout.

prepare

prepare(
    sql: Source | Query,
    *,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[dict[str, object]]]
prepare(
    sql: Source | Query,
    *,
    row: type[_N],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[_N]]
prepare(
    sql: Source | Query,
    *,
    row: type[tuple[*_Ts,]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[tuple[*_Ts,]]]
prepare(
    sql: Source | Query,
    *,
    row: type[dict[str, _T]],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[dict[str, _T]]]
prepare(
    sql: Source | Query,
    *,
    row: _Scalar[_T] | Callable[..., _T],
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = ...,
) -> AbstractAsyncContextManager[PreparedStatement[_T]]
prepare(
    sql: Source | Query,
    *,
    row: Any = dict,
    decoding: Decoding | None = None,
    adapters: Sequence[Binding] | None = None,
    column_adapters: ColumnBindings | None = None,
    timeout: float | InheritType | None = INHERIT,
) -> AbstractAsyncContextManager[PreparedStatement[Any]]

Prepare one fixed-signature query on this held session. The context closes its server statement.

open async

open() -> None

Open the session, or return if it is already open on this loop.

aclose async

aclose() -> None

Close the session and wait for it to end; closing is terminal.

Pool

Pool(
    dsn: str | None = None,
    *,
    min_size: int = 0,
    max_size: int = 10,
    max_idle: float | None = 300.0,
    max_waiters: int = 100,
    **settings: Unpack[_ConnectionSettings],
)

A bounded pool of PostgreSQL sessions. Construction does not open a socket; use connection() to hold one session across several operations.

Parameters:

Name Type Description Default
dsn str | None

A PostgreSQL URI or keyword connection string, as for Connection.

None
min_size int

Sessions the pool keeps open while idle.

0
max_size int

Physical capacity, including sessions being opened, reset, or closed.

10
max_idle float | None

Seconds an idle session above min_size is kept. None disables expiry.

300.0
max_waiters int

Callers allowed to queue for a session. Further demand raises PoolBusyError.

100
**settings Unpack[_ConnectionSettings]

Every keyword option of Connection except sequential, applied to each session.

{}

stats property

stats: PoolStats

Snapshot occupancy without checking out a session; physical states are mutually exclusive.

listen

listen(
    channel: str,
    *channels: str,
    buffer_bytes: int = 1024 * 1024,
    timeout: float | None = None,
) -> AbstractAsyncContextManager[AsyncIterator[Notification]]

Reserve a session for committed notifications on one or more channels.

Queue overflow (buffer_bytes exceeded) raises NotificationOverflowError; overflow or connection loss ends delivery without reconnecting. timeout limits the subscription lifetime in seconds; None (default) sets no deadline and does not inherit operation_timeout.

invalidate_types

invalidate_types() -> None

Refresh client type metadata for subsequent operations on this pool.

Call on the pool's event loop after the migration commits. The call sends no SQL, does not disconnect borrowers, and does not change results already in flight. Other pools and processes must be notified separately.

open async

open() -> None

Authenticate the first connection before reporting readiness.

connection async

connection(
    *, timeout: float | InheritType | None = INHERIT
) -> AsyncGenerator[Connection, None]

Check out one session until the block exits. The checkout timeout does not limit the block.

aclose async

aclose() -> None

Close the pool and its sessions; closing is terminal.

New checkouts fail at once. Connections still checked out stop working, idle sessions close, and Gres waits up to cleanup_timeout for their cleanup.

PoolStats dataclass

PoolStats(
    idle: int,
    in_use: int,
    connecting: int,
    resetting: int,
    closing: int,
    waiters: int,
)

A snapshot of the pool's sessions and the callers waiting for one.

Each session is counted in exactly one of idle, in_use, connecting, resetting and closing; together they hold the capacity, at most max_size.

Attributes:

Name Type Description
idle int

Open sessions ready to be checked out.

in_use int

Sessions checked out by callers.

connecting int

Sessions being opened.

resetting int

Returned sessions whose reset has not finished.

closing int

Sessions being closed that still hold capacity.

waiters int

Callers waiting for a session.

idle instance-attribute

idle: int

in_use instance-attribute

in_use: int

connecting instance-attribute

connecting: int

resetting instance-attribute

resetting: int

closing instance-attribute

closing: int

waiters instance-attribute

waiters: int

pending_cleanup property

pending_cleanup: int

Sessions whose reset or close has not finished: resetting + closing.

ConnectionTarget dataclass

ConnectionTarget(
    host: str, hostaddr: str | None, port: int, dbname: str, user: str
)

Selected PostgreSQL identity and actual TCP address (None for a Unix socket).

host instance-attribute

host: str

hostaddr instance-attribute

hostaddr: str | None

port instance-attribute

port: int

dbname instance-attribute

dbname: str

user instance-attribute

user: str

PasswordProvider module-attribute

PasswordProvider: TypeAlias = Callable[[PasswordRequest], Awaitable[str]]

Async callback returning a password when the server challenges with a password mechanism.

PasswordRequest dataclass

PasswordRequest(target: ConnectionTarget, mechanism: Mechanism)

An admitted server password challenge, before any response is sent.

target instance-attribute

mechanism instance-attribute

mechanism: Mechanism

KeyPasswordProvider module-attribute

KeyPasswordProvider: TypeAlias = Callable[
    [KeyPasswordRequest], Awaitable[str | bytes]
]

Async callback returning the passphrase for an encrypted sslkey.

KeyPasswordRequest dataclass

KeyPasswordRequest(keyfile: Path)

The selected encrypted local private key, before TLS negotiation.

keyfile instance-attribute

keyfile: Path

OAuthProvider module-attribute

OAuthProvider: TypeAlias = Callable[[OAuthRequest], Awaitable[str | None]]

Async callback returning an OAuth bearer token, or None to request server discovery metadata.

OAuthRequest dataclass

OAuthRequest(target: ConnectionTarget, discovery: OAuthDiscovery | None)

Bearer token request for one endpoint, with metadata only after deliberate discovery.

target instance-attribute

discovery instance-attribute

discovery: OAuthDiscovery | None

OAuthDiscovery dataclass

OAuthDiscovery(discovery_url: str, scope: str | None)

Metadata supplied by PostgreSQL; validate the issuer before contacting an identity service.

discovery_url instance-attribute

discovery_url: str

scope instance-attribute

scope: str | None