Sub topic 3
Timeouts and the reserve pool
This chapter assumes you have a working pgbouncer.ini, can connect through PgBouncer with psql, and know that PostgreSQL's max_connections caps server connections.
Timeouts and the reserve pool
When every server connection in a pool is busy, new clients wait. Two settings control that wait:
query_wait_timeout: the longest a client waits for a server connection before PgBouncer returns an error. The default is 120 seconds.reserve_pool_sizeandreserve_pool_timeout: if a client has waited longer thanreserve_pool_timeoutseconds, PgBouncer may open up toreserve_pool_sizeextra server connections for it.
[pgbouncer]
default_pool_size = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
query_wait_timeout = 60Using the admin console
Connect to the virtual database named pgbouncer. Only roles listed in admin_users can log in.
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncerUseful commands are SHOW POOLS, SHOW STATS, SHOW CLIENTS, SHOW SERVERS, and RELOAD, which rereads pgbouncer.ini without dropping clients.
Reading pool and traffic statistics
SHOW POOLS returns one row per pool. The cl_waiting column counts clients waiting for a server connection. sv_active counts server connections in use, and sv_idle counts free ones. SHOW STATS reports totals, including avg_query_time, in microseconds.
TLS and restricting access
Bind listen_addr to a private interface and block port 6432 with a firewall. To encrypt client traffic, set client_tls_sslmode = require and point client_tls_cert_file and client_tls_key_file at your certificate and key.
Where to run PgBouncer and how to keep it available
Run PgBouncer close to the application so each connection crosses the network once. Run at least two instances behind a load balancer or a failover address, and let systemd restart a failed process.
Troubleshooting common problems
- Clients hang: Check
cl_waitinginSHOW POOLS. If it stays above zero whilesv_idleis zero, the pool is too small or queries are slow. - Timeout errors: A client waited longer than
query_wait_timeout. Raise the pool size only if PostgreSQL has headroom. - Lost session settings: Review the transaction pooling caveats from earlier chapters.
Exercise
A pool shows clwaiting = 12 and svidle = 0. Should you raise querywaittimeout or defaultpoolsize?
Show answer
Raise defaultpoolsize, if PostgreSQL's maxconnections has room for it. Clients wait because no server connection is free. Raising querywait_timeout only makes them wait longer before failing.