Sub topic 3
What pg_upgrade does under the hood
This chapter assumes you can run a PostgreSQL cluster yourself. You should know what a data directory is, how pg_ctl starts and stops a server, and what pg_dump produces. You should also have read the earlier chapters on why major upgrades differ and how the upgrade approaches compare. Here you will learn what happens between the moment you run pg_upgrade and the moment it exits. Knowing this makes its error messages and its limits easier to understand.
The core idea: keep the data, rebuild the catalogs
A PostgreSQL cluster holds two kinds of on-disk state.
- User data files. These are the heap and index files of your tables, and their TOAST tables. TOAST is the side storage for large values. The page layout of these files rarely changes between major versions.
- System catalogs. These are tables such as
pg_class,pg_attributeandpg_proc. They describe every object in the cluster. Their structure changes in almost every major release, and tools and extensions read them directly.
A new major version cannot start on the old data directory, because it cannot read the old catalogs. A full dump and restore fixes this by rewriting everything, which is slow for large databases.
pg_upgrade takes a shortcut. It builds new catalogs in the new cluster from a schema-only dump of the old one. It then makes the old user data files appear in the new cluster. No row is read or rewritten.
The catch is that the new catalogs must point at the old files and must keep the same identities. This is why pg_upgrade has special machinery.
The phases of a run
A normal run goes through these phases in order.
| Phase | What happens | Touches old cluster? |
|---|---|---|
| Checks | Compares control data and scans for known incompatibilities | Read only |
| Schema dump | Dumps global objects and each database's schema from the old cluster | Read only |
| Schema restore | Replays the dump into the new cluster | No |
| Freeze and transaction state | Prepares transaction ID state in the new cluster | No |
| File transfer | Copies, clones or links user data files | Depends on mode |
| Script generation | Writes cleanup and follow-up scripts | No |
The diagram shows the same flow with the two clusters.
Checks
Before changing anything, pg_upgrade reads each cluster's control file, the same data that pg_controldata prints. It confirms that both clusters were shut down cleanly and that these settings match:
- the data page and block sizes
- the data checksum setting
- the largest identifier, index key and TOAST chunk sizes
- the encoding and locale settings of the template databases
Then it starts each server and scans the catalogs for objects it cannot carry over. Typical findings:
- columns that use
reg*types such asregprocorregclass, because their stored values depend on OIDs - certain removed data types
- extension libraries missing from the new installation
- tables declared
WITH OIDSin very old versions
Everything found is written to a text file, and the run stops before any change is made. --check runs only this phase.
Schema dump with binary-upgrade mode
pg_upgrade runs pg_dumpall --globals-only for roles, tablespaces and similar cluster-wide objects. For each database it runs pg_dump --schema-only with the internal --binary-upgrade flag. You cannot use this flag for a normal backup. It changes the dump in these ways:
- It adds calls to functions such as
binary_upgrade_set_next_pg_class_oid()before eachCREATE. These tell the new server which OID to give the next object it creates. - It emits
ALTER TABLE ...statements that restore details such as dropped columns, so column numbers (attnum) match the old files exactly. - It records frozen transaction ID and multixact values for each relation, so the old data stays visible.
The new cluster must have the pg_upgrade_support functions available. They are built into the server binaries, so you do not install anything.
Schema restore
pg_upgrade starts the new cluster on a temporary port and restores the dump with pg_restore. Every table, index, sequence, view and function is created again. Because of the OID-setting calls, each object gets its old identity. Each relation's file number is also set to match the old file, so the new catalog entry points at the old file name.
At this point the new catalogs are complete, but the tables are empty as far as the files on disk are concerned. They do not yet contain the old files.
Transaction state
Rows in your old files carry transaction IDs in their headers. For those rows to remain visible, the new cluster must agree about which transactions committed. pg_upgrade therefore does these things:
- It copies the old
pg_xact(commit status) andpg_multixactdirectories into the new cluster. Older versions called the first onepg_clog. - It runs
pg_resetwalon the new cluster to set the next transaction ID, the oldest transaction ID and the next multixact IDs to match the old cluster. - It resets the WAL position, so the new cluster starts a fresh WAL history. WAL from the old cluster is never replayed.
The third point is why you cannot attach an old standby to an upgraded primary. The WAL histories are unrelated. See the replicas chapter for what to do instead.
File transfer
Last, pg_upgrade moves the data files for every user relation into the new data directory, using the transfer mode you chose. The previous chapter covered the modes. The internal work is the same for all of them: for each relation it takes the file number from the old catalog, finds the segment files (16384, 16384.1, and so on) plus the free space map and visibility map forks, and places them under the new cluster's directory for that database.
Index files and the maps need care across versions. If a relation's file format changed between the two versions, pg_upgrade cannot reuse the file as is. Historically this happened with the visibility and free space map layouts, and pg_upgrade rewrote those files during the transfer. If an index format changed in an incompatible way, the release notes tell you to run REINDEX afterwards.
Looking at what it did
You can observe the identity-preserving behavior directly. In link mode, the new file name matches the old one and is the same inode. This query runs on both clusters, and the path comes out the same:
CREATE TABLE IF NOT EXISTS orders (id bigint PRIMARY KEY, placed_at timestamptz);
SELECT oid, relfilenode, pg_relation_filepath('orders') AS path
FROM pg_class
WHERE relname = 'orders';The oid and relfilenode values are the same before and after. If you recreated the table with a dump and restore instead, they would be different.
pg_upgrade keeps its logs and dumps for inspection. Since version 15 they are in a pg_upgrade_output.d directory under the new data directory:
ls /data/pg17/pg_upgrade_output.d/*/Typical contents:
log/pg_upgrade_internal.log: the main loglog/pg_upgrade_dump_*.custom: the per-database schema dumpslog/pg_upgrade_server.log: the log of the temporary serverslog/pg_upgrade_utility.log: logs from helper programs such aspg_resetwal
When a run fails, these files tell you which command failed and why. On success the directory is removed unless you pass --retain. In older versions the logs were written to the directory you ran the command from.
Gotchas and failure modes
The temporary servers
pg_upgrade starts both servers itself, on port 50432 by default, listening on a Unix socket in the current directory. Settings such as listen_addresses are overridden for these runs. So you do not have to remove pg_hba.conf access rules for the check. But you do need these things:
- Both clusters must be stopped before you start, or
pg_upgraderefuses to run. - The user must be able to connect as the superuser. If you use
peerauthentication, run as thepostgresoperating system user. - A
postgresql.confthat lives outside the data directory, as on Debian-style packaging, needs the--old-optionsand--new-optionsflags. - Do not use
-pfor the temporary servers. Use--old-portand--new-port.
Settings are not copied
pg_upgrade carries over the catalogs and data, but not the configuration files. Your postgresql.conf and pg_hba.conf are not read or merged. You must port your settings to the new cluster by hand. Compare them against the new version's defaults, because parameter names and defaults change between releases.
Failure timing decides your options
Where a failure happens determines whether you can retry.
- Before the transfer step: nothing has changed in the old cluster. You fix the problem, delete and re-create the new data directory, and run again.
- During the transfer, in copy or clone mode: the old cluster is still intact. You delete the new directory and retry.
- During or after the transfer in link mode: the old and new clusters share files. Once the new cluster has been started and has changed any data, the old cluster is no longer usable. Rollback then means restoring from backup.
The link-mode behavior is why the fast path needs a tested backup first.
What is not transferred
Some state is not carried across, or only on newer versions:
- Optimizer statistics. Versions before 18 do not carry them across. Without statistics the planner works poorly until you run
vacuumdb --all --analyze-in-stages. Version 18 and later can keep them. - Logical replication slots. Slots on the old cluster are migrated only when the old cluster is version 17 or later.
- Extension upgrades. The extension objects come across at their old versions. Updating them is a separate step, and
pg_upgradewritesupdate_extensions.sqlto help. - Tablespace contents. User tablespaces are supported, but the new cluster uses a version-specific subdirectory inside the same tablespace location. Both clusters then live inside the same directory.
Summary of the model
- The user data files are reused. The catalogs are rebuilt from a schema-only dump taken in binary-upgrade mode.
- Special calls preserve OIDs and file numbers so the new catalog entries match the old files.
- Transaction state is copied or reset so old rows stay visible.
- WAL history starts fresh, so old standbys cannot follow the new primary.
- Configuration and (before version 18) optimizer statistics are not carried over.
Exercise
After a pg_upgrade run in link mode, a colleague proposes starting the old cluster again "just to compare a few rows." The new cluster has already been started once and accepted writes. Why is this unsafe, and what does the schema restore phase do that lets the new cluster use the old files at all?
Show answer
In link mode the old and new data directories contain hard links to the same files, so any write by the new cluster has already changed data the old cluster would read. The old cluster's view would no longer match its own commit status and WAL, so starting it can corrupt the shared files. The only safe way back is a backup. The new cluster can use the old files because the schema dump taken with --binary-upgrade makes the restore recreate every object with its old OID and relfilenode, so the new catalogs point at the existing files. pgupgrade also copies pgxact and pgmultixact and sets the transaction counters with pgresetwal, so the old rows stay visible.
Exercise
A run fails with an error that the old and new clusters differ in a setting that pgupgrade checks, even though both initdb commands looked identical. Name two settings pgupgrade compares from the control files, and name the log directory (version 15 and later) where you would look for details.
Show answer
It compares settings such as the data checksum setting, the block size, the encoding and locale of the template databases, and the identifier and TOAST chunk size limits. The details are in the pgupgradeoutput.d directory under the new data directory, mainly log/pgupgradeinternal.log and the other files in the same log directory.