You run pgBouncer in transaction-pooling mode in front of a Patroni cluster. A controlled switchover takes 6 seconds at the database layer but the application sees a 90-second outage because half the pooler’s server connections are stuck mid-transaction against the demoted primary. The transactions never commit, the clients never get a response, and pgBouncer’s pool fills with orphans until idle_transaction_timeout finally fires. The cluster did its job. The pooler in front of it forwarded the failover into the application as a long, ugly hang. The fix is to teach pgBouncer to participate in the failover, not just to watch it happen.
What’s happening
pgBouncer in transaction-pooling mode multiplexes many client connections onto a small pool of server connections. Each client gets a server connection only for the duration of a transaction; between transactions the server connection is returned to the pool. This is what makes pgBouncer good at handling thousands of cheap clients in front of a few hundred Postgres backends.
The problem during failover: at the instant the writer flips, some of those server connections are mid-transaction. They’re holding locks, they’re waiting on a query result, or they’re parked in idle in transaction between a client’s BEGIN and the next statement. None of them can be safely closed without rolling back work. So pgBouncer does the only thing it can — it waits. It waits for the dead primary to respond, hits server_check_query timeouts after query_timeout seconds (default: 0, meaning never), and only then closes the socket.
Meanwhile, new client requests pile up. New backend connections are attempted against the still-cached old writer IP. Application drivers time out and surface 500s to end users.
The cluster-aware pattern is three changes:
- PAUSE pgBouncer at the start of failover, RESUME after. PAUSE drops all server connections cleanly (after current transactions finish or fail), holds client connections in a queue, and re-establishes server pools against whatever the underlying routing now says is the writer.
- Set
idle_transaction_timeoutandquery_timeout. These cap how long a stuck transaction can hold a server connection hostage. Without them the pool fills with orphans. - Use a TCP router (HAProxy) between pgBouncer and Postgres, not direct DSN. pgBouncer doesn’t natively know which Patroni node is the leader. HAProxy queries Patroni’s
/masterendpoint and routes accordingly. pgBouncer talks to HAProxy on a stable IP; HAProxy hides the leader changes from pgBouncer.
With all three in place, a 6-second cluster switchover produces a 6-10 second pgBouncer pause and zero stranded sessions.
How to verify
What state is pgBouncer in right now?
# Open the admin console (pgbouncer is the special "database" name)
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer
# In the prompt:
SHOW POOLS;
# Look at sv_active, sv_idle, sv_used, sv_tested, sv_login, maxwait
# sv_active = transactions in progress on a backend
# maxwait = oldest client waiting for a server (seconds)
SHOW SERVERS;
# Each backend row. state = active / idle / used / tested / login / new
SHOW CLIENTS;
# Each client row. state = active / idle / waiting
A healthy steady state has sv_active rising and falling with traffic, sv_idle non-zero (pooled and ready), maxwait = 0. Anything above 1-2 seconds on maxwait for any pool means clients are stuck waiting for a server — that’s the failover hang surfacing.
Test the pause/resume manually before you need it:
# Pause everything
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "PAUSE;"
# All server connections drained after their current transactions complete
# Clients can still connect; their queries queue
# At this point, you can take the cluster down for whatever
# When the cluster is back:
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "RESUME;"
# Server pools re-establish, queued client queries flow through
Run a quick before/after sanity check:
# Before
psql -h <pgbouncer> -p 6432 -d app -c "SELECT now(), pg_backend_pid();"
# Pause
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "PAUSE;"
# This query will hang waiting for resume — that's the test
( psql -h <pgbouncer> -p 6432 -d app -c "SELECT 'after-pause';" ) &
# Resume — the hanging query should return immediately
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "RESUME;"
The fix
Step 1 — Configure idle-in-transaction protection on both sides
In Postgres (on every cluster node, via Patroni’s dcs.postgresql.parameters):
parameters:
idle_in_transaction_session_timeout: '60s' # PG kills a session idle in tx for 60s
statement_timeout: '120s' # PG kills any single statement at 120s
lock_timeout: '5s' # PG aborts a stmt waiting for a lock for 5s
In pgBouncer (/etc/pgbouncer/pgbouncer.ini):
[pgbouncer]
# How long a server connection can be held idle inside a transaction.
# After this, pgBouncer closes the server connection (and the client transaction is rolled back).
idle_transaction_timeout = 60
# How long a single query against a backend can run.
# After this, pgBouncer closes the server connection.
query_timeout = 120
# How long pgBouncer waits for a client to start sending a query after receiving a server connection.
# Catches buggy applications that hold pool slots open without doing work.
client_idle_timeout = 0 # 0 = unlimited; set to 600+ if you have noisy clients
# Server-side check before handing a pooled connection to a client.
server_check_query = ';' # cheapest possible
server_check_delay = 30 # check idle connections every 30s
server_lifetime = 3600 # close & recycle every hour even if healthy
server_idle_timeout = 600 # close if idle in pool > 10 min
Reload pgBouncer:
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "RELOAD;"
Step 2 — Configure pgBouncer to talk to HAProxy, not directly to Patroni nodes
This is the single most important change. pgBouncer pointed at one specific Postgres IP will continue trying to connect to that IP across failover. Pointed at HAProxy, it follows whatever HAProxy says is the writer.
[databases]
# WRONG — direct connection, breaks on failover
# app = host=10.10.0.11 port=5432 dbname=app
# RIGHT — connection through HAProxy's write-only frontend on localhost
app = host=127.0.0.1 port=5000 dbname=app
# If you have a read-replica pool, route it through HAProxy's read frontend
app_ro = host=127.0.0.1 port=5001 dbname=app
HAProxy’s postgres_write backend uses option httpchk OPTIONS /master against each node’s Patroni REST API (port 8008). Only the current leader returns HTTP 200 on /master. HAProxy converges within inter * fall seconds (typically 9-10s).
Step 3 — Wire pgBouncer into the Patroni callback
Patroni supports callbacks on cluster-state transitions: on_start, on_stop, on_restart, on_role_change. Add a callback that pauses pgBouncer when the local node demotes and resumes when it promotes.
In patroni.yml:
postgresql:
callbacks:
on_role_change: /usr/local/bin/pgbouncer-failover-callback.sh
Create the callback script /usr/local/bin/pgbouncer-failover-callback.sh:
#!/usr/bin/env bash
# Patroni passes: $1=action ($2=role) $3=cluster
# Actions: on_start | on_stop | on_restart | on_role_change
# Roles: master | replica
ACTION="$1"
ROLE="$2"
CLUSTER="$3"
PGBOUNCER_HOST="127.0.0.1"
PGBOUNCER_PORT="6432"
PGBOUNCER_DB="pgbouncer"
PGBOUNCER_USER="pgbouncer_admin"
PGPASSWORD_FILE="/etc/pgbouncer/.admin_pgpass"
log() { logger -t pgbouncer-callback "$@"; }
case "$ACTION" in
on_role_change)
case "$ROLE" in
master)
log "promoted to master — RESUME pgBouncer pools"
PGPASSFILE="$PGPASSWORD_FILE" psql \
-h "$PGBOUNCER_HOST" -p "$PGBOUNCER_PORT" \
-U "$PGBOUNCER_USER" -d "$PGBOUNCER_DB" \
-c "RESUME;" 2>&1 | logger -t pgbouncer-callback
;;
replica)
log "demoted to replica — PAUSE pgBouncer pools"
PGPASSFILE="$PGPASSWORD_FILE" psql \
-h "$PGBOUNCER_HOST" -p "$PGBOUNCER_PORT" \
-U "$PGBOUNCER_USER" -d "$PGBOUNCER_DB" \
-c "PAUSE;" 2>&1 | logger -t pgbouncer-callback
# Wait 15s for HAProxy to converge, then resume so reads can flow
( sleep 15 && PGPASSFILE="$PGPASSWORD_FILE" psql \
-h "$PGBOUNCER_HOST" -p "$PGBOUNCER_PORT" \
-U "$PGBOUNCER_USER" -d "$PGBOUNCER_DB" \
-c "RESUME;" ) &
;;
esac
;;
esac
Make it executable and restart Patroni so it picks up the callback:
sudo chown postgres:postgres /usr/local/bin/pgbouncer-failover-callback.sh
sudo chmod 700 /usr/local/bin/pgbouncer-failover-callback.sh
sudo systemctl restart patroni
Step 4 — Test under load
Run synthetic write traffic, trigger a switchover, watch the pool:
# Terminal 1 — synthetic load
while true; do
if psql -h pgbouncer.internal -p 6432 -U app -d app -c \
"INSERT INTO drill_heartbeat(ts) VALUES (now())" >/dev/null 2>&1; then
echo "$(date -Iseconds) ok"
else
echo "$(date -Iseconds) FAIL"
fi
sleep 1
done
# Terminal 2 — pgBouncer pool stats
watch -n 1 'psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW POOLS;"'
# Terminal 3 — trigger
patronictl -c /etc/patroni/patroni.yml switchover --force
Expected on Terminal 1: 3-6 FAIL lines, then back to ok. Without the pause/resume wiring, you’ll see 30-60 FAIL lines.
Step 5 — Watch for the failure modes
Three things to alert on:
-- 1. Long-running idle-in-transaction sessions on the primary
SELECT pid, usename, application_name, state,
now() - state_change AS state_age,
query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
AND now() - state_change > interval '30 seconds';
# 2. pgBouncer pool maxwait > 0 sustained
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW POOLS;" \
| awk '$8 > 0 {print}'
# 3. HAProxy and pgBouncer have different opinions about who the writer is
# Compare:
echo "show stat" | socat stdio /run/haproxy/admin.sock \
| awk -F, '$1=="postgres_write" && $18=="UP" {print $2}'
# vs the IP pgBouncer's pool is currently using
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW SERVERS;" \
| awk '/active/ {print $4}'
If HAProxy and pgBouncer disagree for more than 30 seconds, something is wrong with the health check or the callback. A scripted alert here is worth the noise.
For the full HA stack — Patroni + etcd + HAProxy + pgBouncer wired to fail over in under 15 seconds — we operate this on Cloud Compute as part of Managed Cloud Ops. Start a scoping call if you’d like us to take the pooling layer over.