Quick revision
The short answer
The 40 ms run in psql and the 4 second run in production are often not the same execution at all. The copy may have different data or fresher statistics, production may run the query as a prepared statement with a generic plan while psql plans for literal values, settings such as work_mem, random_page_cost or jit may differ, and production may be waiting on locks or I/O that a quiet copy never shows. To see the truth we capture the plan of the real slow execution with auto_explain, using log_min_duration and log_analyze with care for overhead.
What to remember
In this answer, we listed why a query can take 4 seconds in production and 40 ms in psql: different data volume, distribution, bloat and statistics; prepared statements that switch to a generic plan while psql plans for literal values; different work_mem, random_page_cost, effective_cache_size, jit and role or pool settings; and lock, I/O or CPU waits that a quiet copy never has. We then captured the real plan with auto_explain, using log_min_duration, log_analyze and buffers, with timing off and sampling to keep the overhead low.
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 40 ms run in psql and the 4 second run in production are often not the same execution at all. The copy may have different data or fresher statistics, production may run the query as a prepared statement with a generic plan while psql plans for literal values, settings such as work_mem, random_page_cost or jit may differ, and production may be waiting on locks or I/O that a quiet copy never shows. To see the truth we capture the plan of the real slow execution with auto_explain, using log_min_duration and log_analyze with care for overhead.
Why this question is asked
Every backend team has heard a developer say that a query is fast on their machine. With databases, the gap between a test run and production is especially large because the planner's decision depends on data, statistics, parameters, settings and concurrent load, and all of them can differ. Interviewers ask this scenario to see whether we can list these causes systematically and, more importantly, know how to get the real plan rather than guess. In this answer, we will walk through the differences in data and statistics, in how the query is prepared, in settings, and in runtime conditions, and then set up auto_explain to capture the production plan.
1Different Data, Different Statistics
The planner chooses a plan from statistics about the data: row counts, common values, distributions. A copy restored last month may have 30% fewer rows, may be missing a customer whose data is ten times larger than anyone else's, or may have been freshly analyzed after the restore, while production's statistics are three days old after a large load. Any of these can lead to a different plan for the same SQL.
Physical layout differs too. A fresh restore has compact tables and indexes with no bloat, the dead space left by updates and deletes, and its rows are stored in insertion order. Production tables may be twice the size on disk for the same rows. So even with the same plan, the copy touches fewer pages.
2Prepared Statements and Generic Plans
This is the difference most often missed. A Java application using JDBC sends the query with placeholders, such as WHERE status = $1 AND tenant_id = $2, and the PostgreSQL JDBC driver switches to a server-side prepared statement after the same statement has run several times (prepareThreshold, 5 by default). For a prepared statement, PostgreSQL plans the first five executions with the actual values, called custom plans. After that, it may switch to a generic plan, one plan built without knowing the values, if the generic plan's estimated cost is not much worse than the average custom plan.
A generic plan uses average selectivity. If status = 'FAILED' matches 0.1% of rows but status = 'DONE' matches 95%, one generic plan cannot be good for both. In psql the developer types literal values, so the planner always makes a custom plan for those exact values and may pick a fast index scan that production never uses. We can reproduce production's behaviour in psql.
Notice that the same values give a 4 second plan and a 40 ms plan depending only on generic versus custom planning. If this is the cause, we can set plan_cache_mode = force_custom_plan for the affected application role or connection, or change the query or index so that the generic plan is also good.
3Settings That Change the Plan or the Execution
Planner settings are often different between a developer's session and the application's sessions. work_mem decides whether a sort or hash fits in memory or spills to disk, and also whether the planner considers a hash join at all. random_page_cost tells the planner how expensive random reads are compared with sequential ones, so a lower value favours index scans. effective_cache_size tells it how much data is likely cached, which affects index choices. jit, the just-in-time compilation of expressions, can add hundreds of milliseconds of compile time to a query with a high estimated cost.
These settings can be set at many levels: the server configuration, the database, the role the application logs in with, and the session. Connection pools and frameworks often set session parameters at connect time, and the application role may have its own defaults. So we compare what the application really uses, not what psql shows.
| Cause | In the psql run on a copy | In production |
|---|---|---|
| Data and statistics | smaller or freshly analyzed | larger, skewed, stats may be stale |
| Plan type | custom plan for literal values | possibly a generic plan for $1, $2 |
| Settings | developer session defaults | role and pool settings, work_mem, jit |
| Cache | often warm after repeated runs | may be cold for that data |
| Concurrency | quiet, no other sessions | locks, I/O and CPU contention |
4Waiting That EXPLAIN ANALYZE Cannot Show
Even with an identical plan, production can be slower because the query waits. It may wait for a row lock held by another transaction, for I/O because a batch job is reading the disk, or for CPU on a busy server. EXPLAIN ANALYZE on a quiet copy measures a query that waits for nothing. In production, we can see waits while they happen in pg_stat_activity, whose wait_event_type and wait_event columns say whether a backend is waiting for a lock, I/O or something else, and lock waits longer than deadlock_timeout can be logged with log_lock_waits.
5Capturing the Real Production Plan With auto_explain
The most reliable answer is to stop guessing and log the plan of the actual slow execution. auto_explain is an extension shipped with PostgreSQL that does exactly this: when a statement runs longer than a threshold, it writes its plan to the server log.
There is a catch with log_analyze. When it is on, PostgreSQL must instrument every statement, because it cannot know in advance which one will be slow, so all queries pay some overhead, not only the logged ones. Turning off log_timing and sampling a fraction of statements keeps that overhead small. The logged plan shows what production really did with the real parameters, settings and data, and we can then reproduce it on the copy with PREPARE and the same settings, as we did earlier.
6Follow-up questions
What overhead does auto_explain.log_timing add?
With log_analyze on, log_timing makes PostgreSQL read the clock for every row at every plan node, just like EXPLAIN ANALYZE does. On machines where reading the clock is slow, that can add a large percentage to queries that process many rows, and it applies to every instrumented statement. Setting log_timing off keeps actual row counts and loops, which are usually enough to find a bad estimate, and removes most of the cost.
How can I tell whether the application is getting a generic plan?
PostgreSQL 14 and later show generic_plans and custom_plans counters in the pg_prepared_statements view for the current session, and the plan logged by auto_explain for a generic plan shows $1, $2 placeholders in its conditions instead of literal values. In a test session we can force each mode with plan_cache_mode and compare the plans for the same values.
Why would the copy be faster even with the same plan?
Because a freshly restored copy has no bloat, so tables and indexes are smaller, and repeated runs warm its cache. Production may need to read twice as many pages, from a cold cache, while other sessions compete for I/O. Comparing BUFFERS output from both sides shows this difference directly.
7Conclusion
In this answer, we listed why a query can take 4 seconds in production and 40 ms in psql: different data volume, distribution, bloat and statistics; prepared statements that switch to a generic plan while psql plans for literal values; different work_mem, random_page_cost, effective_cache_size, jit and role or pool settings; and lock, I/O or CPU waits that a quiet copy never has. We then captured the real plan with auto_explain, using log_min_duration, log_analyze and buffers, with timing off and sampling to keep the overhead low.
Open with
First, I would not assume both runs are the same execution. The copy might have different data volume or distribution, a missing big tenant, no bloat, or freshly analyzed statistics, any of which changes the plan or the pages read.
Then, if they want more
Second, the application probably runs the query as a prepared statement. After five executions PostgreSQL may switch to a generic plan that does not know the parameter values, while in psql the developer types literals and always gets a custom plan. I can reproduce that with PREPARE and plan_cache_mode set to force_generic_plan.
Third, settings differ: work_mem, random_page_cost, effective_cache_size and jit can be set per role or by the connection pool, so I check pg_settings and pg_roles from the application's role.
Fourth, production may simply be waiting, on row locks, on I/O from other jobs or on CPU, and EXPLAIN ANALYZE on a quiet copy cannot show that; pg_stat_activity wait events and log_lock_waits can.
To stop guessing, I enable auto_explain with log_min_duration at, say, one second, log_analyze and log_buffers on, log_timing off and a sample rate, because log_analyze adds instrumentation to every statement. That logs the plan of the real slow execution with real parameters, which I then reproduce and fix on the copy.
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 "A query takes 4 seconds in production but 40 ms when a developer runs it in psql with...": https://scrivio-interview-library.netlify.app/databases/query-optimization/0cb862fc56/