‹ Back to Home

Scaling PostgreSQL Connections with PgBouncer: The Complete Guide for 2026

PostgreSQL's connection model can become a bottleneck at scale. PgBouncer, the lightweight connection pooler, solves this elegantly. Learn how to set it up, tune it, and avoid the common pitfalls.

Keerthika 8 min read 1,026 1
Follow on Google
Updated 2 weeks ago
Programming Scaling PostgreSQL Connections with PgBouncer: The Complete Guide for 2026 8 min left Follow on Google
Scaling PostgreSQL Connections with PgBouncer: The Complete Guide for 2026

TamilTech AI summary

When your app grows and PostgreSQL starts throwing “remaining connection slots are reserved” errors, you’ve hit a classic scaling wall: each Postgres connection is a full OS process that eats RAM and doesn’t handle thousands of clients well. PgBouncer sits between your app and the database as a lightweight connection pooler, so many client connections share a small pool of real Postgres connections and you avoid blowing past `max_connections`. For most web apps and APIs, **transaction pooling** is the sweet spot—it can cut server connections by 10–100x—while session and statement modes fit longer-lived or single-statement workloads. Setup is straightforward (install, point `pgbouncer.ini` and `userlist.txt` at your DB, then change your app’s connection string to port 6432), but you should disable prepared statements in ORMs, keep transactions short, and use a direct connection or Redis if you need `LISTEN`/`NOTIFY`. Monitor with `SHOW POOLS` so `cl_waiting` stays near zero, tune `default_pool_size`, and you’ll typically see connections drop from hundreds to dozens, lower RAM use, and fewer connection-exhaustion outages.

AI-assisted summary, checked by the TamilTech editorial team.

0:00
0:00
🔒 Listen is for subscribers. Subscribe

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 pgbouncer

CentOS / RHEL / Amazon Linux

sudo yum install pgbouncer # or with dnf sudo dnf install pgbouncer

macOS (Homebrew)

brew install pgbouncer

Docker

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.crt

userlist.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

ToolTypeBest ForOverhead
PgBouncerExternal poolerMost production use casesVery low (~1ms)
Pgpool-IIExternal pooler + proxyRead replicas, HA failoverMedium
Built-in app pool (e.g., HikariCP)In-process poolerSingle-service appsNone (same process)
RDS Proxy (AWS)Managed poolerAWS RDS / Aurora usersLow (managed)
SupavisorCloud-native poolerSupabase / multi-tenant SaaSLow

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.

Frequently asked questions

5

What is the difference between PgBouncer and built-in application connection pooling?

Application-level pools (HikariCP, pg-pool, SQLAlchemy pool) manage connections per process. In a multi-server deployment with dozens of services, each service has its own pool, all connecting directly to PostgreSQL. PgBouncer centralizes this at the infrastructure level, dramatically reducing total connections to the database regardless of how many app servers or services you run.

Which PgBouncer pool mode should I use?

Transaction pooling is best for most web applications and APIs — it gives the largest connection reduction with acceptable trade-offs. Use session pooling if your app relies on PostgreSQL features like prepared statements, advisory locks, or SET commands that don't work in transaction mode.

Does PgBouncer add latency to queries?

The overhead of PgBouncer itself is typically less than 1 millisecond when running on the same host or a nearby server. This is negligible compared to query execution time, and is offset by the massive reduction in connection overhead and memory pressure on PostgreSQL.

Can PgBouncer be used with PostgreSQL read replicas?

PgBouncer can be configured to point to a read replica, but it doesn't do automatic read/write splitting. For that you'd use Pgpool-II, or handle it at the application layer by using separate connection strings for reads and writes.

Is PgBouncer suitable for use with AWS RDS or Aurora?

Yes, PgBouncer works with RDS and Aurora. However, AWS also offers RDS Proxy as a managed alternative. RDS Proxy is easier to operate (fully managed, auto-failover aware) but costs more. PgBouncer gives more control and is free, making it popular even in AWS environments.

Get tomorrow’s tech news on WhatsApp

One short update a day, free. Follow the TamilTech channel.

What do you think?

people reacted

Keerthika

TamilTech editorial team · 3,919 articles

Keerthika is an editor at TamilTech, the Tamil and English technology publication founded by Praveen Kumar S. She covers AI, smartphones, gadgets, EVs, startups and cybersecurity i...

More from Keerthika

Ask TamilTech on WhatsApp

Tech doubt? Ask in Tamil or English — our WhatsApp assistant answers from TamilTech articles in seconds.

Related stories

Comments (0)

| Supports **bold**, *italic*, `code`

Be the first to comment!

Next story You cannot clear a coding round without Big-O
TamilTech

TamilTech

Install app for faster access

Earn XP 🏆
WhatsApp
Notifications