Software

PgBouncer Connection Pooling: Configure PostgreSQL for Reliable App Traffic

Configure PgBouncer for PostgreSQL with session or transaction pooling, safe connection limits, prepared-statement compatibility, monitoring and a production rollout plan.

Sunil Kumar9 min read
Network switch with connected Ethernet cables and active status lights, representing database connection infrastructure

PostgreSQL is designed to handle concurrent work, but opening a new database connection is not free. Each connection consumes server resources, participates in authentication and backend management, and can add pressure during traffic spikes. A web application that creates a connection for every request, or a fleet of workers that all maintain large local pools, can exhaust the database’s connection limit long before the CPU or storage is saturated.

PgBouncer is a lightweight connection pooler that sits between applications and PostgreSQL. It accepts many client connections and reuses a smaller number of server connections according to a pooling mode. That can make connection usage more predictable, but it also changes the lifetime of a database session. The right configuration depends on the application’s use of transactions, prepared statements, temporary tables and session state. This guide explains the trade-offs and gives a cautious production rollout plan.

Why PostgreSQL connection pooling matters

PostgreSQL’s max_connections setting limits the number of concurrent server connections. Increasing it is not a free capacity upgrade: PostgreSQL sizes some resources based directly on this setting, and more active backends can increase memory and scheduling overhead. If a service has many application replicas and each replica maintains a large pool, the total possible connections can exceed the database budget even when each individual pool looks reasonable.

For example, 12 application instances with a local pool maximum of 20 can potentially request 240 database connections. Add background workers, migration jobs, monitoring, reporting and administrative sessions, and the total can grow quickly. A connection pooler allows the application tier to keep more client connections available while limiting how many server connections are open to PostgreSQL.

Pooling does not make slow queries fast and it does not replace query tuning. If a query spends seconds waiting on disk or locks, PgBouncer cannot remove that bottleneck. It addresses connection lifecycle and reuse. For query-level performance analysis, see FutureTechie’s guide to PostgreSQL slow query troubleshooting.

Understand the three PgBouncer pooling modes

Session pooling

In session pooling, a server connection is assigned to a client for the lifetime of that client connection. When the client disconnects, the server connection returns to the pool. This is the most compatible mode because the client retains the same PostgreSQL session while connected. Features such as session-level settings, temporary tables and advisory locks behave as applications generally expect. The trade-off is that an idle client can hold a server connection even when it is not running a query.

Transaction pooling

In transaction pooling, PgBouncer assigns a server connection only while the client is inside a transaction. When the transaction ends, the server connection is returned to the pool and may be assigned to another client. This can support many more client connections than the database has server connections, especially for applications that spend time doing non-database work between short transactions.

The cost is that a client cannot assume it will receive the same PostgreSQL session for its next transaction. Session-level state, LISTEN, session advisory locks, SQL-level prepared statements and temporary tables that survive across transactions can break. The application must be compatible with this lifecycle. PgBouncer’s feature matrix documents the limitations and the options available for protocol-level prepared statements.

Statement pooling

Statement pooling releases the server connection after each statement and disallows multi-statement transactions. It is the most restrictive mode and is appropriate only for workloads that deliberately use autocommit-style single statements. Most general application backends should evaluate session or transaction pooling instead.

Choose the mode before tuning pool sizes

Do not select transaction pooling simply because it allows the largest number of clients. First inspect how the application uses the database. Search for session-level SET commands, session advisory locks, LISTEN, temporary tables, SQL-level PREPARE and features that depend on a connection remaining pinned. Test the actual framework and driver combination, not just a simple command-line query.

If the application depends on session state, start with session pooling or change the application deliberately. In transaction mode, use transaction-scoped settings such as SET LOCAL inside a transaction rather than assuming a plain SET will persist safely. Temporary tables should be created, used and dropped within the same transaction if the selected mode supports that pattern.

A minimal PgBouncer configuration example

The following example illustrates a private listener, SCRAM authentication and transaction pooling. The numbers are starting points for a test environment, not universal sizing recommendations. Store the authentication file as a protected secret and use the authentication method supported by your PostgreSQL and PgBouncer versions.

[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432

auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt

pool_mode = transaction
max_client_conn = 300
default_pool_size = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
server_idle_timeout = 600
server_reset_query = DISCARD ALL

In a real deployment, bind the listener to a private interface reachable only by approved application networks, configure TLS for connections where required, restrict access to the administrative database and protect the authentication file with strict filesystem permissions. Do not expose the PgBouncer admin console to the public internet. Keep the database password and SCRAM verifier out of source control and build logs.

The server_reset_query behavior should be checked against the selected pooling mode and PgBouncer version. Resetting session state can be useful, but it does not make an incompatible application safe for transaction pooling. Test prepared statements and driver behavior using the current PgBouncer documentation.

Size pools with the database budget in mind

max_client_conn is the maximum number of client connections PgBouncer accepts. It is not the number of server connections that PostgreSQL will receive. default_pool_size controls the server connections for each user/database pool unless a more specific setting overrides it. The total server connection budget depends on the number of distinct pools, per-database and per-user limits, reserve pools and other PgBouncer instances.

Suppose one PgBouncer process serves three databases and four database users. A pool for each user/database pair can multiply the possible server connections. Do not simply multiply default_pool_size by the application replica count and assume that is the final total. Map the actual pool keys and use max_db_connections or max_user_connections where a hard ceiling is needed. Leave room for PostgreSQL superuser and operational connections, replication, monitoring, backups and migrations.

PgBouncer’s documentation also warns that increasing max_client_conn may require a higher operating-system file-descriptor limit. The theoretical number of descriptors can exceed the client limit because server connections and other sockets also consume descriptors. Monitor the process limits and the host’s file-descriptor usage rather than treating the configuration value as an isolated setting.

Roll out PgBouncer without creating a second bottleneck

  1. Measure the current workload. Record active and idle connections, connection wait time, peak concurrency, transaction duration and database CPU/memory pressure.
  2. Check application compatibility. Identify session state, prepared statements, temporary tables, advisory locks and driver-specific behavior.
  3. Deploy one private pooler. Start with a non-production service and use a conservative server connection budget.
  4. Switch a canary application. Point one replica or worker group at PgBouncer’s port and run normal application tests.
  5. Observe both sides. Compare client connections, server connections, wait time, query latency and errors.
  6. Expand gradually. Increase traffic only after the pooler and database remain stable under realistic concurrency.
  7. Document failover. Decide how applications reconnect if PgBouncer restarts and how to prevent every client from reconnecting at once.

A common architecture uses an application-side pool plus PgBouncer. That can be valid, but the combined settings must be deliberate. If every application replica has a very large local pool, PgBouncer may simply receive a large number of idle clients and hit its own file-descriptor or memory limits. Set the application pool to match the application’s concurrency needs and let PgBouncer manage the database-side budget.

Monitor PgBouncer with its administration console

PgBouncer exposes an administrative database that supports commands such as SHOW POOLS, SHOW STATS, SHOW CLIENTS, SHOW SERVERS and SHOW CONFIG. Access it only from an approved administrative path.

psql -h 127.0.0.1 -p 6432 -U pgbouncer pgbouncer

SHOW POOLS;
SHOW STATS;
SHOW CLIENTS;
SHOW SERVERS;
SHOW CONFIG;

Look at waiting clients, active and idle server connections, transaction counts, query time and connection churn. A growing queue of waiting clients can mean the server pool is too small, the database is slow, or transactions are being held open too long. Increasing pool size without investigating can worsen database pressure. If server connections are busy for a long time, examine query plans, lock waits and transaction boundaries before changing the pooler.

Prepared statements and driver compatibility

Prepared statement behavior is a frequent source of transaction-pooling surprises. PgBouncer versions from 1.21.0 can track protocol-level prepared statements in transaction pooling when max_prepared_statements is configured to a non-zero value. This does not mean every SQL-level PREPARE/EXECUTE pattern is compatible. The feature matrix distinguishes protocol-level prepared plans from SQL-level prepared statements, and driver versions can add their own constraints.

Test the exact application driver, ORM, framework and PgBouncer release. For example, the PgBouncer FAQ documents specific PHP/PDO and JDBC considerations. If the application relies on a feature that transaction mode cannot preserve, use session pooling for that workload or change the application deliberately. Avoid silently disabling prepared statements in production without measuring the impact and checking application correctness.

Common problems and how to diagnose them

  • Too many PostgreSQL connections remain: verify that applications really connect to PgBouncer and are not bypassing it through a direct database URL.
  • Clients wait for a server connection: inspect SHOW POOLS, query duration, open transactions and the configured pool limits before increasing capacity.
  • Temporary tables or session variables disappear: check whether transaction pooling is compatible with the application’s session-state assumptions.
  • Prepared statements fail: confirm PgBouncer and driver versions, protocol-level tracking settings and whether the application uses SQL-level PREPARE.
  • Connection bursts after restart: use gradual application reconnects, backoff and health checks instead of allowing every replica to retry simultaneously.
  • File-descriptor errors: inspect PgBouncer’s process limits and host limits when increasing client capacity.
  • Latency increases after pooling: distinguish time waiting for a pool connection from query execution time and network latency.

Security and operational considerations

Keep PgBouncer on a private network, restrict which application identities can connect and use strong authentication. Treat its configuration and authentication files as production secrets. Limit administrative access and log configuration changes. If TLS is used between application, pooler and database, verify certificate validation and renewal procedures on each leg. Ensure that failover, backup and maintenance tools have a documented connection path so that a pooler outage does not prevent operators from reaching PostgreSQL.

Do not let the pooler become a single unmonitored point of failure. Run it with a tested restart strategy, health checks and a capacity plan. Depending on the application, multiple pooler instances behind a private service endpoint may be appropriate, but each instance’s server pools must be included in the total database connection budget.

Related FutureTechie guides cover database indexing, Redis caching and PostgreSQL backup and restore. Connection pooling is one part of database reliability; query efficiency, cache design and tested recovery remain separate responsibilities.

Conclusion

PgBouncer can protect PostgreSQL from connection storms and reduce the number of server connections needed for a large client population. Its benefit depends on selecting a pooling mode that matches the application, sizing pools against the total database budget and monitoring both client wait time and server-side work. Begin with a measured canary, verify driver compatibility, keep the pooler private and expand gradually. The goal is controlled connection reuse—not simply a larger connection limit.

Official documentation

Share this article

Written by

Sunil Kumar

Founder of FutureTechie and BoltPane. Writes clear explainers on AI, cybersecurity, gadgets and developer tools for curious readers who want signal over hype.

106 articles View profile

Get the tech briefing

AI, gadgets, software and cybersecurity — distilled into one short briefing every weekday.