Sub topic 2
Choosing a pool mode
This chapter assumes you can run psql, know what max_connections controls, and have a PgBouncer instance you can edit. Each pool mode decides when a server connection goes back to the pool, and that choice determines which features your application can use.
Choosing a pool mode
PgBouncer offers three modes, set with pool_mode in the [pgbouncer] section:
- session: a client keeps its server connection until it disconnects.
- transaction: a server connection is returned to the pool after each transaction.
- statement: a server connection is returned after each statement. Multi-statement transactions are not allowed.
Use transaction mode for most web applications with many short requests. Use session mode when the application relies on session state.
[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 = 20Authenticating clients with auth_file and auth_query
With auth_file, PgBouncer reads usernames and password hashes from a text file. Each line has the form "user" "hash". With auth_query, PgBouncer runs a query against PostgreSQL to fetch the hash for a user, so you do not maintain a separate file. Pair auth_query with a low-privilege auth_user role.
What breaks under transaction pooling
In transaction mode, the next transaction from a client may run on a different server connection. Session-level state does not follow the client. Session SET commands, session advisory locks, LISTEN, and temporary tables can all disappear or land on the wrong client. Use SET LOCAL inside a transaction instead:
BEGIN;
SET LOCAL statement_timeout = '5s';
SELECT count(*) FROM orders;
COMMIT;Prepared statements and PgBouncer
Protocol-level prepared statements belong to one server connection. Under transaction pooling, a later transaction may run on a server that never saw the statement, which produces errors such as "prepared statement does not exist." PgBouncer 1.21 and later can track these statements when max_prepared_statements is greater than zero.
> Hmm
Sizing pools and connection limits
Each pool opens at most default_pool_size server connections per user and database pair. The total across all pools must stay below PostgreSQL's max_connections, with room left for superuser and admin connections. max_client_conn limits client connections to PgBouncer and can be far larger than the server pool.
Exercise
A pool has defaultpoolsize = 20 and there are 3 pools (3 user and database pairs). PostgreSQL has max_connections = 100. Does this configuration leave a safe margin?
Show answer
Yes. The pools can open up to 60 server connections, which is 60 percent of 100 and leaves 40 for superuser and admin use.