PgBouncer transaction pooling and prepared statements

PgBouncer transaction pooling cuts server connections, but it changes what application sessions may do. This page covers which features break, how to configure prepared statements and pool size, and which security fixes to apply.

On this page

Why PgBouncer transaction pooling needs an application check first

Transaction pooling is worth considering only after you have checked what your applications send to the database. If connection counts are approaching PostgreSQL's limits, PgBouncer can reduce the number of server connections your clients need, but transaction mode changes what a client can rely on between statements. PgBouncer is a lightweight connection pooler for PostgreSQL that sits between applications and the server. It keeps a pool of server connections and lends them to clients, and its pool modes decide when a server connection goes back to the pool. Teams usually need transaction mode when many short-lived application connections spend most of their time idle, and a session-level pool would still hold a server connection for each one.

The constraint that drives the whole decision is simple. In transaction pooling mode, each transaction can run on a different server connection, so clients must not depend on session-based features. Session state such as session-level settings, session advisory locks, temporary tables and LISTEN/NOTIFY may appear to work in a quick test and then fail intermittently under load. Before you change anything, inventory every application, migration tool, ORM and batch job that connects through the pooler, and ask each owner which session features it uses. Those findings, not the connection count alone, decide whether transaction mode is safe for each service.

Plan the work around the current release. PgBouncer 1.26.1, released October 14, 2026, includes security fixes for earlier 1.x versions, so any existing deployment should be checked against the PgBouncer changelog before the pooler is configured or upgraded. Confirm the version you run in each environment, including packaged builds on hosts you control, and record the upgrade as part of the rollout plan. The sections that follow cover prepared statements and pool sizing, but none of those settings matter if the application check has not been done first.

Which session features stop working in transaction mode

In transaction pooling mode, PgBouncer can hand each transaction to a different server connection, so anything that depends on state living on one connection breaks silently. The cards below cover the session features most often affected and how to find them before go-live. The exact behavior should be confirmed against the PgBouncer configuration docs for the version you run.

Session-level SET and RESET

A SET issued outside a transaction, or a SET in one transaction that the application expects in the next, may apply to a server connection the client never sees again. Settings such as search_path, timezone or statement_timeout can appear to work in testing and then vary between requests. Search application code and ORM setup hooks for session-level SET calls, and move them into SET LOCAL within a transaction or into the role or database configuration.

PgBouncer config docs

Session-level advisory locks

Session advisory locks such as pg_advisory_lock are held by the server connection that acquired them, not by the client. In transaction mode the unlock may run on a different server connection, or the lock may stay held by a connection the pool later reuses for another client. Transaction-scoped advisory locks, pg_advisory_xact_lock, are the safe replacement. Grep the codebase for pg_advisory_lock and check any migration or job runner that relies on it.

Temporary tables

A CREATE TEMPORARY TABLE exists only on the server connection that created it. The next transaction from the same client may land on a different connection where the table does not exist, which produces errors or, worse, reads from a table with the same name left by another client. Check batch jobs and reporting code for temp tables that span several transactions, and rewrite them as CTEs, regular tables with cleanup, or work done inside one transaction.

LISTEN and NOTIFY

LISTEN registers interest on a specific server connection, so notifications are delivered only if that connection is the one receiving them. In transaction mode, a client can issue LISTEN and then never receive events, because its later statements run elsewhere. If your application uses notifications for cache invalidation or job wake-ups, route those listeners through a direct connection or a session pool. Search for LISTEN in application code, drivers and any event-processing services.

Cursors held across transactions

A cursor declared with DECLARE ... CURSOR WITHOUT HOLD exists only within its transaction, and a cursor declared WITH HOLD lives on one server connection. Either way, a FETCH that runs in a later transaction can fail or read from the wrong connection. Paginated exports and streaming readers are the usual cases. Check drivers that expose server-side cursors, and confirm whether the driver keeps the cursor inside one transaction.

Protocol and driver session state

Some drivers and frameworks keep session-scoped state in the client, such as prepared statement names, session variables set through connection parameters, or a pinned connection for a multi-step operation. These assumptions are invisible in SQL review. Confirm the exact list with the PgBouncer configuration docs and your driver's documentation, then test each path under transaction mode before go-live.

How prepared statements behave behind PgBouncer

Prepared statements are the part of transaction pooling that most often breaks applications, because the statement a driver prepares may not exist on the server connection that runs its next transaction. There are two different mechanisms that people both call prepared statements. SQL-level prepared statements are created with the PREPARE command inside a session and removed with DEALLOCATE, so they live only as long as that server backend. Protocol-level prepared statements are created by the driver through the extended query protocol, which sends a parse message with a statement name, then reuses that name in later bind and execute messages. Many drivers do this automatically for every parameterized query, often with a cached name and no visible SQL. Under transaction pooling, PgBouncer may hand the next transaction to a different server connection, which has never seen that name. The result is an error such as a prepared statement not existing, and it can appear only under load, when connections are reassigned.

PgBouncer handles protocol-level statements through the max_prepared_statements setting. When it is greater than zero, PgBouncer tracks the statements a client has prepared and re-creates them on whichever server connection serves the transaction, so the driver's cached names remain valid. Setting it to zero leaves that tracking off, which is the safe choice for applications that never use protocol-level preparation, but drivers that do will fail intermittently under transaction pooling. Before choosing a value, confirm in the PgBouncer configuration docs how the current release handles this setting, which driver features it supports and what memory cost the tracking adds per pool. Then test each application driver, including any ORM or connection library that prepares statements implicitly, against a staging pooler in transaction mode, and look for statement-not-found errors under concurrent load rather than in single-user tests.

Which PgBouncer pool settings fit which workload

This table compares the PgBouncer settings that matter most in transaction pooling, showing when each fits and what breaks when it is set wrongly. Read each row as a decision: find the workload you run, then check the setting's failure mode before changing it. Defaults and valid ranges belong in the configuration docs, so confirm exact values there for your PgBouncer version.

SettingWhen it fitsWhat breaks if mismatched
pool_mode = sessionApplications that rely on session state, such as session-level SET, advisory locks held across calls, or LISTEN/NOTIFYPooling gains are small because a server connection stays pinned to each client for the whole session
pool_mode = transactionMany short transactions from web or API workers that need a high client count with fewer server connectionsSession features stop working because each transaction may run on a different server connection
pool_mode = statementAutocommit-only workloads with no multi-statement transactions, where each statement is independentExplicit transactions fail or behave unexpectedly, so it is rarely the right choice for general application traffic
max_prepared_statementsDrivers that use protocol-level prepared statements in transaction mode, with a value sized to the number of distinct statements per applicationToo low causes repeated evictions and re-preparation; too high raises memory use on PgBouncer and PostgreSQL for each server connection
default_pool_sizeSized to what PostgreSQL can serve well for the database, leaving headroom for admin and maintenance connectionsToo large pushes PostgreSQL into contention and memory pressure; too small queues client requests and adds latency
max_client_connSet to the total number of application connections across all instances, with room for growth and deploy overlapClients are refused once the limit is reached, which shows up as connection errors during scale-out or rolling restarts
server_reset_queryDefault reset behavior for clean server connections, adjusted only if your session changes need explicit cleanupA weak or missing reset can leak session state between clients, which is a data and security risk
server_reset_query_alwaysEnable when session state can leak even in transaction mode, such as temporary settings applied by application codeAdds reset work on each checkout, so throughput can drop on short transactions

Setting up transaction pooling without breaking applications

This sequence moves an application from direct PostgreSQL connections to PgBouncer in transaction mode while confirming that drivers, session logic and prepared statements still behave correctly. Each step ends with a check that tells the team whether to continue.

  1. Inventory driver and framework versions

    The application team lists every service that connects to PostgreSQL, with its language, database driver, ORM or query library, and exact versions. They also note whether each driver uses protocol-level prepared statements, which is documented in the driver's own configuration reference. The output is a table with one row per service. Confirm each row with the service owner, since a service that is missing from the inventory will fail in production rather than in testing.

  2. Audit code for session features

    Developers search the codebase and migration scripts for features that depend on a single server connection staying attached to a client. In transaction mode, each transaction can run on a different server connection, so session-level SET commands, session advisory locks, LISTEN and NOTIFY, temporary tables that outlive a transaction, and session-scoped cursors need review. The check is a written list of each finding, with a decision to rewrite it, move it to a dedicated direct connection, or accept it with a documented reason.

  3. Set pool mode to transaction

    The operator changes pool_mode to transaction in the PgBouncer configuration file, reloads the configuration, and points a non-production copy of one service at PgBouncer. Services that need session features are routed to a separate pool or to PostgreSQL directly, as decided in the previous step. The check is that the reloaded PgBouncer accepts connections and the test service starts without errors. The pool mode options are described in the PgBouncer configuration reference.

  4. Configure max_prepared_statements for protocol-level drivers

    For drivers that create protocol-level prepared statements, the operator sets max_prepared_statements to a value that covers the statements the application uses, so PgBouncer can track them across server connections. Drivers that reuse statement names without this support will produce errors such as missing prepared statement failures. The team confirms the exact setting against the PgBouncer configuration reference and their driver's documentation, then runs the affected service and checks the PgBouncer logs for prepared statement errors.

  5. Size the pool against max_connections

    The DBA calculates the total server connections that all pools can open toward PostgreSQL and compares that total with the max_connections setting on the database server, leaving headroom for administrative sessions, replication and maintenance. Pool size and per-database limits are set in PgBouncer, and the sum must stay under the PostgreSQL limit. The output is a written sizing sheet that shows the arithmetic. Confirm the final numbers with a load test rather than relying on the first estimate.

  6. Run application test suites

    QA runs the full automated test suites for each service against PgBouncer, including integration tests that exercise transactions, migrations, background jobs and any code paths identified in the audit. Failures are classified as session feature issues, prepared statement issues or unrelated defects. The check is a passing suite on every service with a list of any accepted exceptions signed by the service owner.

  7. Load test and review pooler metrics

    The team runs a load test that mirrors production traffic patterns, then reviews PgBouncer statistics and PostgreSQL activity during the run. They look for client wait times, server connection saturation, errors and any rise in query latency compared with a direct-connection baseline. The test is complete when the results match the sizing sheet and the team records the configuration version that passed. Repeat this step after any change to pool sizes, driver versions or PgBouncer upgrades, including the 1.26.1 release that fixed security issues in earlier 1.x versions.

How to size the pool for different traffic shapes

Many short OLTP transactions are the shape where transaction pooling pays off most. Each transaction holds a server connection for a few milliseconds, so a small number of server connections can serve a large number of client connections. The pool size is driven mainly by how much concurrent database work the server can absorb without queueing on CPU, disk and locks, not by the number of application instances. Treat the server connection count as the quantity to tune, and keep it well below PostgreSQL's max_connections so that administrative sessions, replication and monitoring still have room.

  • Server pool size (default_pool_size): Start from the number of CPU cores and disk parallelism you have, then raise it only if monitoring shows idle server connections while clients wait.
  • Client ceiling (max_client_conn): Set this to the total number of application connections you expect across all instances, including headroom for spikes.
  • Per-backend memory: Each server connection is a PostgreSQL backend with its own memory, so confirm that the pool size times per-backend usage fits within the host's memory budget.
  • Wait time on the client side: Watch cl_waiting and the time clients spend waiting for a server connection in SHOW POOLS.
  • Server utilization: Compare CPU, I/O wait and lock waits on PostgreSQL during peaks, because a larger pool that raises these only moves the queue into the database.

Confirm the choice by checking that client wait stays low at peak while database latency and CPU remain within your targets. Ask your team to rerun this check after each traffic increase.

How client connections map to server connections

The diagram starts with application clients, each holding its own client connection to PgBouncer. PgBouncer keeps a smaller set of server connections to PostgreSQL and assigns one to a client only for the length of a transaction. When the transaction commits or rolls back, the server connection returns to the pool for another client. Check that no application code depends on state that lives on a single server connection, because the next transaction may run on a different one.

Client connections share a smaller pool of server connections, assigned per transaction.

Security fixes and hardening for PgBouncer 1.x

PgBouncer sits between your applications and PostgreSQL, so its version, authentication and transport settings shape who can reach your databases. The cards below cover the security fix release, how to confirm exposure, and the authentication and TLS settings to review before a transaction pooling rollout goes live.

Confirm exposure to the 1.26.1 fixes

PgBouncer 1.26.1, released October 14, 2026, fixed CVE-2026-107350, CVE-2026-107349 and CVE-2026-107348 in earlier 1.x versions. Start by recording the exact PgBouncer build on every pooler host, including containers and packaged copies, because a package manager may report a different version than the binary running in production. Then read the changelog entries for each affected release. Confirm exposure with your security team before you change anything, and record the result for the change ticket.

PgBouncer changelog

Plan the upgrade around pooling mode

Upgrading a pooler is usually a small change, but it still interrupts client connections when you restart or reload it. Plan a maintenance window, or run a second PgBouncer instance behind your load balancer and move traffic over. Test the new version against your transaction pooling settings, including pool_mode, max_client_conn and default_pool_size, in a non-production environment that mirrors your application's driver and prepared statement behavior. Keep the previous binary available for rollback.

Review client authentication settings

Check how clients prove their identity to PgBouncer through auth_type and auth_file, and confirm that the stored password hashes match the method your PostgreSQL server uses. Where PostgreSQL uses SCRAM, make sure PgBouncer is configured to pass credentials in a form the server accepts, and test every application role. Remove shared or stale entries from the auth file, and restrict file permissions so that only the PgBouncer service account can read it.

Encrypt client connections to PgBouncer

Decide whether application traffic to PgBouncer must be encrypted, and configure client_tls_sslmode and the certificate and key settings to match that decision. Do not allow plaintext connections from networks that cross a trust boundary. Confirm that your drivers verify the server certificate rather than accepting any certificate, and rotate the certificate under a documented procedure. Test the handshake for each driver version your applications use, since some older clients negotiate TLS differently.

Encrypt server links from PgBouncer to PostgreSQL

Traffic from PgBouncer to PostgreSQL carries the same credentials and query results, so the server side needs its own TLS decision. Set server_tls_sslmode to the level your security policy requires, and where verification is required, provide the CA file through server_tls_ca_file. Confirm that the PostgreSQL server's pg_hba.conf accepts the connection type PgBouncer uses. Verify the setting with an actual connection test, not only by reading the configuration file.

Limit administrative access to the pooler

The PgBouncer admin console, reached through the special pgbouncer database, can pause, resume and reconfigure pools. Restrict it with admin_users and stats_users, bind the listening address to the interfaces you need, and control which hosts can reach the listening port with firewall rules. Log and review administrative sessions, and keep the admin credentials separate from application credentials so a leaked application password cannot change pool behavior.

What teams ask before hiring help with PgBouncer pooling

How much effort does a transaction-mode PgBouncer migration take?

Effort depends mainly on how many session-dependent features your applications use and how many drivers and services connect through the pool. Each session feature, such as session-level SET commands, advisory locks taken outside a transaction, LISTEN/NOTIFY, temporary tables that span transactions, or protocol-level prepared statements, needs a fix in code, configuration or driver settings. A small number of services on one driver with good test coverage is a far smaller job than many services on mixed drivers with little automated testing. Ask for an inventory of these features before any estimate is discussed, because the inventory is what turns a vague estimate into a bounded one.

Can our team migrate to PgBouncer transaction pooling on its own?

Many teams can, provided they have an engineer who understands both the PostgreSQL protocol and their application's database access layer, and they have a staging environment that reproduces production query patterns. The usual gaps are not PgBouncer configuration itself but the search for session-state assumptions across codebases, and the load testing that shows whether pool sizing holds under peak traffic. Outside help is most useful for that audit, for a written test plan, and for a second review of the configuration before production. Confirm internally who owns each application's database layer before deciding.

What do application owners need to provide for the work?

Application owners need to supply access to their code, their driver and ORM versions, and a list of the database features their services use. They also need to schedule time to review findings, since most fixes sit in application code or connection settings that only the owning team can approve. In practice that means named contacts per service, a staging environment they can run tests against, and a release window for changes that alter how connections are opened or how prepared statements are created. Agree these responsibilities in writing so that a delay in one team does not quietly stall the whole pool rollout.

How long does a PgBouncer pooling project take?

Duration is set by scope, not by a standard timeline. The main drivers are the number of services, the number of session features that need changes, how much automated test coverage exists, and how many environments must be validated before production. Load testing and a staged rollout add time that is easy to underestimate. Ask any provider, including DeployOpen, for a written scope with deliverables, assumptions and a timeline tied to those deliverables. DeployOpen agrees scope, deliverables and timelines in writing before work starts, so you can compare proposals on the same basis.

Is the PgBouncer 1.26.1 security patch urgent?

If you run a 1.x release earlier than 1.26.1, treat the upgrade as a priority. PgBouncer 1.26.1 was released on October 14, 2026 and fixed three CVEs affecting earlier 1.x versions: CVE-2026-107350, CVE-2026-107349 and CVE-2026-107348. Check the PgBouncer changelog for the affected version ranges and the details of each fix, then compare them with the version in your environment. Upgrading PgBouncer is usually a smaller change than a pooling migration, but it still needs a test in staging and a restart plan, so schedule it now rather than waiting for the rest of the project.

What does a quote for PgBouncer pooling work include?

A useful quote lists each deliverable and what it covers: an inventory of session-dependent features, the changes to application or driver configuration, the PgBouncer configuration and pool sizing, load and failure testing, the rollout and rollback plan, and documentation for the team that runs it afterward. It should state assumptions, such as which services are in scope and which environments are available, and what is excluded, such as changes to application features unrelated to pooling. Ask whether the quote is one-time or includes ongoing support, since upgrades and monitoring after go-live recur. DeployOpen provides a quote that follows from the written scope.

Which session features will break in transaction pooling mode?

Any feature that depends on one client keeping the same server connection between transactions will break or behave unexpectedly. PgBouncer's configuration documentation explains that in transaction pooling mode clients must not use session-based features, because each transaction can run on a different server connection. Engineers should check for session-level SET statements, session advisory locks, LISTEN/NOTIFY, WITH HOLD cursors, and protocol-level prepared statements that a driver expects to persist. Confirm the behavior against the PgBouncer configuration reference for your exact version before deciding on fixes.

What DeployOpen needs to scope a PgBouncer engagement

Scoping starts with the versions in play, because they decide which PgBouncer fixes apply and which PostgreSQL behaviors the pool must respect. Tell DeployOpen the PostgreSQL major version on each primary and standby, and the PgBouncer version currently running, including the exact 1.x release. PgBouncer 1.26.1 was released on October 14, 2026 with fixes for CVE-2026-107350, CVE-2026-107349 and CVE-2026-107348 affecting earlier 1.x versions, so an installed release older than that needs a patch decision before any tuning work. Also note whether PgBouncer runs on the database hosts, on separate VMs or in Kubernetes, and whether any traffic reaches the database without passing through the pool.

The application side matters as much as the infrastructure. List every application, service and batch job that connects through the pool, with the language, the driver and its version, the ORM or query layer, and the pool mode each one uses today. Ask specifically whether drivers use protocol-level prepared statements, whether any code relies on SET or session variables, advisory locks, LISTEN/NOTIFY, temporary tables or WITH HOLD cursors, and whether any connection uses SET ROLE or SET SESSION AUTHORIZATION. Those answers determine whether transaction mode is viable for each application, and whether max_prepared_statements must be set. Confirm these with your application owners and driver documentation, since the pool cannot see what a client does inside a session.

Connection metrics and incident history set the pool size and show what has already gone wrong. Provide SHOW POOLS and SHOW STATS output from the admin console over a representative period, the PostgreSQL max_connections value, peak client and server connection counts, and any too many connections, client wait, or timeout errors from logs. Describe recent incidents, such as connection storms after deploys or failovers. Engagements are fixed-scope: scope, deliverables and timelines are agreed in writing before work starts, and DeployOpen does not publish prices. A written quote follows from that scope, so ask for the deliverables, the retest and any ongoing support to be stated separately, and expect the effort to rise with the number of applications and drivers involved.

How DeployOpen delivers PgBouncer pooling

DeployOpen plans, builds, tests, documents and supports PgBouncer in transaction mode inside infrastructure you control, starting with an inventory of which application features depend on session state. The work covers pool design, prepared statement handling for your drivers, and the version and patch baseline, so the pooler is checked against your application before it reaches production.

How we scope

  • Inventory which applications use session features such as SET, advisory locks, LISTEN and temporary tables
  • Confirm each driver's prepared statement behavior and the max_prepared_statements value it needs
  • Agree pool sizing inputs, target PgBouncer version and patch cadence in a written, fixed-scope plan

How we build

  • Configure pool modes, pool sizes and client limits per database and user in your environment
  • Adjust application connection settings and test prepared statement paths under realistic concurrency
  • Run load and failover tests with your workload, then record measured results rather than assumed ones

How we hand over

  • Deliver configuration files, runbooks for pool changes, and the list of known session-feature restrictions
  • Document the upgrade procedure for PgBouncer 1.x releases, including how to read the changelog for security fixes
  • Train your operators on monitoring pool saturation, waiting clients and error patterns before handover is signed off

How we support

  • Ongoing support, upgrades and continuous testing are available as a retainer after handover
  • Apply security releases such as 1.26.1 under the agreed change process and retest affected paths
  • Re-check pool sizing when application concurrency, driver versions or PostgreSQL versions change

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.