Sub topic 4
Your first pgbouncer.ini
This chapter assumes you have a running PostgreSQL server, can use psql, and know what roles, databases, and max_connections are. You should also be able to edit files under /etc on Linux. By the end you will have a working pgbouncer.ini, you will know what each line does, and you will be able to connect through PgBouncer and apply changes safely.
How the file is organized
PgBouncer reads one INI file. It has two sections you need for a first setup:
[databases]maps the database names that clients ask for to real PostgreSQL servers.[pgbouncer]holds the pooler's own settings: where it listens, how it authenticates clients, how it pools, and where it logs.
Lines starting with ; or # are comments. Names and values are case-sensitive in the usual way for INI files, so copy setting names exactly.
A minimal working configuration
Save this as /etc/pgbouncer/pgbouncer.ini:
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
admin_users = pgbouncer_admin
logfile = /var/log/pgbouncer/pgbouncer.log
pidfile = /var/run/pgbouncer/pgbouncer.pidThis configuration accepts up to 1000 client connections on port 6432. It shares at most 20 server connections per user and database pair, and it hands a server connection to a client only for the length of one transaction.
The [databases] section
The left side of each line is the name clients put in their connection string. The right side is a list of key=value pairs that describe the real target.
hostandportlocate PostgreSQL. If you omit them, PgBouncer connects to a Unix socket.dbnameis the real database name. If you omit it, PgBouncer uses the name on the left.- Optional keys such as
user,password,pool_size, andpool_modeoverride global settings for this one database.
The left-hand name does not have to match the real one. This lets you rename or move a database without touching application code:
[databases]
orders = host=10.0.0.12 port=5432 dbname=orders_prod pool_size=40
reports = host=10.0.0.13 port=5432 dbname=reports pool_mode=sessionA line with * as the name acts as a fallback for any database not listed. It is convenient in development, but in production an explicit list is safer because clients cannot reach databases you did not intend to expose.
The [pgbouncer] section
| Setting | What it does | Default |
|---|---|---|
| `listen_addr` | Address PgBouncer accepts clients on | `127.0.0.1` (local only) |
| `listen_port` | TCP port for clients | `6432` |
| `auth_type` | How clients prove who they are | `md5` in older releases, `scram-sha-256` in recent ones |
| `auth_file` | File with usernames and password hashes | none |
| `pool_mode` | When a server connection returns to the pool | `session` |
| `max_client_conn` | Maximum simultaneous client connections | `100` |
| `default_pool_size` | Server connections per user and database pair | `20` |
| `reserve_pool_size` | Extra server connections allowed under load | `0` |
| `reserve_pool_timeout` | Seconds a client waits before the reserve pool is used | `5` |
| `admin_users` | Users allowed to run admin commands | none |
Check the defaults against your installed version, because they have changed between releases.
Two settings are easy to misread:
default_pool_sizeapplies to each user and database pair, not to the whole server. If two roles each useappdb, PgBouncer can open up to 40 server connections for it. Pool sizing gets its own chapter, but remember this now so your first numbers do not surprise you.max_client_connlimits connections to PgBouncer, not to PostgreSQL. It can be far larger thanmax_connectionson the database, which is the whole point of pooling. Each client connection uses a file descriptor, so the operating system's open-file limit (ulimit -n) must be higher thanmax_client_connplus the server connections you expect.
Creating the auth file
PgBouncer verifies logins itself, so it needs the password hashes. The file userlist.txt has one line per user, each with the name and the hash in double quotes. You can generate a line from PostgreSQL as a superuser:
SELECT '"' || rolname || '" "' || rolpassword || '"'
FROM pg_authid
WHERE rolname = 'app_user';Paste the output into /etc/pgbouncer/userlist.txt. Two points matter here:
- The stored hash must match
auth_type. Withauth_type = scram-sha-256, the entry must be a SCRAM secret (it begins withSCRAM-SHA-256$). A legacy MD5 hash in the file only works withauth_type = md5. - Every name in
admin_usersmust also appear in the auth file, or that user cannot log in to the admin console.
Restrict the file, since hashes are credentials:
sudo chown pgbouncer:pgbouncer /etc/pgbouncer/userlist.txt
sudo chmod 600 /etc/pgbouncer/userlist.txtListing every user by hand does not scale. The next chapters cover auth_query, which looks hashes up in PostgreSQL instead.
PostgreSQL must also accept PgBouncer
From PostgreSQL's point of view, PgBouncer is just another client. Its pg_hba.conf needs a rule that matches the address PgBouncer connects from. In this example PgBouncer runs on the same host, so a 127.0.0.1/32 entry with scram-sha-256 is enough. After PgBouncer opens a server connection, PostgreSQL authenticates the role itself, so a wrong password or a missing pg_hba.conf rule fails there, not in PgBouncer.
Starting PgBouncer and connecting
The log and pid directories must exist and be writable by the account PgBouncer runs as. Then start the service, or run it directly in the foreground to see errors on the terminal:
sudo systemctl start pgbouncer
# or, in the foreground for debugging:
pgbouncer /etc/pgbouncer/pgbouncer.iniTo switch an application over, change only the port (and the host, if PgBouncer is elsewhere):
# Application connection string: only host and port change
DATABASE_URL=postgresql://[email protected]:6432/appdb
# Reload pgbouncer.ini without dropping clients (admin console):
# RELOAD;Test with psql:
psql "postgresql://[email protected]:6432/appdb" -c "SELECT 1;"If this works, the client reached PgBouncer, passed its authentication, and PgBouncer opened a server connection to PostgreSQL.
Applying configuration changes
Connect to the special database named pgbouncer as an admin user:
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncerThen run RELOAD;. It re-reads pgbouncer.ini and the auth file without disconnecting clients. Sending SIGHUP to the process has the same effect.
RELOAD does not apply every setting. Changes to listen_addr and listen_port, for example, need a restart, and a restart drops all connections. Pool settings such as default_pool_size and pool_mode apply to new server connections as they are made. Check SHOW CONFIG; in the console to see what PgBouncer actually uses.
Common first-run errors
| Symptom | Likely cause |
|---|---|
| `no such database: appdb` | The name is missing from `[databases]`, or there is a typo |
| `password authentication failed` from PgBouncer | The user is missing from `auth_file`, or the hash does not match `auth_type` |
| Client connects, then `server login has been failing` | PostgreSQL rejected PgBouncer: check `pg_hba.conf` and the role's password |
| `no more connections allowed (max_client_conn)` | More clients than `max_client_conn`; raise it, and check `ulimit -n` |
| Process exits at start with a file error | The log or pid directory does not exist or is not writable |
The PgBouncer log file is the first place to look. It records the reason for each rejected login and failed server connection.
Exercise
You add a second role, reportuser, that also connects to appdb through PgBouncer. With defaultpoolsize = 20, what is the largest number of server connections PgBouncer may open to appdb for these two roles (ignoring the reserve pool)? Also, why might reportuser fail to log in even though the role exists in PostgreSQL?
Show answer
Up to 40, because defaultpoolsize applies to each user and database pair, so appuser and reportuser each get their own pool of 20. Login can fail because PgBouncer checks credentials itself: reportuser must be listed in the authfile (or be found through authquery) with a hash that matches authtype. Being a role in PostgreSQL alone is not enough.
Exercise
You edit listen_port in pgbouncer.ini and run RELOAD; in the admin console. Clients still connect on the old port. What happened, and what must you do?
Show answer
RELOAD does not apply listenaddr or listenport changes. You must restart PgBouncer for the new port to take effect, which drops existing connections, so schedule it accordingly.