PGBOUNCER(1)
๐ PGBOUNCER(1) โ the pgbouncer(1) glow-up ๐ฆ
okay so bestie, sit down, hydrate, and get comfy, because we're about to read the manual page for pgbouncer โ that's the lightweight connection pooler for PostgreSQL โ and honestly? It's giving main character energy for your database layer. ๐
โจ NAME โจ
pgbouncer โ a lightweight connection pooler for PostgreSQL. That's the whole vibe. ๐ซถ
๐ SYNOPSIS ๐
The classic:
pgbouncer [-d][-v][-u user] <pgbouncer.ini>
pgbouncer -V|-h
And on Windows, the options are:
pgbouncer.exe [-v][-u user] <pgbouncer.ini>
pgbouncer.exe -V|-h
Additional options for setting up a Windows service:
pgbouncer.exe --regservice <pgbouncer.ini>
pgbouncer.exe --unregservice <pgbouncer.ini>
๐ DESCRIPTION ๐
So like, pgbouncer is a PostgreSQL connection pooler. Any target application can connect to pgbouncer like it's just a regular PostgreSQL server โ no cap โ and then pgbouncer will either create a connection to the actual server, or it'll reuse one of the connections it already has sitting there. Iconic recycling behavior. โป๏ธ
The whole point, the ~aim~ of pgbouncer, is to lower the performance impact of opening new connections to PostgreSQL. Opening fresh connections is expensive; pgbouncer said "not on my watch." ๐
And here's the important part: so that it doesn't compromise transaction semantics for connection pooling, pgbouncer supports several types of pooling when rotating connections:
- Session pooling โ the most polite method. When a client connects, a server connection gets assigned to it for the whole duration the client stays connected. When the client disconnects, the server connection gets put back into the pool. This is the default method. ๐
- Transaction pooling โ a server connection is assigned to a client only during a transaction. When PgBouncer notices that the transaction is over, the server connection gets put back into the pool. โจ
- Statement pooling โ the most aggressive method. The server connection gets put back into the pool immediately after a query completes. Multi-statement transactions are disallowed in this mode because they would break. ๐ซ
And the administration interface of pgbouncer? It consists of some new SHOW commands that are available when you're connected to a special "virtual" database called pgbouncer. Very exclusive, very VIP. ๐
๐ QUICK-START ๐
Basic setup and usage is as follows, bestie. Follow along:
- Create a
pgbouncer.inifile. Details inpgbouncer(5). Simple example:
[databases]
template1 = host=localhost port=5432 dbname=template1
[pgbouncer]
listen_port = 6432
listen_addr = localhost
auth_type = md5
auth_file = userlist.txt
logfile = pgbouncer.log
pidfile = pgbouncer.pid
admin_users = someuser
- Create a
userlist.txtfile that contains the users allowed in:
"someuser" "same_password_as_in_server"
- Launch
pgbouncer:
$ pgbouncer -d pgbouncer.ini
- Have your application (or the
psqlclient) connect topgbouncerinstead of directly to the PostgreSQL server:
$ psql -p 6432 -U someuser template1
- Manage
pgbouncerby connecting to the special administration databasepgbouncerand issuingSHOW HELP;to begin:
$ psql -p 6432 -U someuser pgbouncer
pgbouncer=# SHOW HELP;
NOTICE: Console usage
DETAIL:
SHOW [HELP|CONFIG|DATABASES|POOLS|CLIENTS|SERVERS|SOCKETS|LISTS|VERSION|...]
SET key = arg
RELOAD
PAUSE
RESUME
SHUTDOWN
[...]
- If you made changes to the
pgbouncer.inifile, you can reload it with:
pgbouncer=# RELOAD;
Slay. You're basically a DBA now. ๐
๐ COMMAND LINE SWITCHES ๐
-d,--daemonโ run in the background. Without it, the process runs in the foreground. ๐
Heads up: in daemon mode, setting pidfile as well as logfile or syslog is required. No log messages will be written to stderr after going into the background.
Note: does not work on Windows; pgbouncer needs to run as a service there.
-u USERNAME,--user=USERNAMEโ switch to the given user on startup. ๐ซถ-v,--verboseโ increase verbosity. Can be used multiple times. (Yes bestie, stack them. Go off.) ๐ฅ-q,--quietโ be quiet: do not log to stderr. This does not affect logging verbosity โ only that stderr is not to be used. For use ininit.dscripts. ๐คซ-V,--versionโ show version. โญ-h,--helpโ show short help. ๐--regserviceโ Win32: register PgBouncer to run as a Windows service. Theservice_nameconfiguration parameter value is used as the name to register under. ๐ช--unregserviceโ Win32: unregister the Windows service. ๐ช
๐ ADMIN CONSOLE ๐
The console is available by connecting as normal to the database pgbouncer:
$ psql -p 6432 pgbouncer
Only users listed in the configuration parameters admin_users or stats_users are allowed to log in to the console. (Except when auth_type=any, then any user is allowed in as a stats_user.) ๐๏ธ
Additionally, the user name pgbouncer is allowed to log in without a password, if the login comes via the Unix socket and the client has the same Unix user UID as the running process. โจ
Real talk: the admin console currently only supports the simple query protocol. Some drivers use the extended query protocol for all commands; those drivers will not work for this. ๐ญ Not their fault, but also not pgbouncer's problem.
๐ธ Show commands ๐ธ
The SHOW commands output information. Each command is described below. ๐ฆ
๐ SHOW STATS ๐
Shows statistics. In this and related commands, the total figures are since process start, and the averages are updated every stats_period. ๐
databaseโ statistics are presented per database.total_xact_countโ total number of SQL transactions pooled bypgbouncer.total_query_countโ total number of SQL commands pooled bypgbouncer.total_server_assignment_countโ total times a server was assigned to a client.total_receivedโ total volume in bytes of network traffic received bypgbouncer.total_sentโ total volume in bytes of network traffic sent bypgbouncer.total_xact_timeโ total number of microseconds spent bypgbouncerwhen connected to PostgreSQL in a transaction, either idle in transaction or executing queries.total_query_timeโ total number of microseconds spent bypgbouncerwhen actively connected to PostgreSQL, executing queries.total_wait_timeโ time spent by clients waiting for a server, in microseconds. Updated when a client connection is assigned a backend connection.total_client_parse_countโ total number of prepared statements created by clients. Only applicable in named prepared statement tracking mode, seemax_prepared_statements.total_server_parse_countโ total number of prepared statements created bypgbounceron a server. Only applicable in named prepared statement tracking mode, seemax_prepared_statements.total_bind_countโ total number of prepared statements readied for execution by clients and forwarded to PostgreSQL bypgbouncer. Only applicable in named prepared statement tracking mode, seemax_prepared_statements.total_client_login_countโ total number of successful client logins.avg_xact_countโ average transactions per second in last stat period.avg_query_countโ average queries per second in last stat period.avg_server_assignment_countโ average number of times a server was assigned to a client per second in the last stat period.avg_recvโ average received (from clients) bytes per second.avg_sentโ average sent (to clients) bytes per second.avg_xact_timeโ average transaction duration, in microseconds.avg_query_timeโ average query duration, in microseconds.avg_wait_timeโ time spent by clients waiting for a server, in microseconds (average of the wait times for clients assigned a backend during the currentstats_period).avg_client_parse_countโ average number of prepared statements created by clients. Only applicable in named prepared statement tracking mode, seemax_prepared_statements.avg_server_parse_countโ average number of prepared statements created bypgbounceron a server. Only applicable in named prepared statement tracking mode, seemax_prepared_statements.avg_bind_countโ average number of prepared statements readied for execution by clients and forwarded to PostgreSQL bypgbouncer. Only applicable in named prepared statement tracking mode, seemax_prepared_statements.avg_client_login_countโ average number of successful client logins per second.
โญ SHOW STATS_TOTALS โญ
A subset of SHOW STATS showing the total values (total_). ๐งฎ
โญ SHOW STATS_AVERAGES โญ
A subset of SHOW STATS showing the average values (avg_). ๐
๐ SHOW TOTALS ๐
Like SHOW STATS but aggregated across all databases. The big picture, bestie. ๐ซถ
๐ฆ SHOW SERVERS ๐ฆ
typeโS, for server.userโ user namepgbounceruses to connect to server.databaseโ database name.replicationโ if the server connection uses replication. Can benone,logicalorphysical.stateโ state of the PgBouncer server connection, one ofactive,idle,used,tested,new,active_cancel,being_canceled.addrโ IP address of the PostgreSQL server.portโ port of the PostgreSQL server.local_addrโ connection start address on local machine.local_portโ connection start port on local machine.connect_timeโ when the connection was made.request_timeโ when the last request was issued.waitโ not used for server connections.wait_usโ not used for server connections.close_neededโ1if the connection will be closed as soon as possible, because a configuration file reload or DNS update changed the connection information orRECONNECTwas issued.ptrโ address of internal object for this connection.linkโ address of client connection the server is paired with.remote_pidโ PID of backend server process. In case the connection is made over Unix socket and the OS supports getting process ID info, its OS PID. Otherwise it's extracted from the cancel packet the server sent, which should be the PID in case the server is PostgreSQL, but it's a random number in case the server is another PgBouncer. ๐tlsโ a string with TLS connection information, or empty if not using TLS.application_nameโ a string containing theapplication_nameset on the linked client connection, or empty if this is not set, or if there is no linked connection.
okay that's part one, and there's more coming so don't go anywhere bestie ๐
prepared_statementsโ how many prepared statements are currently prepped on the server. The ceiling for this is themax_prepared_statementssetting, so that's the vibe limit ๐idโ the server's unique ID, like its own little name tag ๐ท๏ธ
๐ฆ SHOW CLIENTS ๐ฆ
typeโ it'sC, for client. Obviously ๐โโ๏ธuserโ the client's connected user.databaseโ database name, bestie.replicationโ whether the client connection uses replication. Can benone,logical, orphysical.stateโ the client connection's state, and it's one of:active(client connections linked to server connections),idle(client connections with no queries waiting to be processed),waiting,active_cancel_req, orwaiting_cancel_req.addrโ the client's IP address.portโ the client's source port.local_addrโ the connection end address on the local machine.local_portโ the connection end port on the local machine.connect_timeโ timestamp of when the connection happened.request_timeโ timestamp of the latest client request.waitโ the current waiting time, in seconds.wait_usโ the microsecond part of that current waiting time.close_neededโ literally not used for clients ๐ptrโ the address of the internal object for this connection.linkโ the address of the server connection this client is paired with.remote_pidโ process ID, in case the client connects over a Unix socket and the OS supports getting it.tlsโ a string with TLS connection info, or empty if TLS isn't being used.application_nameโ a string containing theapplication_nameset by the client for this connection, or empty if it wasn't set.prepared_statementsโ the amount of prepared statements the client has prepared.idโ unique ID for the client. Every main character needs one ๐
๐ธ SHOW POOLS ๐ธ
A new pool entry gets made for each (database, user) couple. It's giving paired-up dynamic duo energy ๐
databaseโ database name.userโ user name.cl_activeโ client connections that are either linked to server connections, or idle with no queries waiting to be processed.cl_waitingโ client connections that have sent queries but haven't gotten a server connection yet. They're in line, bestie ๐ญcl_active_cancel_reqโ client connections that have forwarded query cancellations to the server and are waiting for the server response.cl_waiting_cancel_reqโ client connections that haven't forwarded query cancellations to the server yet.sv_activeโ server connections that are linked to a client.sv_active_cancelโ server connections that are currently forwarding a cancel request.sv_being_canceledโ servers that normally could become idle, but are waiting to do so until all in-flight cancel requests have completed. Those are the requests sent to cancel a query on this server, btw.sv_idleโ server connections that are unused and immediately usable for client queries. Iconic availability โจsv_usedโ server connections that have been idle for more thanserver_check_delay, soserver_check_queryneeds to run on them before they can be used again.sv_testedโ server connections currently running eitherserver_reset_queryorserver_check_query.sv_loginโ server connections currently in the process of logging in.maxwaitโ how long the first (aka oldest) client in the queue has waited, in seconds.
If this starts increasing, then the current pool of servers isn't handling requests quickly enough. The reason may be either an overloaded server or just too small of a pool_size setting. That's your cue to look at it, bestie ๐
maxwait_usโ the microsecond part of the maximum waiting time.pool_modeโ the pooling mode in use.load_balance_hostsโ theload_balance_hostsin use, if the pool's host contains a comma-separated list.
๐ SHOW PEER_POOLS ๐
A new peer_pool entry gets made for each configured peer. Peer pool era ๐ซถ
peer_idโ ID of the configured peer entry.cl_active_cancel_reqโ client connections that have forwarded query cancellations to the server and are waiting for the server response.cl_waiting_cancel_reqโ client connections that haven't forwarded query cancellations to the server yet.sv_active_cancelโ server connections that are currently forwarding a cancel request.sv_loginโ server connections currently in the process of logging in.
๐ SHOW LISTS ๐
Shows the following internal info, in columns (not rows โ yes, it's that kind of layout, don't come for me):
databasesโ count of databases.usersโ count of users.poolsโ count of pools.free_clientsโ count of free clients. These are clients that are disconnected, but PgBouncer keeps the memory around that was allocated for them so it can be reused for future clients and avoid allocations.used_clientsโ count of used clients.login_clientsโ count of clients in login state.free_serversโ count of free servers. These are servers that are disconnected, but PgBouncer keeps the memory around that was allocated for them so it can be reused for future servers and avoid allocations.used_serversโ count of used servers.dns_namesโ count of DNS names in the cache.dns_zonesโ count of DNS zones in the cache.dns_queriesโ count of in-flight DNS queries.dns_pendingโ not used ๐
๐ SHOW USERS ๐
nameโ the user name.pool_sizeโ the user's overridepool_size, orNULLif not set.reserve_pool_sizeโ the user's overridereserve_pool_size, orNULLif not set.pool_modeโ the user's overridepool_mode, orNULLif not set.max_user_connectionsโ the user'smax_user_connectionssetting. If this setting isn't set for this specific user, then the default value will be displayed.current_connectionsโ current number of server connections that this user has open to all servers.max_user_client_connectionsโ the user'smax_user_client_connectionssetting. If this setting isn't set for this specific user, then the default value will be displayed.current_client_connectionsโ current number of client connections that this user has open to PgBouncer.
๐ฆ SHOW DATABASES ๐ฆ
nameโ name of the configured database entry.hostโ host PgBouncer connects to.portโ port PgBouncer connects to.databaseโ actual database name PgBouncer connects to.force_userโ when the user is part of the connection string, the connection between PgBouncer and PostgreSQL is forced to the given user, whatever the client user. No negotiating ๐pool_sizeโ maximum number of server connections.min_pool_sizeโ minimum number of server connections.reserve_pool_sizeโ maximum number of additional connections for this database.server_lifetimeโ the maximum lifetime of a server connection for this database.pool_modeโ the database's overridepool_mode, orNULLif the default will be used instead.load_balance_hostsโ the database'sload_balance_hosts, if the host contains a comma-separated list.max_connectionsโ maximum number of allowed server connections for this database, as set bymax_db_connections, either globally or per database.current_connectionsโ current number of server connections for this database.max_client_connectionsโ maximum number of allowed client connections for this PgBouncer instance, as set bymax_db_client_connectionsper database.current_client_connectionsโ current number of client connections for this database.pausedโ1if this database is currently paused, else0.disabledโ1if this database is currently disabled, else0.
๐ธ SHOW PEERS ๐ธ
peer_idโ ID of the configured peer entry.hostโ host PgBouncer connects to.portโ port PgBouncer connects to.pool_sizeโ maximum number of server connections that can be made to this peer.
๐ซถ SHOW SOCKETS, SHOW ACTIVE_SOCKETS ๐ซถ
Shows low-level info about sockets โ or only active sockets, when you use the active version. This includes the info shown under SHOW CLIENTS and SHOW SERVERS, plus other more low-level information. It's the behind-the-scenes lore โจ
๐ SHOW CONFIG ๐
Shows the current configuration settings, one per row, with these columns:
keyโ configuration variable name.valueโ configuration value.defaultโ configuration default value.changeableโ eitheryesorno, showing if the variable can be changed while running. Ifno, the variable can be changed only at boot time. UseSETto change a variable at run time.
๐ง SHOW MEM ๐ง
Shows low-level info about the current sizes of various internal memory allocations. The information presented is subject to change โ so don't get too attached, bestie.
๐ SHOW DNS_HOSTS ๐
Shows host names in the DNS cache.
hostnameโ host name.ttlโ how many seconds until the next lookup.addrsโ comma-separated list of addresses.
๐ SHOW DNS_ZONES ๐
Shows DNS zones in the cache.
zonenameโ zone name.serialโ current serial.countโ host names belonging to this zone.
โญ SHOW VERSION โญ
Shows the PgBouncer version string. Slay, version reveal ๐
๐ฎ SHOW STATE ๐ฎ
Shows the PgBouncer state settings. Current states are active and paused.
๐ฅ PROCESS CONTROLLING COMMANDS ๐ฅ
๐
PAUSE [db] ๐
PgBouncer tries to disconnect from all servers. Disconnecting each server connection waits for that server connection to be released according to the server pool's pooling mode โ in transaction pooling mode, the transaction must complete; in statement mode, the statement must complete; and in session pooling mode, the client must disconnect. The command will not return before all server connections have been disconnected. To be used at the time of database restart.
If a database name is given, only that database will be paused.
New client connections to a paused database will wait until RESUME is called. So yes, they're waiting outside like ๐งโโ๏ธ๐งโโ๏ธ๐งโโ๏ธ
๐ DISABLE db ๐
Reject all new client connections on the given database. Not today, new clients ๐
โจ ENABLE db โจ
Allow new client connections after a previous DISABLE command. Welcome back, besties ๐ซถ
๐ RECONNECT [db] ๐
Close each open server connection for the given database โ or all databases โ after it's released (according to the pooling mode), even if its lifetime isn't up yet. New server connections can be made immediately and will connect as necessary according to the pool size settings. Fresh connections, no cap ๐ฅ
okay so this command is useful when the server connection setup has changed โ like, say, you want to do a gradual switchover to a new server. ๐ฆ It is not necessary to run this command when the connection string in pgbouncer.ini has been changed and reloaded (see RELOAD) or when DNS resolution has changed, because then the equivalent of this command will be run automatically. This command is only necessary if something downstream of PgBouncer routes the connections. iykyk ๐
After this command is run, there could be an extended period where some server connections go to an old destination and some server connections go to a new destination. This is likely only sensible when switching read-only traffic between read-only replicas, or when switching between nodes of a multimaster replication setup. If all connections need to be switched at the same time, PAUSE is recommended instead. To close server connections without waiting (for example, in emergency failover rather than gradual switchover scenarios), also consider KILL. ๐ฅ
๐
KILL [db]
Immediately drop all client and server connections on the given database or all databases, excluding the admin database. no cap ๐ซถ
New client connections to a killed database will wait until RESUME is called.
๐
KILL_CLIENT id
Immediately kill the specified client connection along with any server connections for the given client. The client to kill is identified by the id value that can be found using the SHOW CLIENTS command. ๐
An example command will look something like KILL_CLIENT 1234.
๐
RESUME [db]
Resume work from a previous KILL or PAUSE command. we love a comeback era โจ
๐
SHUTDOWN
The PgBouncer process will exit. bye bestie ๐
๐ SHUTDOWN WAIT_FOR_SERVERS
Stop accepting new connections and shutdown after all servers are released. This is basically the same as issuing PAUSE and SHUTDOWN, except that this also stops accepting new connections while waiting for the PAUSE as well as eagerly disconnecting clients that are waiting to receive a server connection. Please note that UNIX sockets will remain open during the shutdown but will only accept connections to the PgBouncer admin console. ๐ง
๐ SHUTDOWN WAIT_FOR_CLIENTS
Stop accepting new connections and shutdown the process once all existing clients have disconnected. Please note that UNIX sockets will remain open during the shutdown but will only accept connections to the pgbouncer admin console. This command can be used to do zero-downtime rolling restart of two PgBouncer processes using the following procedure: ๐
- Have two or more PgBouncer processes running on the same port using
so_reuseport(configuring peering is recommended, but not required). To achieve zero downtime when restarting weโll restart these processes one-by-one, thus leaving the others running to accept connections while one is being restarted. - Pick a process to restart first, letโs call it A.
- Run
SHUTDOWN WAIT_FOR_CLIENTS(or sendSIGTERM) to process A. - Cause all clients to reconnect. Possibly by waiting some time until the client side pooler causes reconnects due to its
server_idle_timeout(or similar config). Or if no client side pooler is used, possibly by restarting the clients. Once all clients have reconnected, process A will exit automatically, because no clients are connected to it anymore. - Start process A again.
- Repeat step 3, 4 and 5 for each of the remaining processes, one-by-one until you restarted all processes.
๐
RELOAD
The PgBouncer process will reload its configuration files and update changeable settings. This includes the main configuration file as well as the files specified by the settings auth_file and auth_hba_file. ๐
PgBouncer notices when a configuration file reload changes the connection parameters of a database definition. An existing server connection to the old destination will be closed when the server connection is next released (according to the pooling mode), and new server connections will immediately use the updated connection parameters. obsessssed with a clean reload โจ
๐
WAIT_CLOSE [db]
Wait until all server connections, either of the specified database or of all databases, have cleared the close_needed state (see SHOW SERVERS). This can be called after a RECONNECT or RELOAD to wait until the respective configuration change has been fully activated, for example in switchover scripts. ๐ฆ
โจ Other commands โจ
๐
SET key = arg
Changes a configuration setting (see also SHOW CONFIG). For example:
SET log_connections = 1;
SET server_check_query = 'select 2';
(Note that this command is run on the PgBouncer admin console and sets PgBouncer settings. A SET command run on another database will be passed to the PostgreSQL backend like any other SQL command.) ๐
๐ก Signals ๐ก
SIGHUPโ Reload config. Same as issuing the commandRELOADon the console.SIGTERMโ Super safe shutdown. Wait for all existing clients to disconnect, but donโt accept new connections. This is the same as issuingSHUTDOWN WAIT_FOR_CLIENTSon the console. If this signal is received while there is already a shutdown in progress, then an โimmediate shutdownโ is triggered instead of a โsuper safe shutdownโ. In PgBouncer versions earlier than1.23.0, this signal would cause an โimmediate shutdownโ. ๐ญSIGINTโ Safe shutdown. Same as issuingSHUTDOWN WAIT_FOR_SERVERSon the console. If this signal is received while there is already a shutdown in progress, then an โimmediate shutdownโ is triggered instead of a โsafe shutdownโ.SIGQUITโ Immediate shutdown. Same as issuingSHUTDOWNon the console.SIGUSR1โ Same as issuingPAUSEon the console.SIGUSR2โ Same as issuingRESUMEon the console.
๐ Libevent settings ๐
From the Libevent documentation:
It is possible to disable support forepoll,kqueue,devpoll,pollorselectby setting the environment variableEVENT_NOEPOLL,EVENT_NOKQUEUE,EVENT_NODEVPOLL,EVENT_NOPOLLorEVENT_NOSELECT, respectively. By setting the environment variableEVENT_SHOW_METHOD, libevent displays the kernel notification method that it uses.
๐ซถ SEE ALSO ๐ซถ
pgbouncer(5)โ man page of configuration settings descriptionshttps://www.pgbouncer.org/
signing off from the PGBOUNCER(1) page, version 1.26.1 โ mwah, bestie ๐๐
๐ฆ where this page comes from
- fedora 44: pgbouncer 1.26.1-1.fc44 ยท ISC and BSD-2-Clause
- nixos 26.05: pgbouncer 1.26.1
- nixpkgs unstable: pgbouncer 1.26.1
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms