To configure PostgreSQL connection pooling, place a pooler between your application and database, cap its backend connections, and route application traffic through it. For typical SaaS APIs, transaction pooling lets many application connections share fewer PostgreSQL connections.
This helps when web replicas, workers, or serverless functions compete for database capacity. Start by choosing who operates the pooler, then size and test it against your application’s transaction behavior.
Key Takeaways
- Use a managed pooler when it meets your compatibility and operational needs; choose PgBouncer when you need configuration control.
- Budget database connections across every pooler instance, application role, and deployment.
- Keep transactions short, establish tenant context inside each transaction, and test prepared statements through the pooled endpoint.
1. Choose PgBouncer or Your Provider’s Pooler
PostgreSQL creates a backend process for each connection. Opening connections repeatedly adds overhead, while excessive concurrent connections consume resources and increase contention.
An application-side pool reuses connections within one process. However, each replica maintains its own pool, so scaling the application can still overwhelm PostgreSQL.
Use a managed pooler for simpler operations
A provider-managed pooler removes the need to deploy, patch, and monitor a separate proxy service. It also provides a pooled endpoint alongside your database connection details.
Supabase, for example, distinguishes pooler client limits from backend connection limits. Its connection pooling documentation explains that shared and dedicated poolers apply their limits independently.
Choose this route when the available pooling mode supports your driver and transaction requirements. Provider poolers don’t all expose the same settings or session behavior.
Run PgBouncer when you need control
PgBouncer lets you configure pool sizes, authentication, timeouts, and pooling modes directly. It’s useful for self-managed PostgreSQL or workloads needing settings a managed endpoint doesn’t expose.
However, your team owns availability and upgrades. A single PgBouncer instance can become an outage point, even when PostgreSQL remains healthy.
2. Select the Right Pooling Mode
Pooling mode determines when another client can reuse a database connection.
| Mode | Backend connection assignment | Suitable workload |
|---|---|---|
| Session | Until the client disconnects | Applications requiring persistent session state |
| Transaction | Until the transaction completes | Short API requests and background jobs |
| Statement | Until each statement completes | Autocommit-only workloads |
Transaction mode is usually the practical starting point for SaaS request traffic. An explicit transaction stays on one backend connection until COMMIT or ROLLBACK.
Session mode offers broader compatibility. However, long-lived application connections can keep backend connections occupied even while idle.
Statement mode disallows transactions spanning multiple statements. That makes it unsuitable for common operations such as updating an account and recording its audit event atomically.
With transaction pooling, avoid relying on session-level settings, temporary tables that must survive transactions, or persistent LISTEN subscriptions. Give workloads requiring these features a separate session-pooled or direct connection path.
3. Set a Database Connection Budget
First, inspect PostgreSQL’s configured ceiling:
SHOW max_connections;
Treat that ceiling as a safety boundary rather than a performance target. More active database connections don’t automatically produce higher throughput.
Reserve capacity outside the pool
For a database configured with 100 connections, a starting budget might allocate 60 to application poolers. Leave the remainder for reserved slots, administration, migrations, monitoring, and other direct clients.
These are example allocations, not universal sizing rules. Database CPU, memory, query duration, and concurrent work determine the useful pool size.
Also account for rolling deployments, when old and new application replicas overlap.
Count pools and pooler instances
PgBouncer’s default_pool_size applies per database/user pair. Therefore, additional application roles or databases can multiply backend connections.
Meanwhile, max_client_conn limits connections into PgBouncer, not connections into PostgreSQL.
A max_db_connections = 60 limit applies within one PgBouncer instance. Two instances configured that way can collectively request 120 database connections. Divide the shared budget across instances.
Start conservatively, then increase backend concurrency only when load tests show better throughput without unacceptable database pressure.
4. Configure a Basic PgBouncer Service
This example assumes PostgreSQL, an existing saas database, and a restricted saas_app login on the same host.
On Debian or Ubuntu, install the packages:
sudo apt-get install pgbouncer postgresql-client
Edit /etc/pgbouncer/pgbouncer.ini:
[databases]
saas = host=127.0.0.1 port=5432 dbname=saas
[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 = 200
default_pool_size = 20
max_db_connections = 60
max_prepared_statements = 100
query_wait_timeout = 5
Here, default_pool_size allows 20 backend connections per database/user pool. The database-wide cap is 60, while up to 200 clients can connect to PgBouncer.
query_wait_timeout limits backend-assignment waits to five seconds. max_prepared_statements enables protocol-level named prepared-statement tracking, discussed below. PgBouncer’s configuration reference documents these settings.
Configure authentication safely
Using an authorized PostgreSQL administrator, retrieve the application’s existing SCRAM verifier:
SELECT rolpassword
FROM pg_authid
WHERE rolname = 'saas_app';
In userlist.txt, put "saas_app" followed by the complete verifier, also double-quoted, on one line. Protect this file as a credential.
For SCRAM backend authentication with this setup, the verifier must match PostgreSQL’s stored verifier. PostgreSQL’s authentication rules must also permit the connection.
Start the service privately
Restrict configuration and credential-file access to administrators and PgBouncer’s service account. Then restart:
sudo systemctl restart pgbouncer
This configuration listens only on loopback. For separate hosts, use private networking and configure TLS independently for both connection legs. Never expose an unprotected pooler publicly.
5. Route Application Traffic Through PgBouncer
Change the application’s host and port to PgBouncer while preserving its database name and login.
For the local setup:
psql -h 127.0.0.1 -p 6432 -U saas_app -d saas
-c 'SELECT current_database(), current_user;'
The command prompts for the password instead of placing it in shell history.
A local connection URI can omit the password:
postgresql://saas_app@127.0.0.1:6432/saas
Supply the password through your application’s secret-management mechanism. PostgreSQL’s connection parameter documentation explains URI syntax and SSL options for libpq-compatible clients.
Retain a small, bounded application-side pool rather than opening unlimited connections. Its connections now terminate at PgBouncer, but they still consume client slots and file descriptors.
Keep migrations and session-dependent jobs on a separately budgeted direct or session-pooled connection. Finally, deploy the endpoint change gradually, because old application instances can keep existing direct connections open.
6. Handle Prepared Statements and Tenant State
Transaction pooling changes which backend handles each transaction. Application correctness must therefore survive backend reuse.
Distinguish prepared-statement mechanisms
PgBouncer 1.21 introduced support for protocol-level named prepared statements in transaction pooling. A nonzero max_prepared_statements enables this tracking; the example configures 100 cached statements per backend connection.
However, SQL commands such as PREPARE and EXECUTE aren’t covered by that tracking. They depend on backend session state.
Test the actual ORM and driver configuration through the pooler. If its preparation mechanism isn’t compatible, disable that mechanism or route the workload through session pooling.
Keep tenant context transaction-local
For row-level security, authenticate the caller and authorize tenant membership before accessing tenant-owned data.
Then begin a transaction on one checked-out application connection. Execute parameterized SELECT set_config('app.tenant_id', $1, true), run the protected queries through that same transaction, and commit.
The final true makes the setting transaction-local. A standalone autocommit call loses that setting before the next query.
Also avoid establishing tenant identity at session scope elsewhere. Transaction-local settings restore previous values when the transaction ends.
On errors, roll back before releasing the connection. Use a restricted application role without superuser or BYPASSRLS privileges, and keep application permission checks.
7. Test Load and Monitor Waiting Clients
A successful connection test proves authentication and routing work. It doesn’t prove the pool can support production traffic.
Exercise realistic concurrency
Run staging load tests through the pooled endpoint using representative application operations. Include API requests, workers, and deployment overlap.
Measure request throughput, p95 latency, connection-acquisition time, and timeout rates. Increase concurrent requests gradually so you can identify where queueing begins.
Test rollback after query errors and reuse across different tenants. Confirm that tenant context disappears after commit or rollback.
Also test slow transactions, database restarts, and interrupted connections. If a connection fails during a write, a retry needs application-level idempotency because the original transaction might have committed.
Inspect both pooling layers
Create a separate monitoring identity in PgBouncer’s authentication file and list it under stats_users. Connect that identity to PgBouncer’s administrative database, named pgbouncer.
Useful commands include:
SHOW POOLS;
SHOW STATS;
SHOW CLIENTS;
SHOW SERVERS;
PgBouncer’s administrative command documentation explains these views. Watch waiting clients, active server connections, and transaction duration alongside PostgreSQL CPU and query latency.
Long-running or idle transactions retain backend connections. Keep external HTTP calls outside database transactions, and configure appropriate statement_timeout and idle_in_transaction_session_timeout values for application roles.
If clients queue while database resources remain available, more backend connections may help. If PostgreSQL is saturated, optimize queries or reduce concurrency before enlarging the pool.
Frequently Asked Questions
Does every SaaS application need PgBouncer?
No. A small deployment with bounded application pools can run comfortably without a separate pooler. Pooling becomes more useful when replicas, workers, or serverless instances create excessive database connections.
Can pooling fix slow queries?
Pooling reduces connection overhead and controls database concurrency. However, it doesn’t repair missing indexes or expensive queries. Raising pool sizes can worsen performance when more queries compete for the same database resources.
Keep the Pool Bounded and Transactions Short
Reliable PostgreSQL connection pooling starts with a shared connection budget and a mode your application supports. A managed endpoint or PgBouncer can provide that boundary, but neither removes transaction and authorization requirements.
Start with a conservative pool, route traffic gradually, and measure waiting time alongside database load. Keep tenant state transaction-local so connection reuse remains safe across customers.