Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

After putting PgBouncer in transaction mode in front of a Spring Boot service using the PostgreSQL JDBC driver, errors appear: 'ERROR: prepared statement "S_3" does not exist'. Explain and fix.

The PostgreSQL JDBC driver switches a statement to a named server-side prepared statement, such as S_3, after it has run it prepareThreshold times (5 by default), and later executes it by name. In PgBouncer's transaction mode the next transaction can run on a different server connection where S_3 was never prepared, so PostgreSQL reports that it does not exist. We fix it by setting prepareThreshold=0 in the JDBC URL, or by enabling PgBouncer's prepared statement support with max_prepared_statements on version 1.21 or later, and then we check the service for other session state it depends on.

Why this question is asked

This error is one of the first things teams hit after adding PgBouncer in transaction mode, and it is confusing because it is intermittent: the application works for a while, then fails on queries that ran fine a minute ago. Interviewers ask it because the answer needs us to connect three pieces: how the JDBC driver prepares statements, how transaction mode moves us between server connections, and which other features depend on staying on one connection. In this answer, we will recap prepared statements in the driver, reproduce the failure step by step, apply both fixes, and then review the other session state, pool settings and testing.

1A Quick Recap: How the JDBC Driver Prepares Statements

A prepared statement is a query whose text is parsed and planned once, then executed many times with different parameters. The PostgreSQL protocol supports two kinds. An unnamed statement lives only until the next one replaces it, so it is used once. A named statement, such as S_3, stays on that server connection until it is closed, and can be executed again by name without sending the text.

The PostgreSQL JDBC driver, pgjdbc, uses unnamed statements at first. When the same PreparedStatement has been executed prepareThreshold times, 5 by default, the driver decides it is worth keeping and prepares it as a named server-side statement, with names S_1, S_2 and so on. From then on it sends only the name and the parameters. This saves parsing and planning time, and it is completely safe as long as every execution happens on the same server connection. With a direct connection or with PgBouncer in session mode, that is always true.

2Reproducing the Failure

In transaction mode, PgBouncer gives our client connection a server connection only for one transaction. The driver does not know this; it believes it is talking to one server the whole time, so it remembers that S_3 exists on its connection.

Java
// HikariCP connection -> PgBouncer (pool_mode = transaction) -> PostgreSQL
for (int i = 1; i <= 7; i++) {
try (var ps = conn.prepareStatement("SELECT * FROM orders WHERE id = ?")) {
ps.setLong(1, i);
ps.executeQuery();
}
conn.commit();
}
// runs 1-4: unnamed statements, fine
// run 5: driver prepares named S_3 on server connection A, fine
// run 6: PgBouncer gives server connection B
// ERROR: prepared statement "S_3" does not exist
Step throughWhy S_3 disappears
JDBC driverPgBouncerServer conn AServer conn B
tx 5: Parse S_3, Execute S_3
runs on A: S_3 now exists on A
COMMIT: A goes back to the pool
tx 6: Execute S_3 (no Parse, driver thinks it exists)
runs on B
ERROR: prepared statement S_3 does not exist

6 messages in order. Play them, or step through them one at a time.

The driver tracks statements per client connection, but they live on server connections.

Notice that the first few executions always work, which is why the problem appears only after warm-up, and why it is intermittent: if PgBouncer happens to give back the same server connection, run 6 works too. The opposite error, prepared statement S_3 already exists, appears when the driver prepares a new S_3 on a server connection where another client already left one.

3Fix 1: Turn Off Server-Side Prepares in the Driver

Setting prepareThreshold=0 tells pgjdbc never to switch to named statements. Every execution uses the unnamed statement, which is parsed and executed within the same request, so it never relies on a previous transaction's server connection.

Properties
spring.datasource.url=jdbc:postgresql://pgbouncer:6432/shop?prepareThreshold=0

This works with any PgBouncer version. The cost is that each execution is parsed and planned again, which for typical short OLTP queries adds a small amount of CPU on the database, often a few percent. For most services it is a fine trade.

4Fix 2: Let PgBouncer Track Prepared Statements

PgBouncer 1.21 added support for protocol-level named prepared statements in transaction mode. With max_prepared_statements set above zero, PgBouncer remembers each statement a client prepares. When that client's next transaction lands on a different server connection, PgBouncer prepares the statement there first, under its own internal name, and then runs it. The driver keeps its server-side prepares and their planning savings.

Java
; pgbouncer.ini
[pgbouncer]
pool_mode = transaction
max_prepared_statements = 200 ; per server connection; 0 disables the feature
-- check the version first
SHOW VERSION; -- in the PgBouncer admin console
-- PgBouncer 1.23.1

This only covers prepares sent through the protocol, which is what JDBC does, not SQL PREPARE statements. The default for max_prepared_statements has changed between releases, so check your version. With this in place, we can remove prepareThreshold=0 and keep the driver's default.

5Review the Other Session State

Prepared statements are the loudest problem, but not the only one. Anything that lives on a server connection beyond one transaction is unreliable in transaction mode. We search the service for a plain SET such as SET search_path or SET TIME ZONE, which must become SET LOCAL inside the transaction or be moved into the connection settings of the role. Temporary tables that are created in one transaction and read in another must change. Session advisory locks with pg_advisory_lock must become pg_advisory_xact_lock, which is released at commit. And features such as LISTEN need their own session-mode pool.

Session state in transaction mode
FeatureSafe?What to do
Named prepared statementsonly with max_prepared_statementsprepareThreshold=0 or PgBouncer 1.21+
SET search_path / SET TIME ZONEnoSET LOCAL, or ALTER ROLE ... SET
Temporary tables across transactionsnouse them within one transaction
pg_advisory_lock (session)nopg_advisory_xact_lock
LISTEN / NOTIFY consumernoa separate session-mode pool

6Pool Settings and Testing

With PgBouncer doing the multiplexing, HikariCP pools can stay small, for example 10 per pod, because the expensive server connections are now governed by PgBouncer's default_pool_size and max_db_connections. HikariCP's maxLifetime should be shorter than any limit that closes client connections from the outside, such as PgBouncer's client_idle_timeout if it is set or an idle timeout on a load balancer, so Hikari retires connections before they are cut. PgBouncer's server_lifetime only recycles its own server connections while they are idle, so it does not break Hikari's connections.

Finally, we test the unhappy paths through PgBouncer: restart PgBouncer, restart or fail over the database, and check that the service recovers, that HikariCP drops broken connections, and that no prepared statement errors return after the reconnects.

7Follow-up questions

Why does the error only appear after a few minutes of traffic?

Because pgjdbc uses unnamed statements for the first prepareThreshold executions of each statement, 5 by default. Only after that does it prepare a named statement and start executing by name, and only when a later transaction lands on another server connection does the error appear.

Does prepareThreshold=0 hurt performance a lot?

Usually not. Each execution is parsed and planned again, which adds some database CPU for short queries. For services dominated by simple primary key lookups it is often unnoticeable; for complex queries executed very often, PgBouncer's prepared statement support is the better fix.

Would session mode fix it?

Yes, because each client keeps one server connection, but then every HikariCP connection holds a server connection all day, and most of PgBouncer's benefit is gone.

8Conclusion

In this answer, we saw that pgjdbc switches a statement to a named server-side prepared statement after prepareThreshold executions and then runs it by name, while PgBouncer's transaction mode can put the next transaction on a different server connection where that statement does not exist. We fixed it with prepareThreshold=0 in the JDBC URL or with max_prepared_statements in PgBouncer 1.21 and later, reviewed the other session state the service relies on, kept HikariCP pools small with a maxLifetime below any limit that cuts client connections, and tested restarts and failover through PgBouncer.

What to say in the interviewAbout 80 seconds aloud

Open with

The JDBC driver uses unnamed statements at first, but after prepareThreshold executions, 5 by default, it prepares the statement as a named server-side statement, S_3 here, and from then on just executes it by name.

Then, if they want more

That assumes we stay on the same server connection. In transaction mode PgBouncer only lends us a server connection for one transaction, so the next transaction can land on another server connection where S_3 was never prepared, and PostgreSQL says it does not exist. It is intermittent because sometimes we get the same connection back.

The quick fix is prepareThreshold=0 in the JDBC URL, which turns off named prepares; it costs a bit of parse and plan time. The better fix, if we run PgBouncer 1.21 or later, is max_prepared_statements, where PgBouncer tracks each client's prepared statements and re-prepares them on whichever server connection the client gets.

Then I would check the rest of the session state: plain SET commands like search_path should be SET LOCAL or role settings, temp tables must stay inside one transaction, session advisory locks become transaction-level ones, and LISTEN needs a session-mode pool.

HikariCP pools can stay small, with maxLifetime below any client-side idle timeout, and I would test PgBouncer and database restarts to make sure the service recovers cleanly.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
PostgreSQL documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "After putting PgBouncer in transaction mode in front of a Spring Boot service using the...": https://scrivio-interview-library.netlify.app/databases/postgresql/21bdae156b/