Sub topic 5
Preparing for the upgrade
Most failed upgrades are decided before pg_upgrade starts. This chapter covers the preparation work: reading release notes, taking backups, installing binaries, matching extensions, and checking the old cluster for known blockers. I assume you can administer a PostgreSQL cluster (data directory, pg_ctl, psql), take backups with pg_dump or pg_basebackup, and know what an extension is. The examples upgrade from version 16 to 17, with binaries in /opt/pg16 and /opt/pg17. Replace these paths with your own.
What preparation has to achieve
By the end of preparation you should be able to answer five questions with evidence:
- What in the new version changes behavior for my application?
- Can I restore the old cluster if everything goes wrong?
- Are the new server binaries installed next to the old ones?
- Does every extension I use exist for the new version?
- Does the old cluster contain anything
pg_upgraderefuses to carry over?
The diagram shows how these steps depend on each other. Initializing the new cluster comes after them and is the subject of the next chapter.
Read the release notes for every version you skip
Release notes for a major version have a "Migration to Version N" section. It lists incompatibilities: removed features, changed defaults, renamed functions and catalog columns.
If you jump from 13 to 17, read the migration sections for 14, 15, 16 and 17. pg_upgrade skips intermediate versions, but your application does not. A default that changed in 15 still affects you.
While reading, sort each item into one of three groups:
- Blocks the upgrade.
pg_upgrade --checkwill fail. Examples are unsupported data types or missing libraries. - Changes behavior. The upgrade succeeds, but queries or permissions behave differently. Examples are changed default privileges on the
publicschema and changed function semantics. - Needs configuration changes. Parameters were renamed, removed, or got new defaults.
Only the first group stops pg_upgrade. The second group is where production incidents come from, so test those items in the rehearsal described below.
Take backups, and know what they protect
A backup is your last rollback path. With --link mode, it is the only one once the new cluster has started (see the transfer modes chapter). Take two kinds.
A physical base backup of the stopped or running old cluster:
/opt/pg16/bin/pg_basebackup -D /backup/pg16-base -Ft -z -P -X streamA dump of global objects, meaning roles and tablespace definitions. A base backup contains them already, but a small text file is easy to inspect and diff:
/opt/pg16/bin/pg_dumpall --globals-only > /backup/globals-pg16.sqlThen check that the backup can be restored. Restore the base backup to a scratch directory and start it on another port. An untested backup is only a hope.
If you plan to use --link, copy the configuration files separately as well. Files such as postgresql.conf, pg_hba.conf and pg_ident.conf may live outside the data directory on Debian-style layouts, and a restore of the data directory alone will not bring them back.
Check disk space
The space you need depends on the transfer mode:
| Mode | Extra space needed on the new data volume |
|---|---|
| Copy | About the size of the old data directory |
| Clone | Little at first, if the filesystem supports reflinks |
| Link | Small: catalogs and new cluster files only |
Measure rather than guess:
du -sh /data/pg16
df -h /dataRemember that pg_upgrade also writes log files and dump files for each database into a directory in the new cluster's location (pg_upgrade_output.d in recent versions). That is small for most databases, but a schema with hundreds of thousands of objects produces large schema dumps.
--link hard links work only within one filesystem. If the old and new data directories are on different mounts, link mode fails, so plan the directory layout now.
Install the new binaries beside the old ones
pg_upgrade needs both server versions installed at the same time. It starts the old server with the old binaries and the new server with the new ones. It also needs to know where each set lives, through --old-bindir and --new-bindir.
Install the new version from the same source as the old one, for example the PGDG packages, so that library versions and build options stay consistent. Install the server package, the contrib modules, and every extension package you use. Verify both sets:
/opt/pg16/bin/postgres --version
/opt/pg17/bin/postgres --version
/opt/pg17/bin/pg_upgrade --versionAlways run the pg_upgrade binary from the new version. It is built to understand the newer cluster layout, and the old version's copy cannot do the job.
Do not start the new server yet. Installing packages on some distributions creates and starts a default cluster. If that happens, stop and remove it, or you will have two servers competing for port 5432 and a new data directory that is not empty.
Match extensions
Extensions are the most common source of surprises. The new cluster must have the extension's shared library and control files available, built for the new major version. pg_upgrade does not copy extension code. It only recreates the catalog entries that say "extension X, version Y is installed".
List what each database in the old cluster uses. Extensions are per database, so loop over all of them:
for db in $(/opt/pg16/bin/psql -XAtc \
"SELECT datname FROM pg_database WHERE datallowconn" postgres); do
echo "== $db"
/opt/pg16/bin/psql -X -d "$db" -c \
"SELECT extname, extversion FROM pg_extension ORDER BY extname"
doneFor each extension in the output, confirm that:
- a package for the new major version exists;
- the new package ships a version of the extension that supports your installed
extversion, or an update path to it; - any entry in
shared_preload_libraries(for examplepg_stat_statements,pg_cron, ortimescaledb) has a build for the new version.
You can check the new side with:
SELECT name, default_version
FROM pg_available_extensions
ORDER BY name;Run this against a temporary instance of the new version, or after the new cluster is initialized.
Third-party extensions can have their own upgrade procedure. Some, such as PostGIS, document specific steps for major upgrades. Read that documentation before the maintenance window, and not during it.
Scan the old cluster for blockers
Some conditions fail the upgrade outright. pg_upgrade --check finds most of them, but you can find them earlier and fix them at your own pace.
Prepared transactions. The old cluster must not contain any:
SELECT gid, prepared, owner, database FROM pg_prepared_xacts;Commit or roll back every row with COMMIT PREPARED or ROLLBACK PREPARED. Stale prepared transactions are often forgotten, and they also hold back vacuum.
Replication slots. Slots on the old cluster are generally not carried to the new one, depending on the versions involved. List them:
SELECT slot_name, slot_type, active FROM pg_replication_slots;Note down which consumers (standbys, logical subscribers, CDC tools) depend on each slot, so you can recreate or resubscribe afterwards. Check the release notes of the target version for what it supports.
Unsupported data types in user tables. Most reg* types (such as regproc and regoper) store OIDs of system objects that change between versions, so columns of these types cannot be upgraded. regclass is the exception that is supported. Look for such columns:
SELECT n.nspname, c.relname, a.attname, t.typname
FROM pg_attribute a
JOIN pg_class c ON c.oid = a.attrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_type t ON t.oid = a.atttypid
WHERE c.relkind IN ('r', 'm')
AND a.attnum > 0
AND NOT a.attisdropped
AND t.typname IN ('regproc', 'regprocedure', 'regoper', 'regoperator',
'regconfig', 'regdictionary')
AND n.nspname NOT IN ('pg_catalog', 'information_schema');An empty result is what you want. Run it in each database. The exact list of unsupported types varies by version, so treat this query as a first filter and confirm with --check later.
Encoding and locale. The new cluster must be created with an encoding and locale that match the old one. Record them now, since the next chapter needs them:
SELECT datname, pg_encoding_to_char(encoding) AS encoding,
datcollate, datctype
FROM pg_database
ORDER BY datname;Also note the cluster-wide data checksum setting with SHOW data_checksums;. The old and new clusters must agree on it.
Old objects that are still around. Look for invalid indexes (pg_index.indisvalid = false) and half-finished CREATE INDEX CONCURRENTLY leftovers. Drop or rebuild them first. Clean-up before the upgrade shortens the maintenance window, because there is less to move and to analyze later.
Capture configuration
The new cluster starts with default settings, and pg_upgrade does not copy postgresql.conf. Save the old settings that differ from defaults:
SELECT name, setting, source
FROM pg_settings
WHERE source NOT IN ('default', 'override')
ORDER BY name;Keep this output, together with copies of pg_hba.conf and pg_ident.conf. After the new cluster is initialized you will merge settings by hand, and compare each one with the release notes. Do not copy the old postgresql.conf over the new one without reading it. Removed or renamed parameters stop the server from starting, and new defaults that suit the new version get overwritten.
Rehearse on a copy
The most reliable preparation is a full rehearsal. Restore the base backup onto a staging host with the same disk layout, install the new binaries there, and run the whole procedure: initialize, --check, upgrade, ANALYZE. A rehearsal gives you three things you cannot get otherwise:
- a measured duration for the maintenance window;
- a chance to run your application's test suite against the new version;
- a written runbook that you have already followed once.
Time the slow parts separately. In link mode the upgrade is fast, and the post-upgrade statistics rebuild often dominates the time before the application performs well again.
Preparation checklist
| Item | Done when |
|---|---|
| Release notes | Migration sections for all skipped versions read and sorted |
| Backups | Base backup and globals dump exist, and a restore was tested |
| Disk space | `df` shows enough room for the chosen mode, on one filesystem for `--link` |
| Binaries | Old and new `postgres --version` both succeed; no default new cluster running |
| Extensions | Every extension and preload library has a build for the new version |
| Blockers | No prepared transactions; slots, `reg*` columns, and invalid indexes handled |
| Configuration | Non-default settings, `pg_hba.conf`, encoding and locale recorded |
| Rehearsal | Full run on a copy completed and timed |
Exercise
Your old cluster has two databases, app and reporting. You run the extension query only against app and see that all extensions have new-version packages. Why is this not enough, and what else in preparation could still stop pg_upgrade --check?
Show answer
Extensions are installed per database, so reporting may use extensions (or libraries) that app does not, and each one needs a build for the new version. Run the extension query in every database that allows connections. Other blockers can remain: prepared transactions in pg_prepared_xacts, columns of unsupported reg* types in user tables, and an encoding, locale, or data checksum setting that the new cluster does not match.
Exercise
You plan to use --link and your new data directory is on a different mount from the old one. What goes wrong, and what does this mean for your backup plan?
Show answer
Hard links cannot cross filesystems, so link mode fails and you must either put both directories on one filesystem or use copy or clone mode. Also, once the new cluster has started after a link-mode upgrade, the old data files are shared with it and the old cluster must not be started. The tested backup from before the upgrade is then the only way back, so it must exist and be restorable before you begin.