Quick revision
The short answer
The PostgreSQL JDBC driver switches a statement to a named server-side prepared statement once it has been executed prepareThreshold times (5 by default). From then on the server plans it as a prepared statement: five custom plans with the real values, then it compares a generic plan's cost with the average custom cost and may keep the generic plan, which does not know the parameter values and can pick a poor scan or join for skewed data. We fix it with plan_cache_mode = force_custom_plan for the role, session or statement, by rewriting the query, or by improving statistics, and we take care with transaction-mode PgBouncer.
What to remember
In this answer, we saw that pgjdbc moves a repeated statement to a named server-side prepared statement after prepareThreshold executions, and that the server then uses five custom plans before it may settle on a generic plan that ignores parameter values. With skewed data, that generic plan can pick a bad scan, which is why the query slows down only after several runs in one connection. We fix it with a scoped plan_cache_mode = force_custom_plan, a rewrite or better statistics, and we check PgBouncer's prepared statement support in transaction mode.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The PostgreSQL JDBC driver switches a statement to a named server-side prepared statement once it has been executed prepareThreshold times (5 by default). From then on the server plans it as a prepared statement: five custom plans with the real values, then it compares a generic plan's cost with the average custom cost and may keep the generic plan, which does not know the parameter values and can pick a poor scan or join for skewed data. We fix it with plan_cache_mode = force_custom_plan for the role, session or statement, by rewriting the query, or by improving statistics, and we take care with transaction-mode PgBouncer.
Why this question is asked
A query that is fast the first few times and then slow in the same connection looks like a ghost: the same SQL, the same values, a different speed. The explanation sits in two layers, the JDBC driver and the PostgreSQL plan cache, and the bug only appears where they meet. Interviewers ask it to see whether we understand both layers rather than blaming the network or the pool. In this answer, we will recap the protocol terms, follow what the driver does, see how the server chooses a generic plan, reproduce the slowdown, and then fix it, including the PgBouncer case.
1A Quick Recap of Prepared Statements in PostgreSQL
PostgreSQL's extended query protocol splits a query into steps: Parse sends the SQL text with placeholders, Bind supplies the parameter values, and Execute runs it. A statement can be unnamed, used once and replaced by the next, or named, kept on the server for the life of the session so it can be bound and executed again without re-parsing.
A custom plan is a plan built for specific parameter values, so the planner can use the statistics for those exact values. A generic plan is built once for a placeholder, without knowing the value, and is reused for any value. Generic plans save planning time; custom plans adapt to the data.
2What pgjdbc Does With prepareThreshold
pgjdbc, the PostgreSQL JDBC driver, does not create a named server-side statement immediately, because many statements are used only once. It counts executions of the same SQL in the connection, and once the count reaches prepareThreshold, 5 by default, it switches to a named statement that it keeps on the server, such as S_1. The driver's statement cache (preparedStatementCacheQueries) means this also works when the application calls prepareStatement each time, as connection pools and JPA do.
3How the Server Chooses a Generic Plan
Once the statement is named, the server's plan cache takes over. For the first five executions of the named statement, it builds a custom plan each time. On the next one, it also builds a generic plan and compares its estimated cost with the average cost of the custom plans so far, adding an allowance for the planning time the generic plan saves. If the generic plan is not clearly more expensive, the server switches to it and stops planning that statement.
7 messages in order. Play them, or step through them one at a time.
Two thresholds, one in the driver and one in the server, explain the delayed slowdown.
Put the two layers together and the slowdown arrives after roughly ten executions in the same connection: a handful as unnamed statements, then five custom plans on the named one, then the generic plan. The exact count depends on the driver version and settings, so check your version, but the shape is always the same: fast at first, slow later, only in long-lived connections.
4Reproducing the Slowdown
We can reproduce it in psql with PREPARE, which creates a named statement just as the driver does. Suppose jobs has 20 million rows, of which 50 have state = 'FAILED' and almost all the rest 'DONE', with an index on state.
Notice the $1 in the generic plan: the planner no longer knows the value. It assumes an average selectivity, which for a column where DONE dominates suggests that walking the primary key will quickly find 100 rows. That is right for DONE and disastrous for FAILED. pg_prepared_statements, from PostgreSQL 14, shows how many generic and custom plans the session has used, which confirms the diagnosis.
5Fixing It
The direct fix is to tell PostgreSQL to always build custom plans for this workload with plan_cache_mode = force_custom_plan. We can set it for one role, for one session from the JDBC URL, or for a single transaction around the problematic query.
The cost is planning on every execution, usually a fraction of a millisecond for a simple query, which is why we scope it instead of setting it globally. Other fixes address the cause. A rewrite can make the plan robust, for example a partial index such as CREATE INDEX ON jobs (id) WHERE state = 'FAILED' with a separate query for failed jobs. Better statistics, a higher statistics target on state, help the generic estimate. Setting prepareThreshold=0 in the driver avoids named server-side statements entirely, but it gives up their benefit for every query in that pool, so it is a blunt tool.
6The PgBouncer Catch
Named statements live in one server session. PgBouncer in transaction mode hands a client a different server connection for each transaction, so a statement prepared in one transaction may not exist in the next, which used to produce errors such as prepared statement S_1 does not exist. PgBouncer 1.21 and later can track protocol-level prepared statements when max_prepared_statements is set; with older versions teams set prepareThreshold=0. Check your pooler version before enabling server-side prepares behind it, and remember that the generic plan issue still applies when the pooler supports them.
7Follow-up questions
Why does the query look fine in psql or a SQL client?
Because a query typed with literal values is planned with those values every time; it never becomes a named prepared statement, so it never reaches the generic plan. Testing with PREPARE and EXECUTE six or more times reproduces what the application sees.
Is force_custom_plan safe to set for the whole database?
It is safe in correctness but costs planning time on every execution of every prepared statement. For a busy OLTP system with many short queries, that can be measurable CPU. Scoping it to the role, pool or transaction that runs skewed queries is the better default.
How do you spot this in production?
Look for a query whose latency in pg_stat_statements is bimodal or depends on connection age, and enable auto_explain so slow executions log their plans. A plan containing $1 in its conditions is a generic plan, which points directly at this cause.
8Conclusion
In this answer, we saw that pgjdbc moves a repeated statement to a named server-side prepared statement after prepareThreshold executions, and that the server then uses five custom plans before it may settle on a generic plan that ignores parameter values. With skewed data, that generic plan can pick a bad scan, which is why the query slows down only after several runs in one connection. We fix it with a scoped plan_cache_mode = force_custom_plan, a rewrite or better statistics, and we check PgBouncer's prepared statement support in transaction mode.
Open with
Two thresholds are stacked here. In the driver, pgjdbc counts executions of the same SQL in a connection, and when it reaches prepareThreshold, five by default, it switches from unnamed statements to a named server-side prepared statement.
Then, if they want more
On the server, a named prepared statement gets custom plans with the real parameter values for its first five executions; after that the planner builds a generic plan, compares its estimated cost with the average custom plan cost, and if it is not clearly worse it keeps the generic plan.
A generic plan does not know the value, so on skewed data it can choose, for example, walking the primary key with a filter when the value is rare, which reads millions of rows. That is why the query is fast for the first several runs in a connection and slow afterwards, and why it looks fine in psql.
I confirm it with PREPARE and EXECUTE six times, by seeing $1 in the plan, or with pg_prepared_statements.
To fix it, I set plan_cache_mode to force_custom_plan scoped to the role, the pool through the JDBC options parameter, or the transaction with SET LOCAL; or I rewrite the query, for example with a partial index for the rare value, or raise the statistics target. Behind transaction-mode PgBouncer I check the version supports prepared statements, or turn server-side prepares off.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- PostgreSQL 14
- 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, MySQL reference manual
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 "With the PostgreSQL JDBC driver, a query becomes slow only after it has run several...": https://scrivio-interview-library.netlify.app/databases/query-optimization/171d6808c6/