Sub topic 7
What breaks under transaction pooling
This chapter assumes you know PostgreSQL sessions, SET, and transactions, and that you have a working pgbouncer.ini with pool_mode = transaction. It covers the session features that stop working in that mode, why they fail, and how to replace them.
Why transaction mode changes the rules
In transaction mode, PgBouncer assigns a server connection to a client when the client starts a transaction. It takes the connection back when the transaction ends. Between transactions the client has no server connection. The next transaction from the same client can run on a different PostgreSQL backend, and that backend may have just served someone else.
PostgreSQL keeps many things per session, meaning per backend process. Those things stay on the backend when the client leaves. They are then either visible to the next client or invisible to the original client on its next transaction.
By default PgBouncer does not reset the server connection after each transaction in this mode. The server_reset_query setting, which defaults to DISCARD ALL, applies only to session mode unless you set server_reset_query_always = 1. Resetting after every transaction costs extra round trips and discards prepared statements and other state. Most deployments therefore change the application instead.
Features that break
| Session feature | What goes wrong | Replacement |
|---|---|---|
| `SET` / `SET SESSION` | Setting persists on a shared backend, or is missing on the next transaction | `SET LOCAL`, or role/database defaults |
| Session advisory locks (`pg_advisory_lock`) | Lock is held by a backend that other clients reuse, and unlock may run on a different backend | `pg_advisory_xact_lock` |
| `LISTEN` / `NOTIFY` | Listener registration stays on one backend, and notifications arrive on a connection the client no longer owns | Direct connection or a session-mode pool for listeners |
| Temporary tables | Table exists only on one backend, so the next transaction may not find it | `ON COMMIT DROP` inside one transaction, or regular tables |
| `WITH HOLD` cursors | Cursor lives on a backend the client may not get back | Fetch inside one transaction, or use keyset pagination |
| SQL-level `PREPARE` / `EXECUTE` | Statement exists on one backend only | See the next chapter on prepared statements |
| `SET ROLE`, `SET SESSION AUTHORIZATION` | Identity change leaks to the next client | `SET LOCAL ROLE` inside a transaction |
The failures fall into two kinds. Some are leaks: state stays behind and another client inherits it, which is a correctness and security problem. Others are lost state: the client expects something and finds nothing, which usually shows up as an error. Leaks are the more dangerous kind, because nothing fails visibly.
Session settings
The most common problem is a connection-level SET. The example below is safe and unsafe side by side.
-- 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;SET LOCAL reverts at COMMIT or ROLLBACK, so nothing is left on the backend. If you need SET LOCAL on every transaction, wrap it in your data-access layer so each transaction starts with the same preamble.
A SET LOCAL outside an explicit transaction block does nothing useful. PostgreSQL warns that it can only be used in transaction blocks, because in autocommit mode the statement is its own transaction and the setting is gone immediately. The setting would also not reach your next statement, which is a separate transaction.
For settings that never change per request, move them out of the application:
ALTER ROLE app_user SET statement_timeout = '30s';
ALTER ROLE app_user IN DATABASE appdb SET search_path = app, public;Role and database defaults apply when PostgreSQL starts a new backend session for that role. PgBouncer opens server connections as the pool's user, so every backend in that pool starts with the same defaults. That makes them safe under any pool mode.
Some startup parameters such as client_encoding, DateStyle, TimeZone, standard_conforming_strings, and application_name are tracked by PgBouncer and applied to server connections for you. Other startup parameters are rejected unless you list them in ignore_startup_parameters. Ignoring a parameter means the client's request is silently not applied, so do it only for parameters you do not depend on.
Locks
A session-level advisory lock belongs to the backend, not to the client:
-- Breaks under transaction pooling
SELECT pg_advisory_lock(42);
-- ... later, possibly on another backend ...
SELECT pg_advisory_unlock(42);The lock stays on the first backend. The unlock runs on a different backend, returns false, and releases nothing. The first backend then keeps the lock until it disconnects, and other clients block on it. The transaction-scoped variant fixes this:
BEGIN;
SELECT pg_advisory_xact_lock(42);
-- critical section: the lock is held for the rest of this transaction
UPDATE jobs SET state = 'running' WHERE id = 7;
COMMIT; -- lock released automaticallyIf the critical section must span several transactions, transaction pooling is the wrong tool for that code path. Route it through a session-mode pool.
LISTEN, temp tables, and cursors
LISTEN registers the backend to receive notifications. After the transaction ends, the registration stays on a backend that your client may never see again. Another client is then silently given that backend, and your client receives nothing. Run listeners on a direct connection to PostgreSQL, or on a session-mode alias.
Temporary tables are visible only to the backend that created them, and they last until the session ends unless declared otherwise. This version is safe because it never outlives one transaction:
BEGIN;
CREATE TEMP TABLE staging (id int, total numeric) ON COMMIT DROP;
INSERT INTO staging SELECT id, sum(amount) FROM payments GROUP BY id;
SELECT count(*) FROM staging;
COMMIT; -- staging is dropped hereA plain CREATE TEMP TABLE followed by queries in later transactions fails or, worse, finds a stale table left by a previous client of that backend.
A session-mode alias for the exceptions
You do not have to choose one pool mode for the whole system. A second entry in [databases] can point at the same database with a different mode:
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
appdb_session = host=127.0.0.1 port=5432 dbname=appdb pool_mode=sessionThe pool_mode key on a database entry overrides the global setting. Web request handlers connect to appdb. Schedulers, migration tools, and LISTEN workers connect to appdb_session. Each alias has its own pool, so size default_pool_size knowing both pools draw from the same PostgreSQL max_connections.
A checklist for migrating
- Search for
SET,pg_advisory_lock,LISTEN,CREATE TEMP,DECLARE ... WITH HOLD, andPREPAREin application code and migrations. - Convert each
SETtoSET LOCALinside a transaction, or move it toALTER ROLE ... SET. - Replace session advisory locks with
pg_advisory_xact_lock, or move that code to a session-mode alias. - Move listeners and long-lived session users to a direct connection or a session-mode alias.
- Run the test suite against PgBouncer with
default_pool_size = 1.
Exercise
A job runner calls SELECT pg_advisory_lock(7), runs three separate transactions through PgBouncer in transaction mode, then calls SELECT pg_advisory_unlock(7). Occasionally other workers hang waiting for lock 7 long after the job has finished. Explain why, and give two ways to fix it.
Show answer
The lock is held by the backend that ran pg_advisory_lock, not by the client. After that transaction ends, PgBouncer can give the client a different backend, so pg_advisory_unlock runs on a backend that does not hold the lock and returns false. The original backend keeps the lock until it disconnects, so other workers block. Fix 1: use pg_advisory_xact_lock(7) inside one transaction that covers the protected work, so the lock is released at commit. Fix 2: send the job runner through a session-mode alias (a [databases] entry with pool_mode=session) so the same backend is held for the whole session.