Sub topic 14
Where to run PgBouncer and how to keep it available
This chapter assumes you can write a working pgbouncer.ini, know the pool modes, and understand how default_pool_size relates to PostgreSQL's max_connections. It covers where to put PgBouncer in your network and what happens when it or the database fails.
PgBouncer is a new single point of failure
Once every application connects through PgBouncer, PgBouncer is on the critical path. If it stops, the application loses the database even though PostgreSQL is healthy. Two decisions follow from this:
- Where the process runs, which affects latency, connection counts, and the blast radius of a failure.
- How many instances you run and how clients find a healthy one.
PgBouncer itself is light. It uses one thread per process and holds little state, so replacing an instance is cheap. The state it does hold, the open server connections, rebuilds on demand. Availability mostly comes down to running more than one instance and routing around dead ones.
Placement options
| Placement | How it works | Strengths | Weaknesses |
|---|---|---|---|
| On each application host (sidecar) | Apps connect to `127.0.0.1:6432` or a Unix socket | No extra network hop for clients. A failure affects only one host. No load balancer needed. | Pools are not shared across hosts, so total server connections grow with the host count. Config is deployed everywhere. |
| On the database host | PgBouncer runs next to PostgreSQL | One place to configure. Pool-to-server hop is local. | Takes CPU from the database. Dies with the host. Clients cross the network on every connection, including TLS setup. |
| Dedicated middle tier | One or more PgBouncer hosts between apps and PostgreSQL | One shared pool for all apps. Easy to scale and replace. | An extra hop. Needs a load balancer or virtual IP for availability. |
There is no universally right answer. Use these rules of thumb:
- A small number of long-lived application hosts and a strong need for simplicity favors sidecars.
- Many short-lived clients (serverless functions, autoscaled containers) favors a middle tier, because a shared pool is the only way to cap server connections.
- Running PgBouncer on the database host is acceptable for small setups, but it fails together with the database.
Count connections across instances
Each PgBouncer instance keeps its own pools. The limit default_pool_size applies per user and database pair, per instance. The worst case on the PostgreSQL side is:
server connections = instances x pairs x (default_pool_size + reserve_pool_size)With four sidecars, one pair, and the sample settings of 20 plus 5, PostgreSQL could see up to 100 connections from PgBouncer alone. Add the connections that bypass PgBouncer (admin tools, replication, monitoring) and compare the total with max_connections. If the total does not fit, lower default_pool_size per instance or use fewer, larger instances. Setting max_db_connections caps connections to one database per instance, which is a useful guard when many pairs exist.
A highly available middle tier
The usual layout puts two or more PgBouncer hosts behind a TCP load balancer. The balancer only forwards bytes and health-checks the backends, so it must work at layer 4, not parse HTTP.
Here is an HAProxy configuration for this layout. It health-checks by opening a TCP connection to each PgBouncer:
defaults
mode tcp
timeout connect 5s
timeout client 30m
timeout server 30m
listen pgbouncer
bind *:6432
balance leastconn
option tcp-check
server pgb1 10.0.1.11:6432 check inter 2s fall 3 rise 2
server pgb2 10.0.1.12:6432 check inter 2s fall 3 rise 2Points to watch:
- Timeouts. The balancer's idle timeouts must be longer than PgBouncer's
client_idle_timeoutandserver_idle_timeout. Otherwise the balancer silently drops connections that PgBouncer still considers open, and applications see random resets. - Balancing method.
leastconnspreads long-lived connections better than round robin. - Health check depth. A TCP check proves the port accepts connections. It does not prove PgBouncer can reach PostgreSQL. A deeper check runs a real query through the pool, which also exercises authentication and the server side:
#!/bin/sh
# Exit 0 only if PgBouncer can run a query on the database behind it.
PGCONNECT_TIMEOUT=3 psql -h 127.0.0.1 -p 6432 -U app_user -d appdb \
-tAc 'SELECT 1' >/dev/null 2>&1Run this from a check agent or a script the balancer can call. Be careful with deep checks: if PostgreSQL is down, every PgBouncer fails its check and the balancer has no backend left. That is usually the correct outcome, but make sure your alerts distinguish "database down" from "pooler down".
A virtual IP managed by Keepalived is an alternative to a balancer. It gives active/passive failover with one address, at the cost of not sharing load between the two hosts.
Using more than one core on a host
PgBouncer is single-threaded, so one process saturates a single CPU core. If a host has spare cores and one process is the bottleneck (visible as a core at 100% while SHOW POOLS shows clients waiting), run several processes. Setting so_reuseport = 1 lets multiple processes listen on the same TCP port on Linux, and the kernel distributes incoming connections between them. Each process needs its own pidfile, logfile, and unix_socket_dir.
Two consequences follow:
- Each process has its own pools, so the connection arithmetic above applies per process.
- A query cancel request arrives on a new connection that the kernel may route to a different process than the one holding the target connection. Recent PgBouncer versions provide a peering feature (
peer_idand a[peers]section) so processes can forward cancels to each other. Check the documentation for your version before relying on it.
Planned maintenance without errors
PgBouncer has commands that make routine work less disruptive. Run them in the admin console:
RELOADre-readspgbouncer.iniwithout dropping clients. If you changed a[databases]entry, server connections made with the old settings are closed once they become idle, and new ones use the new settings.PAUSEstops handing out server connections and waits for active transactions to finish. Once it returns, no queries reach PostgreSQL, so you can restart or fail over the database. Clients stay connected and their new queries wait.RESUMElets them continue.RECONNECTmarks all server connections for replacement. Use it after a DNS or address change when you do not want to wait for connections to age out.SHUTDOWN WAIT_FOR_CLIENTS(in newer versions) stops accepting new clients and exits once existing ones leave. Use it to drain an instance behind a balancer before upgrading it.
A typical rolling upgrade of a two-instance tier is: take instance 1 out of the balancer, drain it, upgrade and start it, wait for its health check to pass, then repeat for instance 2. Applications keep working because the other instance carries the load. Reconnecting clients find the other instance through the balancer.
Failover of the database behind PgBouncer
When PostgreSQL fails over to a standby, PgBouncer must find the new primary. Three approaches exist:
- Point at a stable name that follows the primary. Use a DNS name, a virtual IP, or a Patroni-aware HAProxy endpoint as the
hostin[databases]. PgBouncer re-resolves DNS names, anddns_max_ttlbounds how long it caches a result. - Edit the config and
RELOAD. This is simple, but someone or something must do it during the incident. - Run PgBouncer next to your failover tool so the tool updates the config and reloads as part of promotion.
[databases]
; Stable name that always resolves to the current primary
appdb = host=primary.db.internal port=5432 dbname=appdb
[pgbouncer]
dns_max_ttl = 15
server_lifetime = 3600
server_check_delay = 30
server_login_retry = 3After the old primary goes away, its server connections break. PgBouncer discards them, and clients that were mid-transaction receive an error. That is unavoidable, so applications need retry logic for the failed transaction. Clients that were idle between transactions often notice nothing under transaction pooling, because the next transaction gets a fresh server connection. If the name still points at the old host, new connections fail until the name updates, and clients queue and eventually hit query_wait_timeout. This is why the DNS TTL and the failover tool's update speed matter.
What to monitor for availability
For each instance, alert on:
- The process being up and answering a real query, using the check script above.
cl_waitinginSHOW POOLSstaying above zero for more than a few seconds, which means the pool is too small or the database is slow.maxwaitgrowing, which shows how long the oldest waiting client has been queued.- The count of server connections across all instances approaching
max_connections.
Also keep the same pgbouncer.ini on every instance, managed by configuration management. Instances that drift apart produce errors that depend on which instance a client happened to reach, which is hard to debug.
Exercise
You run three PgBouncer sidecars, one per application host. Each has default_pool_size = 30 and reserve_pool_size = 5, and all three serve one user and database pair. PostgreSQL has max_connections = 100, and 10 connections are reserved for administrators and monitoring. Is this safe in the worst case? What would you change?
Show answer
The worst case is 3 x (30 + 5) = 105 server connections from PgBouncer, which exceeds the 90 available (100 minus 10 reserved). Under a traffic spike the reserve pool could push PostgreSQL to refuse connections. Lower the per-instance values, for example default_pool_size = 25 and reserve_pool_size = 3, which gives 3 x 28 = 84, or move to a shared middle tier so one pool serves all hosts.