With PgBouncer in transaction mode, why do driver prepared statements work while SQL PREPARE and EXECUTE fail, and what does max_prepared_statements control?
answer
- protocol messages vs SQL text
- renamed to PGBOUNCER_ ids
- re-prepared on demand
- LRU per server, default 200
basics
~10 sPgBouncer 1.21+ tracks protocol-level named prepared statements, renames them and re-prepares them on whichever server a client gets; SQL PREPARE is passed through untracked. max_prepared_statements, default 200 since 1.24, sizes the per-server cache.
solid answer
~40 sSince 1.21, PgBouncer inspects the extended protocol's `Parse`, `Bind`, `Describe` and `Close` messages in transaction and statement mode. Each unique query text gets an internal name `PGBOUNCER_<id>`, shared by every client that prepares the same text; PgBouncer rewrites the client's name to it and, if the current server has not prepared it yet, prepares it there first. SQL-level `PREPARE`, `EXECUTE` and `DEALLOCATE` are plain query text and are forwarded untouched, so `EXECUTE` on another backend fails with `prepared statement ... does not exist`; only `DEALLOCATE ALL` and `DISCARD ALL` are handled. `max_prepared_statements` is the size of the LRU cache of statements kept prepared on each server connection; 0 disables the feature, and the default has been 200 since 1.24, although the sample `pgbouncer.ini` still shows a commented 0.
code
sql · 8 lines-- Through PgBouncer, pool_mode = transaction
PREPARE hold_seat(bigint, uuid) AS
INSERT INTO seat_hold (seat_id, held_by, expires_at)
VALUES ($1, $2, now() + interval '5 minutes');
-- A later transaction may be served by another backend:
EXECUTE hold_seat(4711, '0b9e2c5a-6f1d-4c1e-9a77-2f4f1d3e8a10');
-- ERROR: prepared statement "hold_seat" does not existgo deeper
Remember that prepared statements live in one backend session, so transaction pooling needs special handling for them.
Explain the difference between protocol-level and SQL-level prepared statements and why PgBouncer can only rewrite the first kind.
Know the release facts (1.21 support, 1.24 default of 200), size the per-server cache, and recognise the result-type error after migrations and the RECONNECT fix.
Weigh parse-and-plan savings against server memory per backend and PgBouncer CPU, and decide when to scale out with so_reuseport.
## Two kinds of prepared statement PostgreSQL offers prepared statements at two levels, and PgBouncer treats them completely differently. | | Protocol-level (extended query protocol) | SQL-level | |---|---|---| | How it is sent | `Parse` / `Bind` / `Execute` messages, usually by the driver | `PREPARE name AS ...`, `EXECUTE name(...)` as query text | | Seen by PgBouncer as | structured messages it can inspect | an opaque SQL string | | Transaction mode, PgBouncer 1.21+ | tracked and re-prepared when `max_prepared_statements` > 0 | forwarded untouched, breaks | A **prepared statement** lives in one backend's session. Under **transaction pooling** a client's next transaction may run on a different backend, so a statement prepared in one transaction may not exist where the next one runs. ## How PgBouncer tracks protocol-level statements PgBouncer **1.21** added support for named protocol-level prepared statements in transaction and statement mode: 1. When a client sends `Parse` with a name, PgBouncer gives the query text an internal name `PGBOUNCER_<id>`. The same text prepared by any client shares one internal name. 2. PgBouncer records which client name maps to which internal name and rewrites later `Bind`, `Describe` and `Close` messages before forwarding them. 3. If the server connection the client now holds has not prepared that statement, PgBouncer **prepares it there first, transparently**, then runs it. The server only ever sees the internal names. A side benefit is sharing: with a `pool_size` of 20 and 100 clients preparing the same query, PostgreSQL parses it only 20 times. ## What `max_prepared_statements` controls The value is the number of statements kept prepared, in an **LRU cache**, on **each server connection**. It is not a per-client quota. - **0** disables prepared-statement support for transaction and statement pooling. - **200** is the default since **1.24**. The sample `pgbouncer.ini` still shows `;max_prepared_statements = 0`, so never read the default from it. - Set it above the number of statements your application uses regularly, or statements are evicted and re-prepared over and over. - The cost lands on both sides: more prepared plans in every PostgreSQL backend's memory, plus a global query-text cache and a rewrite buffer of up to four times `pkt_buf` per client inside PgBouncer, and extra CPU to inspect and rewrite packets. PgBouncer's own documentation sizes the PgBouncer side for 1,000 active clients preparing 200 unique queries of about 5 kB with the default 4 kB `pkt_buf`: 200 x 5 kB plus 1,000 x 4 x 4 kB, roughly 17 MB, which is small. The server side usually matters more, because every backend in every pool may hold up to the full cache of plans. Because PgBouncer is single-threaded, CPU-bound setups run several processes on one port with `so_reuseport`. - Since 1.26 PgBouncer reports `pgbouncer.max_prepared_statements` to clients at login, so a driver can see whether support is on. ## What still breaks - **SQL-level `PREPARE` / `EXECUTE` / `DEALLOCATE`** are forwarded as text. An `EXECUTE` that lands on another backend fails with SQLSTATE 26000, `prepared statement "..." does not exist`; a second `PREPARE` of the same name on a backend that already has it fails with 42P05, `already exists`. Since 1.22, `DEALLOCATE ALL` and `DISCARD ALL` are the exceptions: they clear the client's tracked statements as expected. - **Changed result types after a migration.** Because clients share one server-side statement per query text, adding a column to a table that a `SELECT *` statement reads can make PostgreSQL raise `cached plan must not change result type`. Running `RECONNECT` on the PgBouncer admin console after the migration closes the server connections as they are released, so statements are prepared afresh. - **Drivers that use only unnamed statements** gain nothing from the cache; the benefit appears only when the driver names and reuses statements. ## A worked example In the ticketing fleet, each serverless invocation reserves a seat with the same `INSERT`. With the driver preparing a named statement and `max_prepared_statements = 200`, the statement is parsed once per server connection and reused by every invocation. Written instead as SQL `PREPARE hold_seat ...` followed by `EXECUTE hold_seat(...)` in separate transactions, it fails intermittently, only under load, when the two transactions are served by different backends.
- After a migration adds a column, clients behind PgBouncer start failing with 'cached plan must not change result type'. Why, and what do you do?PgBouncer shares one server-side prepared statement per query text, and PostgreSQL refuses to change a cached statement's result type, as when `SELECT *` gains a column. Run `RECONNECT` on the admin console: server connections close as they are released and statements are prepared afresh. Naming columns instead of `SELECT *` avoids most cases.
- How should you size max_prepared_statements in PgBouncer?Make it larger than the number of distinct statements the application uses regularly, so the per-server LRU cache does not evict and re-prepare them constantly. Remember that it is per server connection: every backend holds up to that many prepared plans, which costs PostgreSQL memory.
- PgBouncer cannot be used with prepared statements in transaction mode at all.
- max_prepared_statements defaults to 0, as the sample pgbouncer.ini shows.
- PgBouncer tracks SQL-level PREPARE and EXECUTE the same way as protocol-level ones.
- max_prepared_statements caps how many statements a single client may prepare.
- A larger max_prepared_statements only costs memory inside PgBouncer.
Assumes PgBouncer 1.26: protocol-level prepared statements are supported since 1.21, DEALLOCATE ALL and DISCARD ALL since 1.22, and max_prepared_statements defaults to 200 since 1.24.