Sub topic 5
Choosing a pool mode
This chapter assumes you can read a basic pgbouncer.ini, know that PgBouncer maps many client connections onto fewer server connections, and understand PostgreSQL sessions, transactions, and max_connections. The pool mode decides when a server connection goes back to the pool for another client to use. It is the most consequential setting in the file, because it controls both how well you multiplex and which PostgreSQL features still work.
The three modes
PgBouncer offers three values for pool_mode. They differ only in the moment a server connection is released.
| Mode | Server connection released | Multiplexing | Compatibility |
|---|---|---|---|
| `session` | When the client disconnects | Low | Full PostgreSQL behavior |
| `transaction` | When the transaction ends | High | Session state is not preserved |
| `statement` | After every statement | Highest | Multi-statement transactions are rejected |
You set the mode globally in the [pgbouncer] section. You can override it for one database in the [databases] section, or for one user with a pool_mode= entry in the connection string for that database.
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
reports = host=127.0.0.1 port=5432 dbname=reports pool_mode=session
[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
default_pool_size = 20
max_client_conn = 1000Here appdb uses transaction pooling by default, while reports keeps a dedicated server connection for each client for the whole session.
Session pooling
In session mode, a client that connects is assigned a server connection and keeps it until it disconnects. After the client leaves, PgBouncer runs the server_reset_query (by default DISCARD ALL in session mode) to clean the connection, then returns it to the pool.
Session mode is the safest choice. Everything PostgreSQL offers inside a session works: SET, temporary tables, advisory locks, LISTEN/NOTIFY, WITH HOLD cursors, and protocol-level prepared statements.
The cost is that a client that is connected but idle still holds a server connection. If your application keeps 500 idle connections open, session mode needs 500 server connections for them. It mainly helps when clients connect and disconnect often, because PgBouncer reuses warm server connections instead of forking a new backend process each time.
Transaction pooling
In transaction mode, a client gets a server connection when it starts a transaction and gives it back at COMMIT or ROLLBACK. A statement outside an explicit transaction counts as its own one-statement transaction. Between transactions, the client has no server connection, so an idle client costs PostgreSQL nothing.
This is the mode that delivers the large ratios. A web application with 1000 client connections that each run a short transaction a few times per second may need only 20 server connections.
The price is that two consecutive transactions from one client can run on different server connections, and two clients can take turns on the same one. Anything stored in the session can therefore leak to a different client or disappear. The next chapter covers these failures in detail. The most common example is a session-level SET:
-- Unsafe in transaction mode: the setting may land on a server connection
-- that a different client uses next.
SET statement_timeout = '5s';
-- Safe: the setting lasts only until the end of this transaction.
BEGIN;
SET LOCAL statement_timeout = '5s';
SELECT count(*) FROM orders;
COMMIT;Statement pooling
In statement mode, the server connection is released after each statement. PgBouncer enforces this by refusing multi-statement transactions: a client that sends BEGIN and then more statements gets an error.
This mode suits narrow workloads in which every query is an independent, autocommit statement, such as simple key lookups from a very large number of clients. It gives the best multiplexing, but you lose transactions entirely. Few applications qualify, and most should not use it.
What each mode does to a connection
The diagram shows the lifetime of a server connection from one client's point of view.
Decision criteria
Start from what your application needs, not from the mode you would like.
- Does the code depend on session state? If it uses session-level
SET, temporary tables, advisory locks held across transactions,LISTEN, orWITH HOLDcursors, use session mode, or change the code. - Do clients stay connected while idle? Application servers with large framework-side pools, serverless functions, and many microservice replicas usually do. Transaction mode is what lets them share a small set of server connections.
- Are transactions short? Transaction pooling works best when each transaction takes milliseconds. A transaction that runs for minutes holds its server connection the whole time and works like a session-mode client.
- Do you need multi-statement transactions? If yes, statement mode is out.
A common pattern is mixed: run most application traffic through a transaction-mode database entry and give jobs that need session features (migrations, pg_dump, reporting tools, LISTEN consumers) a separate session-mode entry that points at the same PostgreSQL database.
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb pool_mode=transaction
appdb_session = host=127.0.0.1 port=5432 dbname=appdb pool_mode=session pool_size=5Clients choose the behavior by connecting to appdb or appdb_session. Both entries refer to the same dbname, but PgBouncer keeps a separate pool for each.
Edge cases and gotchas
- Pools are per user and database pair. With
default_pool_size = 20, ten distinct users on one database can create up to 200 server connections. Mixed modes multiply this further, since each alias is its own pool. Count all pools when you compare the total against PostgreSQL'smax_connections. - Resetting between clients. In transaction mode, PgBouncer does not run
server_reset_querybetween transactions by default. It is only used whenserver_reset_query_alwaysis on. State that a client leaves behind therefore survives for the next client. This is the reason session-level changes are dangerous. - Long transactions defeat the benefit. An application that opens a transaction, calls a slow external service, then commits will hold server connections as long as it would in session mode. Fix this in the application by keeping external calls outside the transaction.
- Autocommit drivers. Some drivers send
BEGINimplicitly and keep a transaction open after a read. In transaction mode, that connection stays pinned until the driver commits. Check that your driver commits or rolls back at the end of each unit of work. - Protocol-level prepared statements. These depend on session state, so older PgBouncer versions fail with errors like
prepared statement "S_1" does not existin transaction mode. Recent releases can track them withmax_prepared_statements. A later chapter covers this. - Changing modes at runtime. Edit
pgbouncer.iniand runRELOAD;on the admin console. New transactions follow the new setting, but test it first, because clients written for one mode can fail in another.
Trying it
To compare modes yourself, point a client at each pool and watch SHOW POOLS; on the admin console. In session mode, cl_active and sv_active rise together as clients connect. In transaction mode, many clients can show as cl_active while sv_active stays small.
# Open 100 concurrent clients that each run short transactions for 30 seconds
pgbench -h 127.0.0.1 -p 6432 -U app_user -c 100 -j 4 -T 30 appdbWhile that runs, in a second terminal:
psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW POOLS;"With pool_mode = transaction and default_pool_size = 20, the pool should use at most about 20 server connections for the 100 clients. With pool_mode = session, PgBouncer uses 20 server connections and the remaining clients wait, which shows in cl_waiting. The mode, not the client count, sets how far PostgreSQL's load is reduced.
Exercise
An application runs 300 idle-most-of-the-time web workers. Each executes short read and write transactions. It also runs a nightly job that creates a temporary table and uses an advisory lock for the whole session. Which pool modes would you configure, and how would you route the traffic?
Show answer
Use transaction mode for the web workers, because they are idle most of the time and their transactions are short, so a small pool serves all 300. Give the nightly job a separate database entry in session mode (for example appdb_session with a small pool_size), because temporary tables and session-level advisory locks require the same server connection for the whole session. Both entries can point at the same PostgreSQL database. Remember to count both pools when comparing against max_connections.
Exercise
Why does SET LOCAL statement_timeout = '5s' inside BEGIN ... COMMIT work in transaction mode when a plain SET statement_timeout = '5s' does not?
Show answer
A plain SET changes the session and stays in effect after the transaction ends, so it remains on a server connection that PgBouncer may give to a different client. SET LOCAL lasts only until the end of the current transaction, and PgBouncer keeps the same server connection for exactly that long, so the setting is gone before the connection is reused.