Pgbouncer Quick Start
Pgbouncer is a lightweight database connection pool.
Synopsis
Description
pgbouncer is a PostgreSQL connection pooler. Any target application can connect to pgbouncer as if it were a PostgreSQL server, and pgbouncer will create connections to the actual server or reuse existing connections.
The purpose of pgbouncer is to reduce the performance impact of opening new PostgreSQL connections.
To avoid affecting connection pool transaction semantics, pgbouncer supports several types of pooling when switching connections:
Session pooling
The most polite method. When a client connects, a server connection will be assigned for the entire duration of the client connection. When the client disconnects, the server connection is returned to the pool. This is the default method.
Transaction pooling
A server connection is only assigned to a client for the duration of a transaction. When PgBouncer detects transaction end, the server connection is returned to the pool.
Statement pooling
The most aggressive mode. Server connections are immediately returned to the pool after query completion. Multi-statement transactions are not allowed in this mode as they would break.
The pgbouncer management interface is available through some new SHOW commands when connecting to the special ‘virtual’ database pgbouncer.
Getting Started
Basic setup and usage:
Create a pgbouncer.ini file. See pgbouncer(5) for details. Simple example:
Create
users.txtfile containing allowed users:Launch pgbouncer:
Have your application (or psql) connect to pgbouncer instead of directly to PostgreSQL server:
Manage pgbouncer by connecting to the special admin database pgbouncer and issue
show help;to start:If you modify pgbouncer.ini file, you can reload it with:
Command Line Switches
| -d | Run in background. Without it, the process runs in foreground. Note: Doesn’t work on Windows, pgbouncer needs to run as a service. |
|---|---|
| -R | Do online restart. This means connect to running process, load open sockets from it, then use them. If no active process, boot normally. Note: Only works if OS supports Unix sockets and unix_socket_dir is not disabled in config. Doesn’t work on Windows. TLS connections are not used, they are dropped. |
| -u user | Switch to given user on startup. |
| -v | Increase verbosity. Can be used multiple times. |
| -q | Be quiet - don’t log to stdout. Note this doesn’t affect logging verbosity, only that stdout is not used. For init.d scripts. |
| -V | Show version. |
| -h | Show brief help. |
| –regservice | Win32: register pgbouncer to run as Windows service. service_name config parameter value is used as the name to register. |
| –unregservice | Win32: unregister Windows service. |
Admin Console
Console is available by connecting normally to database pgbouncer:
Only users listed in config parameters admin_users or stats_users are allowed to login to console. (Exception: when auth_mode=any, any user can login as stats_user.)
Additionally, when logged in via Unix socket and the client has the same Unix user UID as the running process, username pgbouncer is allowed to login without password.
SHOW Commands
SHOW STATS;
Shows statistics.
| Field | Description |
|---|---|
database | Statistics organized by database |
total_xact_count | Total number of SQL transactions |
total_query_count | Total number of SQL queries |
total_received | Total network traffic received (bytes) |
total_sent | Total network traffic sent (bytes) |
total_xact_time | Total time spent in transactions |
total_query_time | Total time spent in queries |
total_wait_time | Total time spent waiting |
avg_xact_count | Average transactions per second (current) |
avg_query_count | Average queries per second (current) |
avg_recv | Average bytes received per second (current) |
avg_sent | Average bytes sent per second (current) |
avg_xact_time | Average transaction time (milliseconds) |
avg_query_time | Average query time (milliseconds) |
avg_wait_time | Average wait time (milliseconds) |
Two variants: SHOW STATS_TOTALS and SHOW STATS_AVERAGES, showing totals and averages respectively.
TOTAL metrics are actually counters, while AVG are typically gauges. For monitoring, it’s recommended to collect TOTAL, and use AVG for viewing.
SHOW SERVERS
| Field | Description |
|---|---|
type | Server type fixed as S |
user | Username PgBouncer uses to connect to database |
state | State of pgbouncer server connection: active, used, or idle |
addr | IP address of PostgreSQL server |
port | Port of PostgreSQL server |
local_addr | Local address connection originates from |
local_port | Local port connection originates from |
connect_time | Time when connection was established |
request_time | Time when last request was issued |
ptr | Address of internal object for this connection, used as unique identifier |
link | Address of paired client connection |
remote_pid | PID of backend server process. If connected via unix socket and OS supports getting process ID info, it’s the OS pid. Otherwise extracted from cancel packet sent by server - if server is Postgres, should be PID, but if server is another PgBouncer, it’s a random number. |
SHOW CLIENTS
| Field | Description |
|---|---|
type | Client type fixed as C |
user | User client uses to connect |
state | State of pgbouncer client connection: active, used, waiting, or idle |
addr | IP address of client |
port | Client port |
local_addr | Local address |
local_port | Local port |
connect_time | Time when connection was established |
request_time | Time when last request was issued |
ptr | Address of internal object for this connection, used as unique identifier |
link | Address of paired server connection |
remote_pid | If connected via unix socket and OS supports getting process ID info, it’s the OS pid |
SHOW POOLS;
A new connection pool is created for each (database, user) pair.
- database: Database name
- user: Username
- cl_active: Client connections linked to server connection and can process queries
- cl_waiting: Client connections that have sent queries but not yet gotten server connection
- sv_active: Server connections linked to client
- sv_idle: Server connections unused and immediately available for client queries
- sv_used: Server connections idle longer than server_check_delay, so need to run server_check_query before they can be used
- sv_tested: Server connections currently running server_reset_query or server_check_query
- sv_login: Server connections currently in login process
- maxwait: How long the first (oldest) client in queue has been waiting, in seconds. If it starts increasing, the current connection pool can’t handle requests fast enough. Cause could be server overload or pool_size setting too small
- pool_mode: Connection pooling mode being used
SHOW LISTS;
Shows following internal information in columns (not rows):
- databases: Database count
- users: User count
- pools: Pool count
- free_clients: Free client count
- used_clients: Used client count
- login_clients: Client count in login state
- free_servers: Free server count
- used_servers: Used server count
SHOW USERS;
- name: Username
- pool_mode: User’s overridden pool_mode, NULL if using default
SHOW DATABASES;
- name: Name of configured database entry
- host: Host pgbouncer connects to
- port: Port pgbouncer connects to
- database: Actual database name pgbouncer connects to
- force_user: When user is part of connection string, connection between pgbouncer and PostgreSQL is forced to given user, regardless of client user
- pool_size: Maximum number of server connections
- pool_mode: Database’s overridden pool_mode, NULL if using default
SHOW FDS;
Internal command - shows list of fds used with accompanying internal state.
When connected user uses username “pgbouncer”, connected via Unix socket and has same UID as running process, actual fds are passed over connection. This mechanism is used for online restart. Note: Doesn’t work on Windows.
This command also blocks internal event loop, so shouldn’t be used while PgBouncer is in use.
- fd: File descriptor numeric value
- task: One of pooler, client, or server
- user: User of connection using this FD
- database: Database of connection using this FD
- addr: IP address of connection using FD, or unix if using unix socket
- port: Port of connection using FD
- cancel: Cancel key for this connection
- link: Corresponding server/client fd. NULL if idle
SHOW CONFIG;
Shows current configuration settings, one per line, with following fields:
- key: Configuration variable name
- value: Configuration value
- changeable: yes or no, shows whether runtime variable is changeable. If no, variable can only be changed at startup
SHOW DNS_HOSTS;
Shows hostnames in DNS cache.
- hostname: Hostname
- ttl: Seconds until next lookup
- addrs: Comma-separated list of addresses
SHOW DNS_ZONES
Shows DNS zones in cache.
- zonename: Zone name
- serial: Current serial number
- count: Hostnames belonging to this zone
Process Control Commands
PAUSE [db];
PgBouncer tries to disconnect all servers, first waiting for all queries to complete. Command doesn’t return until all queries complete. Use during database restart. If database name provided, only that database is paused.
DISABLE db;
Reject all new client connections on given database.
ENABLE db;
Allow new client connections after previous DISABLE command.
KILL db;
Immediately drop all client and server connections on given database.
SUSPEND;
All socket buffers are flushed and PgBouncer stops listening for data on them. Command doesn’t return until all buffers are empty. Use during PgBouncer online restart.
RESUME [db];
Resume work from previous PAUSE or SUSPEND command.
SHUTDOWN;
PgBouncer process will exit.
RELOAD;
PgBouncer process will reload its configuration file and update changeable settings.
Signals
- SIGHUP: Reload config. Same as issuing RELOAD; command on console.
- SIGINT: Safe shutdown. Same as issuing PAUSE; and SHUTDOWN; on console.
- SIGTERM: Immediate shutdown. Same as issuing SHUTDOWN; on console.
Libevent Settings
From libevent documentation:
