Sub topic 8
Running the upgrade
This chapter covers the upgrade run itself: the final pre-flight steps, the pg_upgrade command, what its output means, and what state both clusters are in afterwards. It assumes you have already done the following:
- Taken and tested a backup.
- Installed the new binaries and the extension packages for the new version.
- Created the new cluster with
initdb. - Run
pg_upgrade --checkuntil it reports no problems.
It also assumes you are comfortable with pg_ctl and basic Linux administration.
Where the downtime starts
Applications must stop writing to the database before you shut down the old cluster. Downtime then covers everything from that shutdown until the new cluster accepts connections again. The steps below make that window predictable.
- Stop the applications, or block them at the connection pooler or firewall.
- Shut down the old cluster cleanly.
- Run
pg_upgrade. - Reconcile configuration files.
- Start the new cluster and rebuild statistics.
Pre-flight checks
Do these in the maintenance window, before the real run.
Stop both servers cleanly
pg_upgrade needs the old cluster to have shut down cleanly, with a final checkpoint written. A crashed or killed server leaves WAL that the new version cannot replay, and pg_upgrade refuses to continue.
/opt/pg16/bin/pg_ctl -D /data/pg16 stop -m fast
/opt/pg16/bin/pg_controldata /data/pg16 | grep "Database cluster state"The second command should print shut down. If it prints in production or in crash recovery, the shutdown was not clean. Start the old server, let it recover, and stop it again.
The new cluster must also be stopped. If you tested it after initdb, stop it now.
Check the environment
Run pg_upgrade as the operating system user that owns both data directories, usually postgres. Also check these points:
- Working directory:
pg_upgradewrites logs and a few scripts to the directory you start it from, so use one that user can write to. In PostgreSQL 15 and later, logs go topg_upgrade_output.dinside the new data directory. - Disk space: In copy mode, free space must be at least the size of the old data directory. In link mode you need only a little extra space for the schema dump and logs.
- Same filesystem: Link mode uses hard links, so both data directories must be on the same filesystem.
- Ports: The tool starts both servers temporarily on its own. By default it uses port 50432 for both, so these starts do not collide with a production port. Override this with
--old-portand--new-portif needed. - Configuration:
pg_upgradedoes not copypostgresql.conf,pg_hba.conforpg_ident.conf. It also does not copypostgresql.auto.conf, which holds settings fromALTER SYSTEM. If the old cluster keeps these files inside the data directory, save copies now.
Run the check one more time
Run --check again right before the real run. It is cheap and catches anything that changed since your last attempt, such as a new extension or a table that now uses an unsupported type.
/opt/pg17/bin/pg_upgrade \
--old-bindir=/opt/pg16/bin \
--new-bindir=/opt/pg17/bin \
--old-datadir=/data/pg16 \
--new-datadir=/data/pg17 \
--checkAlways run the pg_upgrade binary from the new version's bindir. The old binary does not know how to upgrade to a newer release.
Run the upgrade
For most production systems, link mode with parallel jobs gives the shortest downtime.
/opt/pg17/bin/pg_upgrade \
--old-bindir=/opt/pg16/bin \
--new-bindir=/opt/pg17/bin \
--old-datadir=/data/pg16 \
--new-datadir=/data/pg17 \
--link \
--jobs=4--link makes pg_upgrade create hard links from the new cluster's files to the old cluster's relation files instead of copying them. A hard link is a second directory entry for the same file, so the time spent on data files is proportional to the number of files, not their total size. A multi-terabyte cluster can finish in minutes.
--jobs=4 lets pg_upgrade do several things in parallel. It dumps and restores the schemas of different databases at the same time, and it processes relation files concurrently. A reasonable starting value is the number of CPU cores, bounded by what your storage handles well. Most of the work is metadata operations, so more jobs than cores rarely helps.
What the output tells you
pg_upgrade prints one line per step and marks each ok. The exact wording varies by version, but the sequence is stable:
Performing Consistency Checks: the same checks as--check, run again.Creating dump of global objectsandCreating dump of database schemas: it runspg_dumpall --globals-onlyandpg_dump --schema-onlyagainst the old cluster, using a binary-upgrade mode that preserves object identifiers.Checking for presence of required libraries: every shared library that a function or extension references must exist in the new installation.Restoring global objects in the new clusterandRestoring database schemas in the new cluster: roles, tablespaces and schema definitions are recreated in the new cluster.Adding ".old" suffix to old global/pg_control: this appears only in link mode. It is a safety measure and is explained below.Linking user relation files, orCopying user relation filesin copy mode.Setting next OID,Sync data directory to disk,Creating script to delete old cluster.Upgrade Complete.
Only the final block matters operationally. It tells you which scripts were created and what to do next. Keep the whole console output, because it is the first thing you will want if something looks off later.
What link mode does to the old cluster
In link mode, pg_upgrade renames global/pg_control in the old data directory to pg_control.old. Without a pg_control file, the old server will refuse to start. This blocks the most dangerous mistake: starting the old cluster after the new one has modified the shared files.
The state of the old cluster depends on how far you got:
| Situation | Old cluster state | Can you restart it? |
|---|---|---|
| `pg_upgrade` failed before or during the file-linking step | Intact apart from the `.old` rename, if it happened | Yes. Remove the `.old` suffix from `global/pg_control` and start it. |
| `pg_upgrade` succeeded, new cluster not yet started | Intact apart from the `.old` rename | Yes, by the same procedure. |
| New cluster has been started and used | Shared files have been modified | No. Restore from backup. |
| Copy mode, any point | Untouched | Yes. |
Reconcile configuration
Compare the old and new configuration files and carry over the settings you need. Do not copy the old postgresql.conf over the new one, because parameters are added, renamed and removed between versions, and a stale file can prevent startup or silently change behavior.
A practical method is to diff the old file against the new file's defaults, and apply each intentional difference by hand. Typical items are:
listen_addresses,portandmax_connections- memory settings such as
shared_buffersandwork_mem - WAL and replication settings
shared_preload_librariesssland certificate paths
pg_hba.conf usually can be copied over, but read the release notes first. For example, PostgreSQL 14 changed the default password hashing to scram-sha-256, which affects authentication method choices.
Start the new cluster and rebuild statistics
Start the new server and rebuild planner statistics immediately:
/opt/pg17/bin/pg_ctl -D /data/pg17 -l /data/pg17/server.log start
/opt/pg17/bin/vacuumdb --all --analyze-in-stagesReleases before PostgreSQL 18 do not carry optimizer statistics across the upgrade, so right after the start every table looks empty to the planner. --analyze-in-stages runs three passes with increasing sampling: a very coarse pass first, then a medium one, then the full default. After the first pass, which takes seconds to minutes, queries get reasonable plans, and the later passes refine them. You can let applications reconnect after the first pass if your risk tolerance allows it. Upgrading to PostgreSQL 18 or later can preserve statistics, but check the release notes for what is and is not carried over.
Run a few sanity queries before you open the gates: row counts on key tables, a login as an application role, and SELECT version();.
When the upgrade fails
The failure point decides what you do next.
- Failure during checks or schema restore: Nothing in the old cluster has changed except possibly the
.oldrename. The new cluster is partly populated and cannot be reused. Delete its data directory, runinitdbagain, fix the cause, and retry. - Failure during file transfer: Restore the old cluster's
pg_controlif renamed, and start the old cluster to confirm it works. Then recreate the new cluster and retry. - After success, a problem found later: In copy mode, stop the new cluster and start the old one. Writes made on the new cluster are lost. In link mode, the answer depends on whether you have started the new cluster, as the table above shows.
Use the logs to find the cause. In PostgreSQL 15 and later they are in pg_upgrade_output.d under the new data directory, and pg_upgrade deletes that directory after a successful run unless you pass --retain. In earlier versions they are pg_upgrade_*.log files in the working directory. The most informative are pg_upgrade_internal.log and the pg_upgrade_dump_*.log files, which hold the actual SQL errors. A later chapter covers common errors in detail.
Cleanup comes later
A successful run produces delete_old_cluster.sh, which removes the old data directory. Do not run it during the window. Keep the old cluster, and your backup, until the new cluster has run through a full business cycle, including backups, batch jobs and monitoring. The post-upgrade chapter covers cleanup.
Exercise
You ran pg_upgrade --link and it printed "Upgrade Complete". Before starting the new cluster, you discover that the application team needs the window cancelled. Can you start the old cluster again, and what must you do first?
Show answer
Yes, because the new cluster has not been started and so has not modified the shared data files. Link mode renamed global/pg_control to global/pg_control.old in the old data directory. Rename it back to pg_control, then start the old cluster with its own binaries. If the new cluster had already been started and used, you could not safely do this and would restore from backup.
Exercise
A colleague wants to cut downtime and proposes skipping the clean shutdown of the old cluster by sending it kill -9, since pg_upgrade starts the server itself anyway. Why is this wrong, and how would you verify the state before running pg_upgrade?
Show answer
A killed server leaves the cluster in a crashed state with unreplayed WAL, and pg_upgrade requires a clean shutdown so no recovery is needed. Verify with pg_controldata /data/pg16 | grep "Database cluster state", which must say shut down. If it does not, start the old server, let it recover, and stop it with pg_ctl stop -m fast.
Exercise
After a successful upgrade on PostgreSQL 16 to 17, queries on large tables are slow with poor plans. Which command do you run, and why does --analyze-in-stages help?
Show answer
Run vacuumdb --all --analyze-in-stages with the new binaries. Planner statistics are not carried over to the new cluster before PostgreSQL 18, so the planner has no row estimates. The staged analyze produces coarse statistics within the first pass, which gives usable plans quickly, and then refines them in later passes.