Sub topic 15
Troubleshooting common problems
This chapter assumes you have read the earlier chapters. You should know the pool modes, the pgbouncer.ini layout, the SHOW commands on the admin console, and how pool sizing relates to max_connections. Here you will turn those pieces into a diagnostic routine. You start with a symptom, read the right console output, and apply a fix.
A diagnostic routine
Most PgBouncer problems fall into three groups: clients cannot get a server connection, clients get an error from a limit or a timeout, and a query behaves differently than it does without the pooler. The admin console tells you which group you are in.
Run these first:
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer
-- then, inside the admin console:
SHOW POOLS;
SHOW CLIENTS;
SHOW SERVERS;
SHOW STATS;In SHOW POOLS, read these columns:
cl_active: clients currently linked to a server connection.cl_waiting: clients that sent a query and have no server connection yet.sv_active: server connections in use.sv_idle: server connections ready for reuse.maxwait: seconds the oldest waiting client has waited.
Clients wait for a server connection
This is the most common problem. Applications slow down or time out, and SHOW POOLS shows cl_waiting above zero with a growing maxwait.
The cause is usually one of these:
- The pool is full and every connection is busy.
sv_activeequalsdefault_pool_size. Either the pool is too small for the load, or something holds connections too long. - Transactions stay open. An application that runs
BEGIN, does other work, and commits later keeps a server connection for that whole time. InSHOW SERVERS, look for connections in theactivestate with an oldrequest_time. Cross-check withpg_stat_activityon PostgreSQL, where thestatecolumn showsidle in transaction. - Slow queries. Each slow query occupies a server connection for its duration. Fix the query, or set
statement_timeoutfor the role. - PgBouncer cannot open new server connections.
sv_loginstays high, orsv_activeis below the pool size while clients wait. PostgreSQL may be atmax_connections, or the host or port in[databases]is wrong.
Find idle-in-transaction sessions on the PostgreSQL side:
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 60) AS last_query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY xact_start;Raising default_pool_size is the tempting fix, but it only helps when the database has spare capacity. If the database is already CPU-bound, a larger pool adds contention and makes every query slower. Fix long transactions first, then resize.
The reserve pool can absorb short bursts. With reserve_pool_size = 5 and reserve_pool_timeout = 3, a client that waits more than 3 seconds can draw on up to 5 extra server connections. If SHOW POOLS shows waiting clients regularly, the burst is not short, and you need a real fix.
Errors from limits and timeouts
| Error text | Meaning | Fix |
|---|---|---|
| `no more connections allowed (max_client_conn)` | PgBouncer already holds `max_client_conn` client connections. | Raise `max_client_conn`, check for connection leaks in the application, and check the file descriptor limit (`ulimit -n`). |
| `query_wait_timeout` | A client waited longer than `query_wait_timeout` for a server connection. | Treat it as the pool-full case above. |
| `server conn crashed?` or `server closed the connection unexpectedly` | The server connection was closed under an active client. | Check the PostgreSQL log for restarts, `idle_session_timeout`, or `pg_terminate_backend` calls. Also check `server_lifetime` and `server_idle_timeout`. |
| `pooler error: server login has been failing` | PgBouncer cannot log in to PostgreSQL. | Check credentials, `pg_hba.conf` on the server, and that `max_connections` is not exhausted. |
| `client_idle_timeout` closes clients | Clients idle longer than the limit are dropped. | Raise the limit or enable client-side reconnect. |
Two limits are easy to confuse. max_client_conn caps connections from applications to PgBouncer. default_pool_size caps server connections for each user and database pair. If you have several users and databases, the total server connections can reach pairs × (default_pool_size + reserve_pool_size). Make sure that product stays below PostgreSQL's max_connections minus the connections that bypass the pooler, such as superuser access and replication.
Authentication failures
The message password authentication failed in PgBouncer's log can come from two places. Read the log to see which one.
- PgBouncer rejected the client. The client's user is missing from
auth_file, the hash is stale, orauth_typedoes not match the stored hash format. A SCRAM hash inuserlist.txtworks withauth_type = scram-sha-256. After changing a password on PostgreSQL, regenerate the line:
SELECT '"' || rolname || '" "' || rolpassword || '"'
FROM pg_authid
WHERE rolname = 'app_user';- PostgreSQL rejected PgBouncer. PgBouncer logs in to the server as the client's user, using the same hash, unless the
[databases]entry setsuser=andpassword=. Checkpg_hba.conffor the PgBouncer host address. Remember that PgBouncer connects from its own IP address, not from the application's.
With auth_query, a failure often comes from the lookup function. Test it directly as the auth user:
-- Connect to PostgreSQL as pgbouncer_auth, then:
SELECT * FROM public.user_lookup('app_user');An empty result means the user does not exist, or the function cannot read pg_shadow. Confirm that the function was created with SECURITY DEFINER by a role that can read it, and that pgbouncer_auth has EXECUTE.
After you change auth_file or pgbouncer.ini, run RELOAD; in the admin console. Existing client connections keep working. Only new logins use the new values.
Queries behave differently through the pooler
If a query works against PostgreSQL directly and fails or misbehaves through port 6432, suspect transaction pooling. Session state set on one transaction can be gone, or can land on another client's turn.
Common symptoms and causes:
- A setting disappears. A session-level
SETorSET search_pathran earlier, but the next transaction used a different server connection. UseSET LOCALinside a transaction, or set defaults per role withALTER ROLE ... SET. - A setting leaks. A session-level
SETstays on a server connection and affects the next client. Replace it withSET LOCAL:
BEGIN;
SET LOCAL statement_timeout = '5s';
SELECT count(*) FROM orders;
COMMIT;- Prepared statement errors. Messages such as
prepared statement "S_1" does not existoralready existsmean the client prepared a statement on one server connection and later ran it on another. Either disable server-side prepared statements in the driver, use a PgBouncer version that supports protocol-level prepared statements in transaction mode (max_prepared_statementsgreater than zero), or use session mode. LISTEN/NOTIFYstops working. Notifications belong to a session. Connect those clients directly to PostgreSQL, or to a separate session-mode pool.- Advisory locks are not released or are lost.
pg_advisory_lockis session-scoped. Usepg_advisory_xact_lockin transaction mode. - Temporary tables vanish. They belong to a server session. Use
ON COMMIT DROPtables inside one transaction.
A quick test is to point the same client at a session-mode entry. Add a second database alias in [databases] with pool_mode = session. If the problem disappears, session state is the cause.
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
appdb_session = host=127.0.0.1 port=5432 dbname=appdb pool_mode=sessionConnections close after a restart or reload
RELOAD; rereads the configuration and does not disconnect clients. A full restart does drop them. For a restart with little disruption, use SUSPEND; to finish in-flight work, then start the new process with pgbouncer -R (online restart), or put a second instance behind a load balancer. For planned PostgreSQL maintenance, PAUSE appdb; waits for active transactions to finish and holds new queries, and RESUME appdb; lets them continue.
If the server's address changes, for example after a failover, PgBouncer does not refetch DNS for every connection. Check dns_max_ttl, or run RECONNECT appdb; so new server connections use the updated host.
A checklist for a new incident
- Read
SHOW POOLSand notecl_waiting,sv_active, andmaxwait. - Read the PgBouncer log for the exact error text.
- Compare PgBouncer's view with
pg_stat_activity: count connections and look foridle in transaction. - Compare the sum of all pool sizes with
max_connections. - Test the failing query through a session-mode alias to rule out session state.
- Change one setting at a time, run
RELOAD;, and checkSHOW POOLSagain.
Exercise
Clients report timeouts. SHOW POOLS shows clwaiting = 40, svactive = 20, svidle = 0, and defaultpoolsize = 20. pgstatactivity shows 12 sessions in the state "idle in transaction" for several minutes. What is the most likely cause, and what should you do before raising defaultpool_size?
Show answer
The pool is full, and 12 of its 20 connections are held by transactions that were opened and never finished, so the 40 waiting clients cannot be served. Find the application code that starts a transaction and then waits, for example on an external call, and fix it to commit or roll back promptly. As a safeguard, set idleintransactionsessiontimeout for the role on PostgreSQL. Raising defaultpoolsize would only hide the problem and could overload the database.
Exercise
After deployment, an application using transaction pooling reports "prepared statement S_3 does not exist" on some requests. Name two ways to fix it.
Show answer
The driver prepared the statement on one server connection and later ran it on another. Either turn off server-side prepared statements in the driver, or enable protocol-level prepared statement support in PgBouncer by setting maxpreparedstatements above zero (in a version that supports it). Moving the application to session pooling also works, but it removes most of the multiplexing benefit.