Jarwis.ClusterOps

Blog

PgBouncer in front of Patroni: connection pooling that keeps working after a failover

Jarwis Team · · 6 min read · PostgreSQL, Patroni, Pgbouncer

The most common PostgreSQL outage we see in small and mid-sized teams is not a crash. It is FATAL: sorry, too many clients already, usually at the moment traffic goes up and a few dozen application pods each open their own pool. The database has CPU to spare. It just cannot take another connection.

A connection pooler fixes this, and PgBouncer is the one most teams reach for. Putting it in front of a Patroni cluster adds a second problem: after a switchover or failover, the pooler has to find the new leader. This post covers both: how to size and configure PgBouncer, and how to make it follow the leader.

Why connections are expensive in PostgreSQL

PostgreSQL forks one backend process per client connection. Each backend has its own memory, and every active one competes for the same cores and the same lock manager. Raising max_connections to 2000 does not give you 2000 concurrent queries. It gives you 2000 processes, most of them idle, and a scheduler that works harder than it needs to.

Check what you have right now:

SELECT state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY count(*) DESC;

If most rows say idle, the application is holding connections it is not using. That is exactly what a pooler is for: many client connections in front, a small number of server connections behind.

Pool modes: pick the one your application can live with

PgBouncer has three pool modes. Two matter in practice.

  • transaction gives the server connection back after each transaction. It multiplexes best and is the right default for most web workloads.
  • session holds the server connection for the whole client session. Use it when the application depends on session state.

Session state is what breaks in transaction mode. Temporary tables, SET without LOCAL, session-level advisory locks, LISTEN/NOTIFY and WITH HOLD cursors all assume the next statement lands on the same backend. If you rely on any of them, either use session mode for that application or change the code.

Prepared statements need a separate note. Protocol-level prepared statements historically did not work in transaction mode. PgBouncer 1.21 and later can track them if you set max_prepared_statements to a non-zero value. If your driver prepares statements automatically and you see prepared statement does not exist errors, check your PgBouncer version first.

A working configuration

This is a minimal pgbouncer.ini for a single database, using auth_query so you do not have to maintain a user list by hand:

[databases]
appdb = host=10.0.0.11 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_user = pgbouncer_auth
auth_query = SELECT uname, phash FROM pgbouncer.user_lookup($1)
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20

auth_query needs a role that is allowed to read password hashes without being a superuser. The usual pattern is a SECURITY DEFINER function, created in each database PgBouncer serves:

CREATE ROLE pgbouncer_auth LOGIN PASSWORD 'change-me';
CREATE SCHEMA pgbouncer;

CREATE FUNCTION pgbouncer.user_lookup(IN i_username text, OUT uname text, OUT phash text)
RETURNS record AS $$
BEGIN
  SELECT usename, passwd FROM pg_catalog.pg_shadow
  WHERE usename = i_username INTO uname, phash;
  RETURN;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

REVOKE ALL ON FUNCTION pgbouncer.user_lookup(text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION pgbouncer.user_lookup(text) TO pgbouncer_auth;
GRANT USAGE ON SCHEMA pgbouncer TO pgbouncer_auth;

The application then connects to port 6432 with the same database name, user and password it used before. Nothing else changes in the connection string except the port and, if the pooler is on another host, the host.

Sizing the pool

default_pool_size is the number of server connections per database and user pair. It is the number that protects PostgreSQL, so it should be small. A common starting point is a small multiple of the CPU cores on the database host, then measure. Raise it only when you can show clients waiting while the database is not busy.

max_client_conn is how many application connections PgBouncer will accept. It can be much larger, since idle client connections are cheap. The ratio between the two is the whole point.

To see whether the sizing is right, connect to the PgBouncer admin console and look at:

SHOW POOLS;
SHOW STATS;

The columns that matter are cl_waiting (clients with no server connection yet) and maxwait (how long the oldest one has waited). A non-zero cl_waiting for a few seconds during a spike is normal. A maxwait that keeps climbing means the pool is too small, or queries are too slow and holding connections.

The Patroni problem: where does the pooler point?

On a plain primary and replica pair, you can hard-code the primary in the [databases] section. With Patroni that stops working the first time the leader changes. After a switchover, PgBouncer is still connecting to a node that is now a read-only standby, and every write fails with cannot execute INSERT in a read-only transaction.

There are two common ways to solve it:

  1. Point PgBouncer at a load balancer that health-checks Patroni's REST API (/primary on port 8008 returns 200 only on the leader) and let that balancer follow the leader.
  2. Run a small script or confd-style watcher next to PgBouncer that queries Patroni, rewrites the host= line and reloads PgBouncer.

The first adds a hop and another component to keep healthy. The second is fine, but you now own a script that has to behave correctly during an election, when no member claims to be leader. The sane behavior is to leave the target unchanged until a new leader shows up.

Make the pooler itself highly available

A single PgBouncer is a single point of failure that you added on purpose. The usual fix is two poolers and a floating virtual IP managed by Keepalived, so the application's connection string never changes if one pooler host dies. Put the poolers on different hosts, and prefer hosts that are not database members if you can spare them.

Alerts worth having

Two conditions catch most pooler trouble before users do: clients waiting (more than 10 waiting for a sustained period) and pool saturation (more than 90 percent of the pool in use). Alert on both, and alert on the health of the full path, not just on whether the PgBouncer process is listening. A pooler that is up but pointed at a demoted node looks healthy to a port check.

How this looks in Jarwis ClusterOps

On a PostgreSQL or Patroni cluster, the Load Balancers tab has PgBouncer next to HAProxy. You pick the node (a cluster member is allowed, no extra host required) and the client port, which defaults to 6432. Pool mode defaults to transaction, authentication defaults to auth_query, and the defaults are 1000 client connections with a pool of 20 server connections. You can also set minimum pool, reserve pool and a per-database cap. Changing settings regenerates the configuration and reloads PgBouncer without dropping connected clients.

On Patroni, a small follower service on the PgBouncer node checks which member is leader every couple of seconds and re-targets PgBouncer when it changes. It does not depend on the controller being reachable, and during an election it leaves the target alone until a new leader appears. Two PgBouncer load balancers plus a Floating VIP give you a highly available pooler. The default alert rules cover clients waiting and pool saturation, and a health probe connects through the pooler port to verify the whole client to leader path.

Lite is free up to three nodes, which is enough for a three-node Patroni cluster with PgBouncer running on one of the members. If you want to look at a live PostgreSQL cluster first, there is a read-only demo at demo.jarwis.com. The setup details are in the PgBouncer docs, and the failover side is covered in high availability and failover.