Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A query that ran in 20 ms for months suddenly takes 4 seconds after a data load, with no code change. How would you investigate it?

With no code change, the usual cause is a different execution plan: the data load changed the table's size or value distribution, the statistics the planner relies on are stale or now misleading, and it picks a worse plan. We compare the plans before and after, check and refresh statistics with ANALYZE, look for bloat, check whether a cached generic plan for prepared statements is bad for skewed values, and rule out lock or I/O waits. Then we fix it with fresh statistics, a better index or a query change, and add a regression check.

Why this question is asked

A query that was fast for months and is suddenly slow is one of the most common database incidents, and one of the most misdiagnosed. People look for a code change, a slow network or a bad deploy, while the real change happened inside the database: it simply decided to run the same SQL differently. Interviewers ask this to see whether we investigate methodically and know how the planner makes its decisions. In this answer, we will recap how the planner chooses a plan, then go through the investigation step by step, and finish with the fix and how to stop it happening again.

1A Quick Recap of the Query Planner

When we send SQL, the database does not run it directly. The planner considers several ways to execute it, for example an index scan or a sequential scan, a nested loop join or a hash join, and estimates the cost of each from statistics: how many rows each table has, how many distinct values a column holds, the most common values and a histogram of the rest. It picks the cheapest estimate.

So the plan depends on statistics, and statistics describe the data as it was when they were last collected. In PostgreSQL, ANALYZE collects them, and autovacuum runs it automatically after enough rows change. After a large load, there can be a window where the table has changed a lot but the statistics have not, or the new data has a very different shape, such as one customer with 2 million new rows.

2Compare the Plans

The first question is whether the plan changed. We run EXPLAIN (ANALYZE, BUFFERS) on the slow query with the same parameters the application uses, and compare it with the old plan if we have one, from auto_explain logs, a query monitoring tool, or a copy of the database from before the load.

SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 4711 AND status = 'OPEN' ORDER BY created_at DESC LIMIT 20;
-- before the load: 20 ms
-- Index Scan using orders_customer_created_idx (rows=20) Execution Time: 18.9 ms
-- after the load: 4 s
-- Index Scan Backward using orders_created_idx (actual rows=20, loops=1)
-- Filter: (customer_id = 4711 AND status = 'OPEN')
-- Rows Removed by Filter: 3,812,440
-- Execution Time: 4021.7 ms

Notice the clue: the planner now walks the created_at index and filters rows, expecting to find 20 matches quickly, but it removes 3.8 million rows first. Its estimate of how common this customer's open orders are no longer matches reality. A large gap between estimated and actual rows in the plan almost always means a statistics problem.

3Check Statistics and Bloat

We check when the table was last analyzed and how much it has changed since. pg_stat_user_tables shows last_analyze, last_autoanalyze, the number of live and dead rows and the modifications since the last analyze. If the load added millions of rows after the last analyze, we run ANALYZE on the table and run EXPLAIN again. Often that alone restores the old plan.

SQL
SELECT relname, n_live_tup, n_dead_tup, n_mod_since_analyze, last_autoanalyze
FROM pg_stat_user_tables WHERE relname = 'orders';
-- orders | 52,000,000 | 9,400,000 | 11,200,000 | 2026-11-01 02:10 (before the load)
ANALYZE orders; -- refresh statistics, then EXPLAIN again

The same view shows bloat: 9.4 million dead rows, left behind by updates or deletes in the load, make sequential and index scans read many pages of garbage. If vacuum has not caught up, the table and its indexes are much larger than the live data, and every scan pays for it. A VACUUM, and for heavy bloat a rebuild with REINDEX CONCURRENTLY or a tool like pg_repack, fixes that.

4Check Plan Caching for Prepared Statements

Java applications use prepared statements with bind parameters. The PostgreSQL JDBC driver switches to server-side prepared statements after a statement has run a few times (prepareThreshold, 5 by default), and PostgreSQL then may switch from custom plans, built for each parameter value, to one generic plan that ignores the values. That is efficient when data is evenly spread, but if one customer now has 2 million orders and most have 50, a generic plan can be terrible for one of them.

We can test this by running the query with EXPLAIN using literal values, then with PREPARE and EXECUTE several times. If the literal version is fast and the prepared one becomes slow after a few executions, plan caching is the issue. Options include setting plan_cache_mode = force_custom_plan for that user or session, or changing the query or indexes so one plan is good for all values; check your PostgreSQL version for the exact behaviour.

5Rule Out Contention

Not every slowdown is a plan problem. If the plan is unchanged and the query is still slow, it may be waiting rather than working. pg_stat_activity shows each session's wait_event: Lock waits mean another transaction holds a row or table lock, for example a long-running load that is still committing; IO waits mean the data no longer fits in memory and reads go to disk. EXPLAIN (ANALYZE, BUFFERS) also helps here, because a high count of shared read buffers compared with hits shows the query is reading from disk.

Step throughInvestigating a sudden slowdown
  1. Plan changed?
    YesCheck estimates versus actual rowsNoLook at waits: locks, I/O
  2. Stats stale after the load?
    YesANALYZE and compare the plan againNoCheck bloat and dead rows
  3. Fast with literals, slow when prepared?
    YesGeneric plan problemNoFix with an index or query change
  4. Add a regression checkplan or latency test for this query

4 steps in order. Play them, or step through them one at a time.

6Follow-up questions

How do you stop this happening after every data load?

Make ANALYZE part of the load job, right after it finishes, instead of waiting for autovacuum. For very large tables, tune the autovacuum analyze thresholds per table so a few percent of changed rows triggers it, and raise the statistics target for columns with skewed values.

What is a regression check for a query?

A test in the performance suite that runs the query against production-like data and fails if latency or the plan shape changes beyond a limit, for example if it stops using the expected index. pg_stat_statements trends in production give an early warning between releases.

Could adding an index fix it when statistics are fresh?

Yes. Here an index on (customer_id, status, created_at) lets the database find exactly the 20 rows it needs in order, whatever the distribution, so the plan no longer depends on a fragile estimate.

7Conclusion

In this answer, we saw that a query that slows down without code changes has usually changed plans, because the data load left statistics stale or the distribution skewed. We compare plans, look for gaps between estimated and actual rows, check statistics and bloat in pg_stat_user_tables, test whether prepared statements get a bad generic plan, and rule out locks and I/O waits. Fresh statistics, a better index or a query change fixes it, and a regression check keeps it fixed.

What to say in the interviewAbout 80 seconds aloud

Open with

With no code change, my first suspicion is that the execution plan changed. The planner picks a plan from statistics, and a big data load can leave them stale or change the distribution, for example one customer suddenly having millions of rows.

Then, if they want more

So I would run EXPLAIN ANALYZE with BUFFERS on the slow query with real parameters and compare it with the old plan from auto_explain or a pre-load copy. A big gap between estimated and actual rows, like the planner walking an index and removing millions of rows, points to statistics.

Then I check pg_stat_user_tables for last analyze and modifications since, run ANALYZE on the table, and look at dead rows for bloat, which may need a vacuum or a rebuild.

Because Java uses prepared statements, I would also check whether PostgreSQL switched to a generic plan that is bad for skewed values, by comparing literals with repeated prepared executions, and fix that with plan_cache_mode or a better index. If the plan did not change, I look at wait events in pg_stat_activity for locks or I/O.

The fix is usually ANALYZE in the load job, an index that fits the query, or a query change, plus a regression check for that query in the performance suite.

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.
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 that ran in 20 ms for months suddenly takes 4 seconds after a data load, with no...": https://scrivio-interview-library.netlify.app/databases/database-scaling/bfd1269a4e/