Video in progress
After putting PgBouncer between the application and PostgreSQL, "prepared statement S_1 does not exist" errors started. Why?
In transaction pooling mode, every transaction lands on an arbitrary server connection. The JDBC driver creates a prepared statement in one server session and then tries to use it in another. The fix: the prepared statement support in PgBouncer 1.21+, or turning off server-side prepare in the driver.
📖 Answer
PgBouncer's three modes:
- session: the client connection is tied to one server connection for the whole session. Safe, but saves little;
- transaction: a server connection is given out only for the length of a transaction. It lets you serve 2000 clients on 50 server connections;
- statement: every query stands alone, and multi-statement transactions don't work.
After PgJDBC runs the same query 5 times (prepareThreshold=5), it prepares it on the server side under the name S_1. In transaction mode, the next transaction lands on a different server connection, where S_1 doesn't exist.
The solutions:
# with an old PgBouncer, in the JDBC URL
jdbc:postgresql://pgbouncer:6432/app?prepareThreshold=0
This turns off server-side prepare. The cost: every query is parsed and planned again, and CPU goes up a bit.
PgBouncer 1.21+ has the max_prepared_statements setting: PgBouncer tracks the prepared statements itself and recreates them on the server connection where they are needed. I prefer that option now.
Some other things don't work in transaction mode either, and I check for them in review:
- session parameters set with
SET(SET LOCALworks inside a transaction); - session-level advisory locks;
LISTEN/NOTIFY;- temporary tables outside a transaction.
A Hikari pool + PgBouncer makes a two-layer pool. Keep the Hikari size small and let PgBouncer do the main multiplexing.
Sign up to mark studied questions and save your progress.