Scaling PostgreSQL Connections with PgBouncer: The Complete Guide for 2026
You've built a great product. Traffic is growing. And then one day, your application starts throwing errors: FATAL: remaining connection slots are reserved for non-replication superuser connections. Your PostgreSQL database has run out of connections — and your app is on fire.
This is one of the most common scaling bottlenecks teams hit with PostgreSQL, and it has a well-proven, elegant solution: PgBouncer.
In this guide, we'll explain why PostgreSQL struggles with thousands of connections, how PgBouncer solves this, how to set it up in production, and how to tune it for maximum performance.
Why PostgreSQL Struggles with Too Many Connections
PostgreSQL handles connections differently from databases like MySQL or MongoDB. Each connection in PostgreSQL spawns a dedicated backend process on the operating system. This means:
- Every connection consumes RAM (typically 5–10 MB per connection)
- The OS has to schedule and context-switch between many processes
- PostgreSQL has a hard limit (max_connections, default 100) on simultaneous connections
- Opening and closing connections is expensive — TCP handshake + process fork every time
In a modern web application, each API request might need a database connection. If you're running 50 application servers, each with a connection pool of 20 connections, you already need 1,000 simultaneous connections. Scale that to a microservices architecture with dozens of services and you can see the problem quickly.
Simply increasing max_connections to 1,000 or more is not the answer — it will actually hurt performance due to memory pressure and context switching overhead, even when most connections are idle.
What Is PgBouncer?
PgBouncer is an open-source, lightweight connection pooler for PostgreSQL. It sits between your application and PostgreSQL as a proxy, maintaining a small pool of actual database connections and serving many application connections from this pool.
Think of it like a hotel front desk. Instead of every guest having their own dedicated staff member (a connection), there's a small team (the pool) that serves all guests efficiently, one request at a time.
PgBouncer can handle thousands of client connections while keeping only a fraction of that many real connections open to PostgreSQL — dramatically reducing memory usage, process overhead, and connection churn.
PgBouncer's Three Pooling Modes
PgBouncer offers three distinct pooling strategies. Choosing the right one is critical.
1. Session Pooling
A server connection is assigned to a client connection for the full duration of the client's session. The connection is only returned to the pool when the client disconnects.
Best for: Applications that use long-lived connections (e.g., desktop applications, BI tools)
Connection savings: Minimal — mainly reuses connections across reconnects
PostgreSQL feature support: Full — all features work including prepared statements, advisory locks, SET commands
2. Transaction Pooling
A server connection is assigned only for the duration of a transaction. Once the transaction ends (COMMIT or ROLLBACK), the connection goes back to the pool immediately.
Best for: Web applications, APIs, microservices — the sweet spot for most teams
Connection savings: Excellent — 10-100x reduction in required server connections
Limitation: Some PostgreSQL features don't work (prepared statements, SET commands, advisory locks, LISTEN/NOTIFY)
3. Statement Pooling
A server connection is assigned only for a single SQL statement. After each statement, the connection is returned to the pool.
Best for: Very specific use cases with single-statement workloads
Limitation: Multi-statement transactions are not supported — not suitable for most applications
Recommendation for most teams: Start with transaction pooling. It gives the best connection reduction with acceptable limitations for typical web workloads.
Installing PgBouncer
PgBouncer is available in most Linux package managers and is trivial to install.
Ubuntu / Debian
sudo apt update sudo apt install pgbouncerCentOS / RHEL / Amazon Linux
sudo yum install pgbouncer # or with dnf sudo dnf install pgbouncermacOS (Homebrew)
brew install pgbouncerDocker
docker pull bitnami/pgbouncer
Configuring PgBouncer
PgBouncer is configured via two files: pgbouncer.ini (main config) and userlist.txt (credentials).
pgbouncer.ini — Core Configuration
[databases] ; Format: alias = host=... port=... dbname=... myapp_db = host=127.0.0.1 port=5432 dbname=myapp [pgbouncer] ; Listen on all interfaces, port 6432 (PgBouncer default) listen_addr = 0.0.0.0 listen_port = 6432 ; Authentication auth_type = md5 auth_file = /etc/pgbouncer/userlist.txt ; Pooling mode — transaction is recommended for web apps pool_mode = transaction ; Maximum connections PgBouncer will open to PostgreSQL max_db_c 100 ; Maximum client connections PgBouncer will accept max_client_c 1000 ; Pool size per (database, user) pair default_pool_size = 20 ; Extra connections to allow before queueing reserve_pool_size = 5 reserve_pool_timeout = 3 ; Kill idle server connections after this many seconds server_idle_timeout = 600 ; Kill idle client connections after this many seconds client_idle_timeout = 0 ; Administrative interface admin_users = pgbouncer_admin stats_users = stats ; Logging logfile = /var/log/pgbouncer/pgbouncer.log pidfile = /var/run/pgbouncer/pgbouncer.pid ; TLS (recommended for production) ;server_tls_sslmode = require ;server_tls_ca_file = /etc/ssl/certs/ca-certificates.crtuserlist.txt — User Credentials
PgBouncer needs to know the passwords of the users connecting through it. Store them as MD5 hashes (or SCRAM in newer versions):
"myapp_user" "md5" "pgbouncer_admin" "md5"
To generate an MD5 hash for PgBouncer:
echo -n "passwordusername" | md5sum | awk '{print "md5" $1}'
Alternatively, use auth_query to let PgBouncer fetch credentials directly from PostgreSQL — more secure and easier to manage:
; In pgbouncer.ini auth_type = md5 auth_query = SELECT usename, passwd FROM pg_shadow WHERE usename=$1 auth_user = pgbouncer_auth_user
Starting PgBouncer
Start as systemd service sudo systemctl start pgbouncer sudo systemctl enable pgbouncer # Or manually pgbouncer -d /etc/pgbouncer/pgbouncer.ini # Verify it's running psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW POOLS;"
Connecting Your Application Through PgBouncer
Simply change your application's database connection string to point to PgBouncer instead of PostgreSQL directly:
Before (direct PostgreSQL) DATABASE_URL=postgresql://myapp_user:password@db-host:5432/myapp # After (via PgBouncer) DATABASE_URL=postgresql://myapp_user:password@pgbouncer-host:6432/myapp_db
That's it. Your application doesn't know it's talking to PgBouncer — it looks like a regular PostgreSQL server.
Key Tuning Parameters
Getting the most out of PgBouncer requires tuning these parameters for your workload:
Monitoring PgBouncer
Connect to PgBouncer's admin console to monitor it in real time:
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -- Show all pools and their stats SHOW POOLS; -- Show all client connections SHOW CLIENTS; -- Show server connections to PostgreSQL SHOW SERVERS; -- Show aggregate statistics SHOW STATS; -- Reload config without restart RELOAD;
The most important columns in SHOW POOLS:
- cl_active: Clients currently executing queries
- cl_waiting: Clients waiting for a server connection (should be near 0)
- sv_active: Server connections in use
- sv_idle: Server connections available in the pool
If cl_waiting is consistently above 0, your pool is under-sized — increase default_pool_size.
Common Pitfalls and How to Avoid Them
1. Prepared Statements Break in Transaction Pooling Mode
Many ORMs (ActiveRecord, SQLAlchemy, Hibernate) use prepared statements by default. In transaction pooling mode, a prepared statement created on one server connection may not exist on the next connection you get.
Fix: Disable prepared statements in your ORM or application driver.
- Rails: Add prepared_statements: false to database.yml
- SQLAlchemy: Use use_native_hstore=False and disable statement caching
- Node.js (pg): Avoid client.prepare() calls
- Django: Set OPTIONS: {"options": "-c default_transactioff"} — or use session pooling
2. SET Commands and Session Variables Don't Persist
In transaction pooling, SET search_path, SET timezone, and similar session-level commands don't persist across transactions because the underlying connection changes.
Fix: Use the server_reset_query config option or set these at the database/role level instead of at session level.
3. LISTEN/NOTIFY Doesn't Work
PostgreSQL's pub/sub mechanism requires a dedicated connection. In transaction pooling, this isn't possible.
Fix: Maintain a separate, direct PostgreSQL connection (bypassing PgBouncer) for LISTEN/NOTIFY. Many applications use Redis pub/sub for this instead.
4. Long-Running Transactions Holding Pool Connections
A transaction that stays open for a long time (e.g., fetching data and processing before committing) holds a server connection in the pool, starving other clients.
Fix: Keep transactions short. Process data outside transactions where possible. Use server_check_delay and monitor sv_active for long-held connections.
PgBouncer vs Alternatives
| Tool | Type | Best For | Overhead |
|---|---|---|---|
| PgBouncer | External pooler | Most production use cases | Very low (~1ms) |
| Pgpool-II | External pooler + proxy | Read replicas, HA failover | Medium |
| Built-in app pool (e.g., HikariCP) | In-process pooler | Single-service apps | None (same process) |
| RDS Proxy (AWS) | Managed pooler | AWS RDS / Aurora users | Low (managed) |
| Supavisor | Cloud-native pooler | Supabase / multi-tenant SaaS | Low |
Production Architecture: Where to Run PgBouncer
There are two common deployment patterns:
1. PgBouncer on the application server (sidecar)
Run PgBouncer on the same host as each application server. Each app connects to localhost:6432. This reduces network latency but means more PgBouncer instances to manage.
2. PgBouncer as a dedicated proxy tier
Run one or more PgBouncer instances on dedicated hosts between app servers and the database. Simpler to manage but adds a network hop. Use HAProxy or a load balancer in front of multiple PgBouncer instances for HA.
For most startups and mid-size companies, option 2 with a single PgBouncer instance is the right starting point. Add redundancy (two PgBouncer instances behind a load balancer) once you need it.
Real-World Impact: Numbers to Expect
Here's what teams typically see after adding PgBouncer with transaction pooling:
- PostgreSQL connections: 500+ → 20–50 (90%+ reduction)
- PostgreSQL RAM usage: significantly reduced (fewer idle processes)
- Connection open time: near zero (reusing pooled connections)
- Query throughput: 2–5x improvement under high concurrency
- Application errors from connection exhaustion: eliminated
Conclusion
PostgreSQL is one of the most powerful and reliable databases in the world, but its process-per-connection model means connection pooling is not optional at scale — it's essential. PgBouncer is the industry-standard solution: battle-tested, extremely lightweight, and trusted by companies like GitLab, Shopify, and Notion.
The setup takes under an hour. The performance gains are immediate and dramatic. If you're running PostgreSQL in production and haven't added PgBouncer yet, there's no better time than today.




Comments (0)
Be the first to comment!