Skip to content

PostgreSQL major version upgrade with pg_upgrade — the in-place runbook

Why dump and restore stops scaling, what pg_upgrade --check catches, the --link vs --clone vs copy trade-off, extension updates, the post-upgrade ANALYZE nobody remembers, and how far rollback actually goes.

PostgreSQL changes its on-disk catalog format between major versions, so moving from 16 to 17 is never a package upgrade — the new server refuses to start on the old data directory. pg_upgrade bridges the gap: it installs a fresh catalog for the new major, then copies or hard-links the existing relation files into place, so wall-clock time tracks how many objects you have rather than how many bytes. A 4 TB database with a normal schema upgrades in a couple of minutes with --link; the same database through pg_dump and pg_restore takes most of a day, because every row is re-parsed and every index rebuilt. This runbook covers the whole sequence: the pre-flight check, the mode choice, the port swap, extension updates, the planner statistics that do not come along for free, and exactly how much rollback you have left once the new cluster has started.

What you’ll accomplish

  • Install a new PostgreSQL major version alongside the running one without disturbing it.
  • Run pg_upgrade --check and clear every class of problem it reports before you take an outage.
  • Choose deliberately between copy mode, --link and --clone, and understand what each one costs you in rollback.
  • Complete the upgrade, swap ports and configuration, and rebuild planner statistics so query plans do not fall off a cliff.
  • Know precisely when the old cluster stops being a valid fallback, and what your options are after that point.

Prerequisites

  • A backup you have restored at least once. Not a backup you took — a backup you have proven. --link mode in particular removes the old cluster as a fallback the moment the new server starts, so the restore path is your only rollback.
  • Both major versions installed on the same host. pg_upgrade reads the old cluster with the old binaries and writes the new one with the new binaries; it needs both present simultaneously.
  • Root or sudo, plus the ability to run commands as the postgres OS user. pg_upgrade must run as the user that owns both data directories, and it refuses to run as root.
  • Enough free disk space for copy mode: roughly the size of the current data directory, again. --link and --clone need almost none, but both require the old and new data directories to live on the same filesystem.
  • Honest expectations about your distribution. Debian and Ubuntu with the PGDG repository ship pg_upgradecluster, a wrapper that handles paths, ports and configuration for you — pg_upgradecluster -m upgrade --link 16 main does most of what this guide does by hand. RHEL, Rocky and AlmaLinux have no such wrapper: binaries live in /usr/pgsql-16/bin, data in /var/lib/pgsql/16/data, and you drive pg_upgrade directly. The examples below use the RHEL-style paths because they show the mechanics.
  • A maintenance window. The database is down from the moment you stop the old cluster until the new one accepts connections — minutes with --link, and however long a full read-and-write of the data directory takes in copy mode.

How it works

A PostgreSQL data directory holds two very different things. The system catalog — pg_control, the pg_catalog tables, the shared catalogs in global/ — encodes the internal format that changes between majors. User data lives in relation files under base/<database-oid>/, and that page format almost never changes between adjacent majors.

pg_upgrade exploits that split. It dumps the schema (not the data) out of the old cluster, replays it into the freshly initialized new cluster, and then moves the relation files across, remapping file names to the new OIDs. Nothing reads a single user row.

How the relation files get from one directory to the other is the mode choice:

Old and new PostgreSQL data directories sharing the same relation file inodes through hard links, with the old cluster rendered unusable once the new one starts

Copy mode is the default: every file is read and written. Slow, but the old cluster remains a complete, untouched, startable database.

--link creates hard links instead. The file exists once on disk with two directory entries pointing at it, so the upgrade finishes in the time it takes to create a few thousand links. The catch follows directly from the picture above: once the new server starts and writes a page, that write lands in the file the old cluster also points at. The old cluster is not dramatically corrupt, it is simply inconsistent with its own catalog, and PostgreSQL will not let you start it. pg_upgrade knows this and refuses to run --link twice against the same old cluster.

--clone uses a copy-on-write reflink. You get the speed of --link and the independence of copy mode, because the first write to a shared block allocates a new one. It requires filesystem support: Btrfs, XFS formatted with reflink=1, or APFS on macOS. On ext4 it fails immediately with a clear error.

Where each one lands:

Decision tree from database size, downtime budget and filesystem layout to dump and restore, logical replication, pg_upgrade with link or clone, or pg_upgrade in copy mode

Step-by-step

1. Install the new major version alongside the old one. Nothing here touches the running cluster.

sudo dnf install -y postgresql17-server postgresql17-contrib
Installed:
  postgresql17-server-17.5-1PGDG.rhel9.x86_64
  postgresql17-contrib-17.5-1PGDG.rhel9.x86_64
Complete!

Install the new-version package for every extension you use — PostGIS, pg_repack, timescaledb, whatever is in your shared_preload_libraries. Missing extension libraries are the single most common --check failure.

2. Read the old cluster’s settings, because the new one has to match. pg_upgrade compares encoding, locale and checksum settings and aborts on any mismatch.

sudo -u postgres /usr/pgsql-16/bin/pg_controldata /var/lib/pgsql/16/data \
  | grep -E 'checksum|Database block size'
Database block size:                  8192
Data page checksum version:           1
sudo -u postgres psql -Atc "SELECT datname, pg_encoding_to_char(encoding), datcollate, datctype FROM pg_database WHERE datname = 'template1'"
template1|UTF8|en_US.UTF-8|en_US.UTF-8

3. Initialize the new cluster with those exact settings. --data-checksums is the one people forget; if the old cluster has checksums and the new one does not, pg_upgrade stops.

sudo -u postgres /usr/pgsql-17/bin/initdb \
  --pgdata=/var/lib/pgsql/17/data \
  --data-checksums \
  --encoding=UTF8 \
  --locale=en_US.UTF-8
Success. You can now start the database server using:
    /usr/pgsql-17/bin/pg_ctl -D /var/lib/pgsql/17/data -l logfile start

Do not start it. pg_upgrade needs it initialized and stopped.

4. Run the check pass. You can do this days ahead, with the old cluster still serving traffic. Run it from a directory the postgres user can write to — pg_upgrade drops a pg_upgrade_output.d directory and several scripts wherever you invoke it.

cd /var/lib/pgsql
sudo -u postgres /usr/pgsql-17/bin/pg_upgrade \
  --old-bindir=/usr/pgsql-16/bin \
  --new-bindir=/usr/pgsql-17/bin \
  --old-datadir=/var/lib/pgsql/16/data \
  --new-datadir=/var/lib/pgsql/17/data \
  --link \
  --jobs=4 \
  --check
Performing Consistency Checks
-----------------------------
Checking cluster versions                                     ok
Checking database user is the install user                    ok
Checking database connection settings                         ok
Checking for prepared transactions                            ok
Checking for system-defined composite types in user tables    ok
Checking for reg* data types in user tables                   ok
Checking for presence of required libraries                   ok
Checking for new cluster tablespace directories               ok

*Clusters are compatible*

Anything other than *Clusters are compatible* is a to-do list. The recurring ones: a database with datallowconn set to false (all non-template0 databases must allow connections), columns typed unknown or regproc/regconfig/regoper, prepared transactions still sitting in pg_prepared_xacts, extension libraries absent from the new installation, and logical replication slots — which are not carried across when the old cluster predates PostgreSQL 17, so drop them and rebuild the subscriptions afterwards. Keep --check and the real run identical apart from --check itself, so the check validates the mode you will actually use.

5. Stop both clusters. The real run requires it, and pg_upgrade will tell you so in an unfriendly way if you forget.

sudo systemctl stop postgresql-16
sudo systemctl status postgresql-16 --no-pager | head -3
● postgresql-16.service - PostgreSQL 16 database server
     Loaded: loaded (/usr/lib/systemd/system/postgresql-16.service; enabled)
     Active: inactive (dead) since Thu 2026-07-23 22:04:11 EDT

6. Run the upgrade. Same command, minus --check.

cd /var/lib/pgsql
sudo -u postgres /usr/pgsql-17/bin/pg_upgrade \
  --old-bindir=/usr/pgsql-16/bin \
  --new-bindir=/usr/pgsql-17/bin \
  --old-datadir=/var/lib/pgsql/16/data \
  --new-datadir=/var/lib/pgsql/17/data \
  --link \
  --jobs=4
Setting next OID for new cluster                              ok
Sync data directory to disk                                   ok
Creating script to delete old cluster                         ok
Checking for extension updates                                ok

Upgrade Complete
----------------
Optimizer statistics are not transferred by pg_upgrade.
Once you start the new server, consider running:
    /usr/pgsql-17/bin/vacuumdb --all --analyze-in-stages

Running this script will delete the old cluster's data files:
    ./delete_old_cluster.sh

--jobs parallelizes the per-database schema dump and restore and the file transfer. It helps when you have many databases or tablespaces, does nothing on a single small-schema database, and should not exceed your CPU count.

7. Carry your configuration over. initdb produced a stock postgresql.conf and pg_hba.conf. Your tuning and your authentication rules are still in the old directory.

sudo -u postgres diff /var/lib/pgsql/16/data/pg_hba.conf \
                      /var/lib/pgsql/17/data/pg_hba.conf
84,86c84
< host    appdb   app_rw   10.20.0.0/16   scram-sha-256
< host    appdb   app_ro   10.20.0.0/16   scram-sha-256
< hostssl replication  repl 10.20.0.4/32  scram-sha-256
---
> host    all     all      127.0.0.1/32   scram-sha-256

Re-apply those lines by hand rather than copying the file wholesale: a blind copy of postgresql.conf can carry a setting the new version has removed, which stops the server from starting. Check the port explicitly, because initdb and your packaging may not agree:

sudo -u postgres grep -E '^port' /var/lib/pgsql/17/data/postgresql.conf
port = 5432

If the new cluster was initialized on 5433 for the upgrade, set it back to 5432 now, and make sure the old cluster’s service is disabled so nothing races for the port.

8. Start the new cluster. This is the point of no return for --link.

sudo systemctl disable --now postgresql-16
sudo systemctl enable --now postgresql-17
sudo -u postgres psql -Atc 'SELECT version()'
PostgreSQL 17.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 11.4.1, 64-bit

9. Update extensions. An extension’s tables came across untouched, so the catalog still records the old extension version even though the new shared library is on disk. Find the mismatches:

sudo -u postgres psql -d appdb -c "SELECT name, default_version, installed_version FROM pg_available_extensions WHERE installed_version IS NOT NULL AND installed_version <> default_version"
        name         | default_version | installed_version
---------------------+-----------------+-------------------
 pg_stat_statements  | 1.11            | 1.10
 postgis             | 3.5.0           | 3.4.2
(2 rows)

Then update each one, in every database that has it:

sudo -u postgres psql -d appdb -c 'ALTER EXTENSION pg_stat_statements UPDATE'
ALTER EXTENSION

Skipping this is how you end up with an extension whose SQL definitions and C functions disagree, which surfaces later as a missing-symbol error in the middle of a query.

10. Rebuild planner statistics. pg_upgrade does not transfer optimizer statistics for target versions through 17, and even on 18 — where most statistics do come across — extended statistics objects still need rebuilding. An unanalyzed 4 TB database will pick sequential scans over everything and look like an outage.

sudo -u postgres /usr/pgsql-17/bin/vacuumdb --all --analyze-in-stages --jobs=4
vacuumdb: processing database "appdb": Generating minimal optimizer statistics (1 target)
vacuumdb: processing database "appdb": Generating medium optimizer statistics (10 targets)
vacuumdb: processing database "appdb": Generating default (full) optimizer statistics

The staged form is deliberate: the first pass gives the planner something usable within seconds, so traffic can come back while the fuller passes run. Older pg_upgrade versions generated an analyze_new_cluster.sh for this; it was dropped in PostgreSQL 14 in favour of calling vacuumdb directly.

11. Reclaim the old cluster’s space — later. pg_upgrade wrote the script for you, and there is no hurry.

sudo -u postgres ./delete_old_cluster.sh

Wait until you have watched a full business cycle on the new version. In copy mode the old directory is your rollback; in --link mode it is not, but its configuration files are still worth keeping.

Validate it works

Confirm the catalog version and that the cluster is in a clean state:

sudo -u postgres /usr/pgsql-17/bin/pg_controldata /var/lib/pgsql/17/data \
  | grep -E 'cluster state|Catalog version'
Database cluster state:               in production
Catalog version number:               202406281

Confirm statistics actually landed, rather than assuming vacuumdb finished:

sudo -u postgres psql -d appdb -c "SELECT relname, last_analyze FROM pg_stat_user_tables WHERE last_analyze IS NULL LIMIT 5"
 relname | last_analyze
---------+--------------
(0 rows)

An empty result means every user table has statistics. Then check that nothing is quietly failing:

sudo -u postgres psql -d appdb -c "SELECT count(*) FROM pg_extension WHERE extversion <> (SELECT default_version FROM pg_available_extensions a WHERE a.name = extname)"
 count
-------
     0
(1 row)

Finally, run your slowest three production queries with EXPLAIN (ANALYZE, BUFFERS) and compare against the plans you captured before the outage. Plan changes across a major version are normal; a 30 ms index scan turning into a 40 second sequential scan usually means statistics, not a planner regression.

Troubleshooting

“Your installation references loadable libraries that are missing from the new installation.” The named file in loadable_libraries.txt is an extension .so you installed for the old major and not the new one. Install the matching package (postgis34_17, pg_repack_17, and so on) and re-run --check. If the extension is genuinely obsolete, DROP EXTENSION it in the old cluster first — pg_upgrade cannot drop it for you.

“All non-template0 databases must allow connections.” Someone set datallowconn = false on a database, usually to freeze it. pg_upgrade has to connect to every database to dump its schema.

sudo -u postgres psql -c "ALTER DATABASE archive_2019 WITH ALLOW_CONNECTIONS true"
ALTER DATABASE

“The source cluster contains prepared transactions.” Two-phase commit transactions cannot be carried across. Inspect them before you destroy them — an unresolved prepared transaction is usually a stuck application, not garbage.

sudo -u postgres psql -c 'SELECT gid, prepared, owner, database FROM pg_prepared_xacts'
      gid       |           prepared            | owner  | database
----------------+-------------------------------+--------+----------
 txn_88213_ord  | 2026-07-11 03:12:44.201+00    | app_rw | appdb
(1 row)

Then COMMIT PREPARED 'txn_88213_ord' or ROLLBACK PREPARED 'txn_88213_ord' as appropriate. Prepared transactions also hold back the transaction ID horizon, so one this old is a problem regardless of the upgrade — see VACUUM and autovacuum for what that costs you.

The new cluster will not start after the upgrade. Nine times out of ten it is a postgresql.conf copied wholesale from the old cluster containing a parameter the new major has removed or renamed. The server log names it exactly:

FATAL:  unrecognized configuration parameter "vacuum_defer_cleanup_age" in file
"/var/lib/pgsql/17/data/postgresql.conf" line 612

Comment the line out and start again. This is why step 7 says re-apply, not copy.

Queries are correct but text sorting looks wrong, or a unique index rejects a row it should accept. This is not pg_upgrade — it is a glibc collation change that came with the OS upgrade you did at the same time. Index ordering for text columns is baked in at build time. Any B-tree index on a collatable column has to be rebuilt:

sudo -u postgres reindexdb --all --concurrently --jobs=4

Plan for it whenever the upgrade moves you across a major OS release, as separate and longer work than the version upgrade itself.

Rolling back. If you used copy mode or --clone and have not yet started the new cluster with production traffic: stop the new cluster, restore the old cluster’s port in its postgresql.conf, and start postgresql-16. The old data directory was never touched. If you used --link and the new cluster has started, that path is closed — pg_upgrade will have moved the old cluster’s control file aside precisely so you cannot start it against half-modified files. Your rollback is a restore from backup, which is why step zero was proving one.

When this is the wrong approach

  • You cannot take the outage. pg_upgrade requires both clusters stopped, and there is no way around that. If the service has to keep answering, upgrade through logical replication instead: stand up the new major as a subscriber, let it catch up, then switch the application over — the mechanics are in logical replication in depth. It costs far more preparation and forces you to think hard about sequences, DDL and large objects, but the switchover becomes a connection-string change.
  • The database is small. Under a hundred gigabytes or so, pg_dump --format=directory and pg_restore --jobs=N are easier to rehearse and give you freshly built indexes and clean statistics on the far side. The extra hour buys a smaller surface area.
  • You are also changing machines. pg_upgrade operates on two data directories on one host. Replicate first and upgrade second, or restore a backup on the new host and upgrade there.
  • You want to change encoding, locale or checksum settings. None of these can change during an upgrade; pg_upgrade verifies they match and aborts otherwise. Changing them requires a dump and reload.
  • You are on a managed platform. RDS, Cloud SQL and Azure Database run pg_upgrade for you behind one API call. Driving it yourself is not an option, and the useful preparation is different: clear replication slots, check extension availability on the target version, schedule the window.

The authoritative reference is the PostgreSQL documentation for pg_upgrade, which lists every option and the full set of checks in the order they run.

If this is the kind of work you’d rather never own again, it’s the daily job of Managed Cloud Ops — book an infrastructure review.