Sub topic 2
Choosing an upgrade approach
PostgreSQL gives you three ways to move to a new major version: dump and restore, pg_upgrade, and logical replication. This chapter compares them and gives you criteria for choosing one. The later chapters in this tutorial run pg_upgrade step by step.
This chapter assumes you can administer a single PostgreSQL cluster (data directory, pg_ctl, psql). It also assumes you have used pg_dump or pg_basebackup and know what a publication and a subscription are in broad terms.
The three approaches in one view
All three approaches end in the same place: a new cluster running the new major version with your data in it. They differ in how the data gets there, how long the application is down, and what can go wrong.
| Aspect | Dump and restore | `pg_upgrade` | Logical replication |
|---|---|---|---|
| Data movement | Logical export, then re-import | Reuses data files (copy, clone or link) | Initial table copy, then streamed changes |
| Downtime scales with | Database size | Number of objects, and the transfer mode | Cutover only (seconds to minutes) |
| Old cluster kept intact | Yes, always | Yes, unless you used `--link` and started the new cluster | Yes, always |
| Can change encoding, locale, block size | Yes | No, the new cluster must match | Yes (per database) |
| Extra disk space | Dump file plus new cluster | Roughly a second copy in copy mode, little in link mode | A full second cluster |
| Complexity | Low | Medium | High |
| Best fit | Small databases, cross-platform moves | Most in-place upgrades | Near-zero-downtime requirements |
Dump and restore
This is the oldest method and the simplest to reason about. You export the database as SQL (or an archive) using the new version's pg_dump, then load it into a freshly initialized new cluster.
# Roles and tablespaces are not part of a per-database dump.
/opt/pg17/bin/pg_dumpall -h oldhost --globals-only > /backup/globals.sql
# Directory format allows parallel dump and parallel restore.
/opt/pg17/bin/pg_dump -h oldhost -Fd -j 4 -f /backup/appdb.dir appdb
# On the new cluster:
/opt/pg17/bin/psql -d postgres -f /backup/globals.sql
/opt/pg17/bin/pg_restore -C -d postgres -j 4 /backup/appdb.dirUse the new version's pg_dump against the old server. Newer pg_dump binaries know how to read older servers, and they emit SQL that the new server understands.
Strengths:
- It rebuilds everything from scratch. Table and index bloat disappears, and indexes are built fresh.
- It is the only method that lets you change block size, move to a different CPU architecture or operating system, or switch encoding without extra tools.
- The old cluster is never touched, so rollback is trivial.
Weaknesses:
- Downtime lasts as long as the dump plus the restore, including index builds. For a multi-terabyte database that is hours or days.
- If writes continue during the dump, they are missing from the new cluster. For a consistent move you must stop writes for the whole window.
A common pattern for small databases (a few gigabytes) is to accept the downtime. Parallel restore with -j shortens it, but it never scales like the other two methods.
pg_upgrade
pg_upgrade creates the new cluster's catalogs from the old cluster's schema, then makes the old user data files available to the new cluster. It does not re-export row data. That is why it is fast. The next chapter covers the internals.
/opt/pg17/bin/pg_upgrade \
--old-bindir=/opt/pg16/bin \
--new-bindir=/opt/pg17/bin \
--old-datadir=/data/pg16 \
--new-datadir=/data/pg17 \
--linkThree transfer modes decide how the data files get to the new cluster:
- Copy duplicates every file. It is slowest and needs the most disk, but the old cluster stays valid.
- Clone uses file-system reflinks where supported. It is fast, and the old cluster stays valid.
- Link creates hard links. It is the fastest, and downtime barely depends on data size, but once the new cluster starts, the old one cannot be used safely.
Strengths:
- Downtime is typically minutes, even for very large databases, when you use
--linkor--clone. - It is a supported, widely used path across many versions. You can usually skip intermediate majors (for example 12 to 17) in a single run.
- It needs no changes to the application.
Weaknesses:
- Downtime is still real. Both clusters must be stopped while it runs.
- The new cluster must be compatible with the old one in settings that affect on-disk format: encoding, locale provider settings, data checksums, and block size. You cannot use
pg_upgradeto change these. - Old planner statistics were not carried across by older versions, so you must rebuild them afterwards. Until you do, query plans can be poor.
- Extensions need compatible shared libraries installed for the new version. Some data types and extensions block the upgrade until you change them.
- Bloat in the old cluster comes along with the data files.
Logical replication
Here you build the new cluster alongside the old one and let PostgreSQL replicate changes to it while the application keeps running. At a chosen moment you stop writes on the old cluster, let the new one catch up, and point the application at the new one.
The outline:
- On the old cluster (the publisher), set
wal_level = logicaland restart if it was not already set. - Copy the schema to the new cluster. Logical replication does not replicate DDL (schema changes).
- Create a publication on the old cluster and a subscription on the new cluster.
- Wait until the initial table copy finishes and replication lag is near zero.
- Stop application writes, wait for the subscriber to catch up, and fix sequences.
- Switch the application to the new cluster.
# Schema only, using the new version's pg_dump.
/opt/pg17/bin/pg_dump -h oldhost -s -d appdb > /backup/appdb-schema.sql
/opt/pg17/bin/psql -h newhost -d appdb -f /backup/appdb-schema.sql-- On the old cluster (publisher), connected to appdb:
CREATE PUBLICATION upgrade_pub FOR ALL TABLES;
-- On the new cluster (subscriber), connected to appdb:
CREATE SUBSCRIPTION upgrade_sub
CONNECTION 'host=oldhost port=5432 dbname=appdb user=replicator'
PUBLICATION upgrade_pub;The connection string needs a role with the REPLICATION attribute (or equivalent privileges) on the old cluster. Supply the password through a .pgpass file or the PGPASSFILE environment setting on the new server, not in the SQL text.
Strengths:
- Application downtime shrinks to the cutover itself, often under a minute.
- You can test the new cluster with real, live data for days before committing.
- Rollback is simple before cutover. You drop the subscription and carry on with the old cluster.
- You can change encoding or other cluster-level settings, and you also get fresh, unbloated tables.
Weaknesses (these are the ones that bite):
- Sequences are not replicated. After cutover, sequences on the new cluster still hold their initial values. Inserts then fail with duplicate keys. You must copy sequence values before you open the new cluster to writes.
- DDL is not replicated. Schema changes during the migration must be applied to both sides by hand.
- Large objects are not replicated. Data stored with
lo_*functions must be moved another way. - Tables need a replica identity. A table that receives
UPDATEorDELETEneeds a primary key, or an explicitly configured replica identity, on the publisher. - You run two full clusters at once, with extra write-ahead log (WAL) retention on the old cluster while the subscriber falls behind.
- More moving parts, so more to monitor: replication slots, lag, and subscription errors.
A sequence fix-up can be generated from the old cluster at cutover time, after writes have stopped:
-- Run on the old cluster. Output is a list of setval statements
-- to run on the new cluster.
SELECT format('SELECT setval(%L, %s);',
quote_ident(schemaname) || '.' || quote_ident(sequencename),
last_value)
FROM pg_sequences
WHERE last_value IS NOT NULL;Deciding between them
Start from your downtime budget and work outward. The questions below usually settle the choice.
Work through these criteria in order:
- Do you need a different encoding, block size, architecture or operating system? If so,
pg_upgradeis ruled out. Choose dump and restore or logical replication. - How much downtime can you accept? Hours: any method works, and dump and restore is the simplest. Minutes:
pg_upgradewith--linkor--clone. Seconds: logical replication. - How large is the database? Under a few gigabytes, the speed difference rarely matters. At hundreds of gigabytes or more, a full dump and restore is rarely acceptable.
- How much rollback safety do you need? Dump and restore and logical replication leave the old cluster untouched.
pg_upgrade --linkis the least reversible once the new cluster has started, so you need a backup or a replica as your fallback. Chapter "Planning for rollback" covers this. - Does your schema suit logical replication? Tables without primary keys, heavy use of large objects, or frequent schema changes make it harder.
- How much operational skill and time do you have? Logical replication has the longest rehearsal time.
pg_upgradeis the middle ground.
For most self-managed PostgreSQL servers, the answer is pg_upgrade. The tradeoff is a short, planned outage in exchange for a procedure that is well understood and quick to rehearse. Reach for logical replication when the outage budget is truly tiny and you have time to test.
Combining approaches
The approaches are not exclusive. Two combinations are common:
pg_upgradeplus replicas. Upgrade the primary withpg_upgrade, then rebuild standbys from it. A later chapter covers the standby procedure.- Dump and restore for one troublesome database. If a cluster holds one database with an unsupported extension state, you can restore that database separately while the rest goes through
pg_upgrade. This adds complexity, so do it only when you have to.
Managed services (Amazon RDS, Cloud SQL and similar) wrap these same mechanisms behind their own upgrade commands. The trade-offs on this page still apply to what happens underneath.
Exercises
Exercise
A team runs a 1.5 TB PostgreSQL 15 cluster. They can accept a 20-minute maintenance window, the new cluster will use the same encoding and block size, and they have a tested backup. Which approach fits best, and which transfer mode would you choose if rollback is handled by the backup?
Show answer
Use pg_upgrade. A dump and restore of 1.5 TB would take far longer than 20 minutes, and logical replication is more complex than the window requires. With rollback covered by the backup, --link gives the shortest downtime. If they wanted to keep the old cluster valid after the new one starts, --clone (on a file system that supports it) would be the safer fast choice.
Exercise
After a logical-replication cutover, the application starts failing with "duplicate key value violates unique constraint" on tables that load correctly. What was missed, and how do you fix it?
Show answer
Sequences are not replicated, so the new cluster's sequences still hold their starting values and reissue IDs that already exist. Generate setval statements from pg_sequences on the old cluster after writes stop, run them on the new cluster, and add this step to the cutover runbook.
Exercise
Name two requirements that rule out pg_upgrade, and say which other approaches remain.
Show answer
Needing a different encoding or block size, or moving to a different CPU architecture or operating system. pg_upgrade needs the new cluster to match the old on-disk format. Dump and restore, or logical replication, remain available.