Sub topic 8
Prepared statements and PgBouncer
This chapter explains why prepared statements fail under transaction pooling, how PgBouncer 1.21 and later can track them, and how to configure your driver when it cannot. It assumes you have read the chapters on pool modes and on what breaks under transaction pooling. You should also be comfortable with psql and with the difference between a session and a transaction in PostgreSQL.
What a prepared statement is
A prepared statement is a query that PostgreSQL parses and plans in advance under a name. The client then runs it repeatedly with different parameter values. This saves parse time and prevents SQL injection through parameter binding.
There are two ways to prepare a statement:
- SQL level. You run
PREPARE name AS ...and laterEXECUTE name (...)as ordinary SQL commands. - Protocol level. The driver sends the wire-protocol messages
Parse,Bind,Describe,Execute, andClose. Most drivers use this, often without you noticing. A namedParsecreates a named prepared statement.
In both cases the prepared statement belongs to one server connection. It lives in that backend process's memory and disappears when the connection closes. Other connections cannot see it.
Why transaction pooling breaks them
In session mode a client keeps the same server connection until it disconnects, so its prepared statements stay available. In transaction mode a server connection returns to the pool after each transaction. The next transaction from the same client may run on a different server connection.
The sequence looks like this:
You will see one of two errors, depending on timing:
ERROR: prepared statement "S_1" does not exist. The client assumes the statement exists, but the server connection it landed on has never seen it.ERROR: prepared statement "S_1" already exists. The client prepares a name again, and the server connection it landed on already holds that name from another client.
Both errors are intermittent. They depend on which pooled connection a transaction receives. A low-traffic test can pass while production fails, because with few clients the same server connection is usually reused.
Option 1: let PgBouncer track protocol-level statements
PgBouncer 1.21 added support for protocol-level prepared statements in transaction mode. Enable it with max_prepared_statements. The default is 0, which leaves the feature off.
[pgbouncer]
pool_mode = transaction
max_prepared_statements = 100When the setting is non-zero, PgBouncer does the following:
- It intercepts each named
Parsemessage from a client and remembers the statement text for that client under the client's own name. - It rewrites the name to an internal one before it forwards the message, so two clients that both choose
S_1do not collide on the same server connection. - When a client sends
BindorDescribefor a statement, PgBouncer checks whether the assigned server connection already has it. If it does not, PgBouncer sends theParsefirst, then theBind. - It forgets a statement when the client sends
Closeor disconnects.
The client sees an ordinary session in which its statements persist. The server connection only holds the statements it has actually needed.
The value of max_prepared_statements is a limit on how many prepared statements PgBouncer tracks for each server connection. Each tracked statement uses memory in PgBouncer and in the PostgreSQL backend, so do not set it much higher than your applications use. A value around 100 is a common starting point. If a server connection accumulates more than the limit, PgBouncer closes the least recently used ones on that connection.
Limits of this feature
- Only protocol-level statements are tracked. SQL-level
PREPAREandEXECUTEcommands are plain query text to PgBouncer. They still break in transaction mode. - It needs PgBouncer 1.21 or later. Check with
SHOW VERSION;on the admin console. On older versions the setting does not exist. - It does not change other session state.
SET, advisory locks,LISTEN, and temporary tables still cannot be used safely in transaction mode. - It adds some per-query work. PgBouncer must inspect and track messages. For most workloads the cost is small compared with the cost of disabling prepared statements.
Check your own version's documentation before relying on details. Features in this area have changed between releases.
Option 2: turn off named prepared statements in the driver
If you run an older PgBouncer, or you use SQL-level PREPARE, configure the client so it does not rely on named statements surviving between transactions. Most drivers have a setting for this. The table lists common ones. Names and defaults change between versions, so confirm them in your driver's documentation.
| Driver or framework | Setting |
|---|---|
| PostgreSQL JDBC | `prepareThreshold=0` in the connection URL |
| psycopg 3 (Python) | `prepare_threshold=None` on `connect()` |
| asyncpg (Python) | `statement_cache_size=0` on `connect()` or `create_pool()` |
| Ruby on Rails | `prepared_statements: false` in `database.yml` |
| Npgsql (.NET) | `Max Auto Prepare=0` and avoid explicit `Prepare()` calls |
| Prisma | `pgbouncer=true` in the connection string |
When a driver does not prepare statements, it sends each query with unnamed (or no) prepared statements. The unnamed statement is parsed and bound within one Parse/Bind/Execute cycle that completes inside a single transaction, so any server connection can run it. You lose the saved parse time, which is usually small compared with network round trips.
Here is psycopg 3 configured this way. The only change from a direct connection is the port and the prepare_threshold setting:
import psycopg
# Port 6432 is PgBouncer. prepare_threshold=None means psycopg never
# creates server-side named prepared statements on its own.
with psycopg.connect(
"postgresql://[email protected]:6432/appdb",
prepare_threshold=None,
) as conn:
with conn.cursor() as cur:
for order_id in (1, 2, 3):
cur.execute("SELECT status FROM orders WHERE id = %s", (order_id,))
print(cur.fetchone())For JDBC, the setting goes in the URL:
jdbc:postgresql://127.0.0.1:6432/appdb?prepareThreshold=0If you use asyncpg, note that disabling the cache with statement_cache_size=0 is the documented way to use it with PgBouncer in transaction mode on versions without prepared-statement support.
Option 3: use session mode for that workload
If an application depends heavily on PREPARE/EXECUTE or on other session state, give it its own pool entry in session mode. The [databases] section lets you define two names for the same database with different pool modes:
[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb
appdb_batch = host=127.0.0.1 port=5432 dbname=appdb pool_mode=session pool_size=5
[pgbouncer]
pool_mode = transaction
max_prepared_statements = 100The batch job connects to appdb_batch. Everything else uses the transaction pool. This keeps the benefit of multiplexing for web traffic and avoids rewriting the batch code. The cost is that session-mode clients hold a server connection for their whole lifetime, so size that pool, and its share of max_connections, deliberately.
Choosing between the options
| Situation | Choice |
|---|---|
| PgBouncer 1.21+, driver uses protocol-level named statements | Set `max_prepared_statements` |
| PgBouncer older than 1.21 | Disable named statements in the driver, or upgrade |
| Code uses SQL `PREPARE` and `EXECUTE` | Rewrite to parameterized queries, or use a session-mode pool |
| Heavy use of other session features too | Session-mode pool for that application |
Checking that it works
Test with concurrency, not a single connection. A reliable approach is to set default_pool_size = 2 in a test environment and run several client connections that each execute the same parameterized query in a loop. With a tiny pool, the same server connection is shared constantly, so errors appear quickly if tracking is not working.
You can also look at the server side. Run this on PostgreSQL itself, not through PgBouncer:
SELECT count(*) AS prepared_statements
FROM pg_prepared_statements;This view lists only the prepared statements of your own session, so it shows the statements held by whichever connection you are on. To see the effect across all server connections, run it from a session-mode connection that you control, or check driver logs for the does not exist and already exists errors. A clean run with no such errors under a small pool is good evidence.
Common mistakes
- Enabling
max_prepared_statementsand expecting SQLPREPAREto work. The feature handles protocol messages only. - Setting it too low. If it is smaller than the number of distinct statements a client uses, PgBouncer closes and reparses statements frequently, which removes the benefit.
- Fixing the error by switching the whole pool to session mode. This works but gives up multiplexing, and
max_connectionspressure returns. - Testing with one client. The failure needs at least two clients sharing a server connection.
Exercise
An application uses a driver that creates named protocol-level prepared statements. It connects to PgBouncer 1.22 in transaction mode and intermittently fails with prepared statement "S_3" does not exist. Name two ways to fix it without changing the pool mode, and say which one you would try first.
Show answer
One fix is to set max_prepared_statements to a non-zero value such as 100 in the [pgbouncer] section and reload, so PgBouncer tracks the statements and re-prepares them on whichever server connection a transaction receives. The other is to disable named prepared statements in the driver, for example prepareThreshold=0 for JDBC or prepare_threshold=None for psycopg 3. Try max_prepared_statements first. The version already supports it, it needs no application change, and it keeps the benefit of prepared statements.
Exercise
After you set max_prepared_statements = 100, a script that runs PREPARE q AS SELECT 1; in one transaction and EXECUTE q; in the next still fails sometimes. Why, and what are your options?
Show answer
max_prepared_statements tracks only protocol-level Parse/Bind messages. PREPARE and EXECUTE sent as SQL text are not tracked, so the prepared statement exists only on the server connection that ran PREPARE. Rewrite the script to use parameterized queries through the driver, or point the script at a session-mode pool entry (for example pool_mode=session on a separate [databases] entry) so it keeps one server connection.