Scrivio Interview library
ScenarioAdvanced6 min read · updated 12 November 2026

You are upgrading PostgreSQL by two major versions for 40 databases. How do you manage the risk of query plan regressions?

We manage plan regression risk by measuring instead of hoping: capture the top queries from pg_stat_statements with representative parameters, replay them on an upgraded copy with production-like data, and compare plans and timings. Right after pg_upgrade we run ANALYZE, because older versions do not carry optimizer statistics across (check your version), we review both releases' planner changes and defaults, and we roll out the 40 databases by risk tier with rollback plans and per-service latency dashboards.

Why this question is asked

A major PostgreSQL upgrade changes the planner, and a planner change can turn a fast query into a slow one even though the SQL and data are the same. With 40 databases, the chance that at least one important query regresses is high, so the question is not whether to accept risk but how to find it before customers do. Interviewers ask this to see whether we can run a large change safely and methodically. In this answer, we will recap why upgrades change plans, build a baseline, test plans on an upgraded copy, handle statistics after pg_upgrade, and plan the rollout and rollback.

1Why a Major Upgrade Can Change Plans

Every major PostgreSQL release improves the planner: new join strategies, better estimates, new ways to use indexes, incremental sorts, changes in how parallel queries are costed. Defaults also change from time to time. Most of these improvements make most queries faster, but the planner works from estimates, and an improvement that helps a thousand queries can push one query with a poor estimate across a threshold into a worse plan.

Going two versions at once, say from 15 to 17, means both releases' changes land together. That is fine, and usually cheaper than two separate upgrades, but it means reading two sets of release notes and testing against the combined behaviour.

2Build a Baseline Before Anything Changes

We cannot detect a regression without knowing what normal looks like. pg_stat_statements, the extension that aggregates execution statistics per normalized query, gives us the queries that matter most by total time and by call count. We export them per database a week or two before the upgrade.

SQL
SELECT queryid, calls, round(mean_exec_time::numeric, 2) AS mean_ms,
round(total_exec_time) AS total_ms, query
FROM pg_stat_statements
ORDER BY total_exec_time DESC LIMIT 100;
-- queryid 81723..., calls 4.2M, mean_ms 1.84, query: SELECT ... WHERE tenant_id = $1 ...

Notice that pg_stat_statements stores the query with placeholders, not the real values. A plan depends on the values, especially on skewed columns, so for each important query we also collect representative parameters: a typical value, a very common value and a rare one, taken from application logs or from auto_explain samples. We also save the current plans with EXPLAIN for those parameter sets, so we have something concrete to compare.

3Replay on an Upgraded Copy

Next we restore a recent backup of each database, or at least of each database class, upgrade the copy with the same method we will use in production, and replay the baseline. Production-like data matters: a copy with a tenth of the rows will produce different plans from the real one.

Step throughTesting plans before the real upgrade
  1. Export top queries and parameterspg_stat_statements, logs
  2. Restore backup and upgrade the copysame method as production
  3. Run ANALYZE on the copyfresh statistics first
  4. Replay baseline and logged trafficplans and timings
  5. Any query slower than threshold?
    YesFix it and replay againNoDatabase ready for its tier

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

The loop repeats until no important query is slower on the new version.

For each query and parameter set, we compare the plan shape and the timing between the old and new versions and flag anything slower by, say, more than 50 percent or 10 ms. For broader coverage, tools can replay logged traffic, for example pgreplay from a statement log, which also catches queries that are not in the top 100. Every flagged query gets an owner and a fix before its database is upgraded: an index, a statistics change, a rewrite or, as a last resort, a setting for that query's role.

4Statistics After pg_upgrade

pg_upgrade, the tool that converts a cluster in place by reusing the data files, is fast, but in versions before 18 it does not carry optimizer statistics over. The new cluster starts with empty statistics, and until ANALYZE runs every estimate is a guess. That is the most common cause of a terrible first hour after an upgrade, and it has nothing to do with the planner itself. PostgreSQL 18 can preserve most statistics during pg_upgrade, while extended statistics still need a fresh ANALYZE; check your version's notes.

Java
pg_upgrade --old-datadir ... --new-datadir ... --link
# start the new cluster, then immediately:
vacuumdb --all --analyze-in-stages --jobs 8
# stage 1 builds rough statistics within minutes, later stages refine them

The --analyze-in-stages option exists exactly for this: it gives the planner usable statistics quickly and then improves them. We keep traffic off, or limited, until at least the first stage finishes. Custom statistics targets and CREATE STATISTICS objects are kept as definitions, but their data must also be rebuilt by ANALYZE.

5Read the Release Notes for Planner Changes

For both versions we skip, we read the release notes with one question: what changes the planner or a default? Examples of the kind of item to look for are new plan types, changed cost defaults, changes in parallelism and changed behaviour of features we use, such as partitioning or JIT compilation. Each relevant item becomes a check in the replay: if we rely on a feature that changed, we make sure a query using it is in the test set.

6Roll Out by Risk Tier, With a Way Back

With 40 databases, we never upgrade all of them on the same night. We group them by risk: internal tools and low-traffic services first, then mid-tier services, then the payment and core databases last, so lessons from the early waves reach the critical ones. Each wave waits a few days of normal traffic before the next.

Rollback must be designed in advance. pg_upgrade --link is fast but, once the new cluster has started, the old one can no longer be used safely, so a way back means restoring from backup or using an upgrade method with a live fallback, such as logical replication to a new-version cluster with the old primary kept in sync until we are confident. For the first days after each wave, dashboards show latency per service and per top query compared with the baseline, and on-call engineers know the playbook: identify the query, compare plans, apply the prepared fix.

7Follow-up questions

Why not upgrade one version at a time?

It halves the change in each step but doubles the downtime, testing and coordination. Two versions at once is usually the better trade if the replay tests cover both releases' planner changes, which is why reading both sets of notes matters.

What if a regression appears only in production?

We treat it like any plan regression: confirm with EXPLAIN ANALYZE, compare with the baseline plan we saved, check that ANALYZE has completed, and apply a targeted fix. The saved baseline plans make this much faster than starting from nothing.

Does a managed service change the plan?

The principles stay the same. A managed service may run pg_upgrade for us and may or may not run ANALYZE afterwards, so we check its documentation, run ANALYZE ourselves if needed, and still replay our queries on a test instance first.

8Conclusion

In this answer, we saw that a major upgrade changes the planner and can turn a few queries slower, so we capture a baseline from pg_stat_statements with real parameters, replay it on an upgraded copy with production-like data, and fix every regression before the real upgrade. We run ANALYZE straight after pg_upgrade, because older versions do not keep statistics, read both releases' notes for planner changes, and roll out by risk tier with a rollback path and dashboards per service.

What to say in the interviewAbout 80 seconds aloud

Open with

I treat it as a measured migration rather than a hope. Two weeks before, for each database I export the top hundred queries from pg_stat_statements by total time and by calls, and collect representative parameters for them, including skewed values, because pg_stat_statements only stores placeholders.

Then, if they want more

I save their current plans. Then I restore backups, upgrade the copies the same way I will in production, run ANALYZE, and replay the queries, plus logged traffic with a tool like pgreplay for coverage. Anything noticeably slower gets an owner and a fix before that database moves.

I also read the release notes of both versions for planner changes and changed defaults, and make sure those features are in the test set. On the night, I run vacuumdb with analyze-in-stages right after pg_upgrade, because before version 18 optimizer statistics are not carried over, and an unanalyzed cluster is the classic first-hour disaster.

I roll out in tiers, internal and low-risk databases first, core payments last, with a few days between waves. Each database has a rollback plan, which with pg_upgrade --link means a backup restore or a logical-replication fallback, and for the first days we watch per-service latency against the baseline.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 18
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 "You are upgrading PostgreSQL by two major versions for 40 databases. How do you manage...": https://scrivio-interview-library.netlify.app/databases/query-optimization/31bba10099/