PostgreSQL migration and upgrade tools step by step: pg_dump, pg_upgrade and logical replication

Moving a PostgreSQL database to a new major version, a new server or a managed service comes down to a handful of tools. This guide explains which tool fits which move and how to run each one step by step: pg_dump and pg_restore, pg_upgrade, the upgrade function of the managed services, logical replication, blue/green deployments on Amazon RDS and Aurora, and pgloader for a change of engine.

Which tool for which move

Three questions decide the tool: does the database stay on the same server, can you reach its data files, and how long may the application be unavailable. On a managed service you have no access to the data files, so pg_upgrade is only available there through the service's own upgrade function.

  • New major version on your own server: pg_upgrade. With --link or --clone it takes minutes whatever the size of the database; in the default copy mode it takes about as long as copying the data directory.
  • New server, other operating system or a managed service, with a maintenance window of hours: pg_dump and pg_restore. This works between any versions and from any source to any PostgreSQL target, and the source stays untouched.
  • New major version on RDS, Aurora, Azure, Cloud SQL or AlloyDB: the service's in-place major version upgrade, or on RDS and Aurora a blue/green deployment when the switch has to be shorter.
  • Any move with minutes or seconds of downtime: logical replication (publication and subscription), or a migration service built on it (the Azure migration service, Google Database Migration Service, AWS DMS).
  • From MySQL or SQL Server to PostgreSQL: pgloader for the data, but converting the schema and the code is the bigger job.
RouteDowntime classWay backMain prerequisites
pg_dump + pg_restoreOffline: grows with the sizeSource untouched: reconnect the applicationClient tools of the target version; roles and extensions on the target
pg_upgrade --linkOffline: minutes, depends on the number of objectsRestore of the backup taken before (the old cluster is unusable once the new one has started)Old and new binaries on one server, same file system, --check without errors
pg_upgrade (copy or clone)Offline: copy grows with the size, clone takes minutesOld cluster untouched: start it againCopy: room for a second data directory; clone: Btrfs, XFS with reflink or APFS
In-place upgrade on a managed serviceOffline: minutes to an hour or moreSnapshot or point-in-time restore to a new instanceSupported version path, extensions accepted by the pre-check, read replicas dealt with
Logical replicationMinimal or near-zero: depends on the switchSource kept as it was at the switch; replication back is possiblewal_level = logical, primary key or replica identity, no reliance on large objects or unlogged tables, DDL freeze
RDS / Aurora blue/greenNear-zero: AWS states usually under a minuteOld environment kept read-only as -old1rds.logical_replication = 1, primary keys, no DDL or large-object changes during the deployment
pgloaderOffline: grows with the sizeSource untouchedSchema and code converted and tested first

Whatever the route, rehearse it on a copy and time every step: that time, not an estimate, is your downtime. The free scan shows which of these routes fit your database and the target you choose; the full report contains the runbook of the chosen route with the commands filled in for your database.

pg_dump and pg_restore step by step

pg_dump makes a logical copy of one database: the SQL that creates the schema plus the data of every table. pg_restore loads it into another server, in parallel when the dump is in custom or directory format. It works from any supported version to any newer one and to every managed service, which makes it the default route for a move with a maintenance window. Prerequisites:

  • Use the client tools of the target version or newer: a newer pg_dump reads older servers, not the other way round.
  • Roles and tablespaces are not in the dump. They are global objects: export the roles with pg_dumpall --roles-only and create them on the target first. On a managed service, first remove the attributes that are not allowed there (SUPERUSER, REPLICATION, BYPASSRLS).
  • Extensions: the dump contains CREATE EXTENSION, not the extension itself. Install the same extensions on the target first; on a managed service, check that each one is supported or allow-listed, and add those that need it to shared_preload_libraries (for example pg_cron or pg_stat_statements).
  • Managed services: restore with --no-owner, --no-tablespaces and --role= followed by your admin role, because that role is not a superuser there. Add --no-privileges only when you have not recreated the roles: it leaves out every GRANT.
  • Large objects (pg_largeobject) are part of a dump of the whole database, but not when you select schemas or tables with --schema or --table. Millions of them make the dump and the restore much slower: count them first.
  • Connections: pg_dump -j 4 opens five connections to the source and pg_restore -j 4 four to the target; check max_connections.
FormatOptionParallel dumpParallel restoreRestore with
Plain SQL-Fp (default)NoNopsql -f
Custom-FcNoYes, pg_restore -jpg_restore
Directory-FdYes, pg_dump -jYes, pg_restore -jpg_restore
Tar-FtNoNopg_restore
pg_dump and pg_restore to a new server or a managed service
# 1. Roles and tablespaces are not in pg_dump: export the roles from the source
pg_dumpall -h <source-host> -U <superuser> --roles-only > /backup/roles.sql
# own server: run it on the target (an error that your admin role already exists is expected)
# managed service: first remove SUPERUSER, REPLICATION and BYPASSRLS from roles.sql
psql -h <target-host> -U <admin> -d postgres -f /backup/roles.sql

# 2. Dump the source: directory format, 4 parallel jobs, compression level 5
pg_dump -h <source-host> -U <user> -d <database> -Fd -j 4 -Z 5 -f /backup/<database>.dir

# 3. Target: empty database (same encoding and locale as the source), extensions first, then the parallel restore
createdb -h <target-host> -U <admin> -T template0 -E UTF8 <database>
psql -h <source-host> -U <user> -d <database> -Atc "SELECT extname FROM pg_extension WHERE extname <> 'plpgsql';"
psql -h <target-host> -U <admin> -d <database> -c "CREATE EXTENSION IF NOT EXISTS <extension>;"
pg_restore -h <target-host> -U <admin> -d <database> -j 4 /backup/<database>.dir
# managed service instead:
pg_restore -h <target-host> -U <admin> -d <database> -j 4 --no-owner --no-tablespaces --role=<admin> /backup/<database>.dir

# 4. Planner statistics
vacuumdb -h <target-host> -U <admin> -d <database> --analyze-in-stages -j 4

The dump reads one consistent snapshot, so the application can keep running during the dump, but nothing it writes after the start is in it. For the real migration, stop writes before the dump starts.

Timing, as a rough guide only: the restore usually takes longer than the dump, because every index is built and every foreign key checked after the data has been loaded. The parallel restore spreads that work over the jobs, but one very large table is still loaded by a single job. Measure both steps on a copy of your own database, with the same hardware and network.

pg_dump does not include planner statistics by default, so the target starts without them. vacuumdb --analyze-in-stages first computes rough statistics for every table, so that queries get usable plans quickly, then repeats the work with the full sample.

Plain SQL suits small databases and can be read and edited; use the directory format for anything large. The custom format gives a single file and still allows a parallel restore and the restore of single objects with pg_restore -l and -L.

pg_upgrade step by step

pg_upgrade upgrades a cluster to a new major version on the same server. It dumps and restores only the schema (the system catalogue) and reuses the data files as they are, which is why it is fast. The binaries of both versions are installed side by side, and the new cluster is created empty with initdb before the upgrade. Prerequisites:

  • The same settings for the new cluster: the same encoding and locale as the old one. From PostgreSQL 18 on, initdb enables data checksums by default and pg_upgrade refuses clusters whose checksum settings differ: check SHOW data_checksums; on the old cluster and add --no-data-checksums where needed.
  • Run --check first. It reports incompatibilities without changing anything (for example columns of reg* types, or extensions without a build for the new version) and can run while the old cluster is still in use.
  • Extensions: install the extension packages for the new version, but do not run CREATE EXTENSION in the new cluster: pg_upgrade carries the extensions over. Where newer extension versions exist, it writes the script update_extensions.sql; you can also run ALTER EXTENSION … UPDATE yourself.
  • Configuration: postgresql.conf and pg_hba.conf of the new cluster are new files; carry over your settings before you open the new cluster to the application.
  • Standbys are not upgraded by pg_upgrade itself: upgrade them with rsync as the documentation describes, or rebuild them afterwards.
ModeOptionTimeOld cluster afterwards
Copy--copy (default)Grows with the size of the dataUntouched: can be started again
Link--linkMinutes, whatever the sizeUnsafe once the new cluster has started: restore from the backup
Clone--cloneMinutes (copy-on-write)Untouched; Linux with Btrfs or XFS with reflink, or macOS with APFS
Copy file range--copy-file-range (17+)Faster copy on some file systemsUntouched; Linux and FreeBSD
Swap--swap (18+)Moves the data directories: the fastestDestroyed as soon as the file transfer starts
Upgrade a cluster with pg_upgrade --link
# Run as the operating system user that owns the data directories (usually postgres).
# 0. New, empty cluster with the same encoding, locale and checksum setting as the old one
psql -d postgres -c "SHOW data_checksums;"   # on the old cluster
<new bindir>/initdb -D <new datadir> -E UTF8 --locale=<locale of the old cluster> --no-data-checksums
#    --no-data-checksums only when the old cluster has none (initdb enables them by default from PostgreSQL 18)

# 1. Check: changes nothing, the old cluster may keep running
pg_upgrade --check -b <old bindir> -B <new bindir> -d <old datadir> -D <new datadir> -j 4

# 2. Backup first: after --link it is your only way back
pg_basebackup -h <host> -U <replication user> -D /backup/base -Ft -z -P

# 3. Stop the old cluster, then upgrade
<old bindir>/pg_ctl -D <old datadir> stop -m fast
pg_upgrade -b <old bindir> -B <new bindir> -d <old datadir> -D <new datadir> --link -j 4

# 4. Start the new cluster, then statistics and extensions
<new bindir>/pg_ctl -D <new datadir> start
vacuumdb --all --analyze-in-stages -j 4                        # new version 17 or older
vacuumdb --all --analyze-in-stages --missing-stats-only -j 4   # new version 18 or later (statistics were carried over) ...
vacuumdb --all --analyze-only -j 4                             # ... followed by this
psql -d <database> -c "SELECT extname, extversion FROM pg_extension;"   -- then ALTER EXTENSION <name> UPDATE; where a newer version exists

With --link the old and the new cluster share the data files. If pg_upgrade stopped before linking, the old cluster is unchanged. If it finished but you have not started the new cluster yet, you can still go back by removing the .old suffix from global/pg_control in the old data directory. Once the new cluster has started, it writes to the shared files and the only way back is the backup: take it before the upgrade and know how long its restore takes.

Statistics: up to PostgreSQL 17 the new cluster starts without planner statistics, and vacuumdb --all --analyze-in-stages straight after the upgrade is essential. When the new version is 18 or later, pg_upgrade carries over most optimizer statistics (not all of them: statistics added by extensions and the activity statistics are not transferred; --no-statistics switches the transfer off). The documentation of versions 18 and 19 then recommends vacuumdb --all --analyze-in-stages --missing-stats-only followed by vacuumdb --all --analyze-only.

The time of a link or clone upgrade depends on the number of objects (tables, indexes, large objects), not on the data volume: a database with tens of thousands of tables takes longer than a large database with a few hundred.

Major version upgrades on managed services

On RDS, Aurora, Azure Database for PostgreSQL, Cloud SQL and AlloyDB you cannot run pg_upgrade yourself; each service runs it for you, with its own pre-checks. The database is unavailable during the upgrade, and the upgrade cannot be undone in place: the way back is a snapshot or a point-in-time restore to a new instance. Test the upgrade first on a copy restored from a snapshot.

ServiceWhat the service doesWatch out for
Amazon RDS for PostgreSQLRuns its checks, then the upgrade; with automated backups on, it takes snapshots during the upgradeThe pre-check lists what blocks the upgrade (for example unsupported extensions); a custom parameter group needs a counterpart for the new version
Amazon Aurora PostgreSQLUpgrades the whole cluster, writer and readers togetherCluster and instance parameter groups for the new version; a blue/green deployment shortens the downtime
Azure Database for PostgreSQL flexible serverPre-check, an implicit backup, then pg_upgrade; versions can be skippedNo automatic way back (point-in-time restore to a new server); read replicas must be removed first; some extensions must be dropped first; 10 to 20% free storage
Cloud SQL for PostgreSQLBackups before and after the upgrade; Google states that a single instance usually takes less than 10 minutesSeparate pre-check command; the upgrade deletes logical replication slots, which must be recreated
AlloyDB for PostgreSQLUpgrades all instances of the cluster in one operation; rolls back by itself when it fails before the primary is upgradedGoogle states about 20 minutes to an hour of downtime for the primary, mostly depending on the schema; test on a clone
Start the upgrade from the command line
# Take a manual snapshot first and test the upgrade on a copy restored from it.

# Amazon RDS for PostgreSQL (custom parameter group: add --db-parameter-group-name <group for the new version>)
aws rds modify-db-instance --db-instance-identifier <id> --engine-version <version> --allow-major-version-upgrade --apply-immediately

# Amazon Aurora PostgreSQL (custom parameter groups: add --db-cluster-parameter-group-name and --db-instance-parameter-group-name)
aws rds modify-db-cluster --db-cluster-identifier <id> --engine-version <version> --allow-major-version-upgrade --apply-immediately

# Azure Database for PostgreSQL flexible server
az postgres flexible-server upgrade -g <resource group> -n <server> --version <version>

# Cloud SQL for PostgreSQL: pre-check, then the upgrade
gcloud sql instances pre-check-major-version-upgrade <instance> --target-database-version=POSTGRES_<version>
gcloud sql instances patch <instance> --database-version=POSTGRES_<version>

# AlloyDB for PostgreSQL
gcloud alloydb clusters upgrade <cluster> --region=<region> --version=POSTGRES_<version>

# Afterwards, in every database: statistics and extensions
psql -h <host> -U <admin> -d <database> -c "ANALYZE;"
psql -h <host> -U <admin> -d <database> -c "SELECT extname, extversion FROM pg_extension;"   -- then ALTER EXTENSION <name> UPDATE;

After every in-place upgrade, run ANALYZE in each database (statistics are not always carried over) and update the extensions with ALTER EXTENSION … UPDATE where the service has not done so. On RDS and Aurora, a blue/green deployment (see below) reduces the downtime of a major version upgrade to the switchover.

Logical replication for minimal or near-zero downtime

Logical replication sends row changes from a publication on the source to a subscription on the target. It works between different major versions (from PostgreSQL 10 on) and between your own servers and managed services, so it covers an upgrade and a move at the same time. The target first receives a full copy of every table, then keeps up with the changes until the switch. The switch itself means stopping writes, waiting until the lag is zero, setting the sequences and reconnecting the application. Prerequisites and limits:

  • wal_level = logical on the source, which needs a restart, with enough max_replication_slots and max_wal_senders: one slot per subscription plus spare ones for the table synchronisation during the initial copy. Managed sources use their own setting: rds.logical_replication = 1 on RDS and Aurora, the server parameter wal_level = logical on Azure, the flag cloudsql.logical_decoding on Cloud SQL and alloydb.logical_decoding on AlloyDB.
  • A primary key or replica identity on every table that gets updates or deletes. Without one, the source refuses those updates and deletes as soon as the table is in a publication. Add a primary key, or use a unique index on NOT NULL columns with REPLICA IDENTITY USING INDEX. REPLICA IDENTITY FULL is the last resort: every change logs the whole old row and the target has to search for it, which is slow on large tables without a suitable index.
  • Not replicated: DDL (schema changes), large objects, unlogged and temporary tables, materialized views (refresh them on the target) and, before PostgreSQL 19, sequence values. TRUNCATE is replicated.
  • Rights: CREATE PUBLICATION … FOR ALL TABLES needs a superuser, or on a managed service the admin role the provider documents for it; the user of the subscription connection needs the REPLICATION attribute (or the service's equivalent) and read rights on the tables.
1. Source: settings and the tables that stand in the way
-- on the source
SHOW wal_level;                 -- must be logical (changing it needs a restart)
SHOW max_replication_slots;     -- free slots: one per subscription plus some for the initial table sync
SHOW max_wal_senders;
-- managed sources set instead: rds.logical_replication = 1 (RDS, Aurora), wal_level = logical (Azure server parameter),
-- cloudsql.logical_decoding = on (Cloud SQL), alloydb.logical_decoding = on (AlloyDB)

-- tables without a usable replica identity: updates and deletes fail once they are published
SELECT c.oid::regclass AS table_name, c.relreplident
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND c.relpersistence = 'p'
  AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg_toast%'
  AND (c.relreplident = 'n'
    OR (c.relreplident = 'd' AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary))
    OR (c.relreplident = 'i' AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisreplident)));

-- not replicated: unlogged tables and large objects
SELECT oid::regclass AS unlogged_table FROM pg_class WHERE relkind = 'r' AND relpersistence = 'u';
SELECT count(*) AS large_objects FROM pg_largeobject_metadata;

-- fix: a primary key where possible, REPLICA IDENTITY FULL as a last resort
ALTER TABLE public.order_line ADD PRIMARY KEY (order_id, line_no);
ALTER TABLE public.audit_log REPLICA IDENTITY FULL;
2. Publication, schema and subscription
# 1. Source: publication (wal_level = logical is set and the server has been restarted)
psql -h <source-host> -U <user> -d <database> -c "CREATE PUBLICATION mmdb_pub FOR ALL TABLES;"

# 2. Target: roles, empty database, schema only
pg_dumpall -h <source-host> -U <superuser> --roles-only > /backup/roles.sql
psql -h <target-host> -U <admin> -d postgres -f /backup/roles.sql   # an error that your admin role already exists is expected
#    managed target: first remove SUPERUSER, REPLICATION and BYPASSRLS from roles.sql
createdb -h <target-host> -U <admin> -T template0 -E UTF8 <database>
pg_dump -h <source-host> -U <user> -d <database> --schema-only | psql -h <target-host> -U <admin> -d <database>

# 3. Target: subscription (creates the replication slot on the source and starts the initial copy)
psql -h <target-host> -U <admin> -d <database> -c "CREATE SUBSCRIPTION mmdb_sub CONNECTION 'host=<source-host> dbname=<database> user=<replication user> password=<password>' PUBLICATION mmdb_pub;"
3. Follow the initial copy and the lag
-- target: state per table (r = ready; i, d, f, s = still copying or synchronising)
SELECT srrelid::regclass AS table_name, srsubstate FROM pg_subscription_rel ORDER BY 2, 1;

-- target: the apply worker of the subscription
SELECT subname, received_lsn, latest_end_lsn, last_msg_receipt_time FROM pg_stat_subscription;

-- source: lag per subscriber, in bytes (0 = caught up)
SELECT application_name, state, pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS lag_bytes FROM pg_stat_replication;

-- source: WAL held back per slot (an inactive slot keeps WAL until the disk is full)
SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS retained
FROM pg_replication_slots;
4. The switch, the sequences and the clean-up
# 1. Stop writes on the source (application in maintenance mode) and wait until lag_bytes is 0

# 2. Copy the sequence values (logical replication does not carry them before PostgreSQL 19)
psql -h <source-host> -U <user> -d <database> -Atc "SELECT format('SELECT setval(%L, %s, true);', quote_ident(schemaname) || '.' || quote_ident(sequencename), last_value) FROM pg_sequences WHERE last_value IS NOT NULL" | psql -h <target-host> -U <admin> -d <database>

# 3. Compare row counts on both sides, then point the application to the target

# 4. When the go-live is accepted: drop the subscription (this also drops its slot on the source) and the publication
psql -h <target-host> -U <admin> -d <database> -c "DROP SUBSCRIPTION mmdb_sub;"
psql -h <source-host> -U <user> -d <database> -c "DROP PUBLICATION mmdb_pub;"

# Source no longer reachable? Detach the slot first, then drop it on the source later:
#   ALTER SUBSCRIPTION mmdb_sub DISABLE;  ALTER SUBSCRIPTION mmdb_sub SET (slot_name = NONE);  DROP SUBSCRIPTION mmdb_sub;
#   SELECT pg_drop_replication_slot('mmdb_sub');   -- on the source
Source on PostgreSQL 19 or later: sequences through the subscription
-- source (publisher) on PostgreSQL 19 or later: publish the sequences together with the tables
CREATE PUBLICATION mmdb_pub FOR ALL TABLES, ALL SEQUENCES;

-- target: CREATE SUBSCRIPTION copies the current sequence values once;
-- at the switch, after writes have stopped, copy them again:
ALTER SUBSCRIPTION mmdb_sub REFRESH SEQUENCES;

During the initial copy, the slot keeps WAL on the source until the target has caught up, so plan disk space on the source for the changes of the whole copy period. max_sync_workers_per_subscription (default 2) sets how many tables are copied at the same time; the changes are applied by a single worker per subscription.

Freeze schema changes until after the switch. When a change cannot wait, apply it to the target first and then to the source, and run ALTER SUBSCRIPTION mmdb_sub REFRESH PUBLICATION; after adding tables.

A replication slot that nobody reads keeps WAL on the source until the disk is full. After the switch, or when you abandon an attempt, drop the subscription and check pg_replication_slots on the source. max_slot_wal_keep_size limits how much WAL a slot may hold back, at the price of a broken subscription when the limit is reached.

Sequence synchronisation in PostgreSQL 19 is not continuous: REFRESH SEQUENCES copies the values at the moment you run it, needs a publisher on version 19 or later and the same sequence definitions on both sides. With an older source, the setval query above does the same job.

For very large databases, pg_createsubscriber (PostgreSQL 17 and later) turns a physical standby into a logical subscriber and so avoids the initial copy. It needs the same major version on both sides; the version upgrade then happens on that subscriber with pg_upgrade before the switch. Check the documentation of both tools for that sequence.

The free scan reads the replica identity of every table, the large objects, the unlogged tables and wal_level, and lists what makes logical replication harder in your database. The full report gives this runbook filled in for your database, including the ALTER TABLE statements for the tables concerned.

Blue/green deployments on Amazon RDS and Aurora

A blue/green deployment creates a copy of the production instance or cluster (green) and keeps it in sync with production (blue). You upgrade or change green, test it and switch over: RDS stops writes on both sides, waits until green has caught up, and renames the instances and endpoints so that the application keeps its connection string. For a major version upgrade of RDS for PostgreSQL, and for Aurora PostgreSQL, blue and green are kept in sync with logical replication, so its limits apply. Prerequisites:

  • Parameter group: rds.logical_replication = 1 in the DB parameter group (RDS) or DB cluster parameter group (Aurora), with max_replication_slots, max_wal_senders and max_logical_replication_workers at least the number of databases plus one (postgres and rdsadmin count too) and max_worker_processes higher still, then a reboot. Set the same values in the parameter group for the new version.
  • Primary keys: every table needs one, or REPLICA IDENTITY FULL where no unique key exists.
  • During the deployment: no DDL, no GRANT or REVOKE and no new or changed large objects on blue; AWS then marks replication as degraded and the deployment has to be recreated. Unlogged tables are not replicated, materialized views are not refreshed on green, and extensions such as pg_partman and pglogical must be disabled. Blue may not itself be a publisher or subscriber.
  • Sequences are set by RDS during the switchover; a very large number of sequences makes the switchover slower, which the timeout has to allow for.
  • Disk space on blue: WAL stays on blue until green has applied it. AWS advises room for at least one day of WAL.
Create, switch over and clean up a blue/green deployment
# 0. Parameter group of blue (RDS: DB parameter group, Aurora: DB cluster parameter group), then reboot:
#    rds.logical_replication = 1; max_replication_slots, max_wal_senders, max_logical_replication_workers >= databases + 1
#    count the databases: SELECT count(*) FROM pg_database WHERE datistemplate = false;

# 1. Create the green environment (it replicates from blue)
aws rds create-blue-green-deployment --blue-green-deployment-name <database>-upgrade --source <DB instance or cluster ARN> --target-engine-version <version> --target-db-parameter-group-name <parameter group for the new version>
#    Aurora: add --target-db-cluster-parameter-group-name <cluster parameter group for the new version>
aws rds describe-blue-green-deployments --blue-green-deployment-identifier <bgd id>

# 2. Wait until green is AVAILABLE, test it (read-only), check the lag on blue (0 = caught up)
psql -h <blue endpoint> -U <admin> -d <database> -c "SELECT slot_name, pg_current_wal_lsn() - confirmed_flush_lsn AS lsn_distance FROM pg_replication_slots WHERE slot_type = 'logical';"

# 3. Switchover (timeout in seconds, 30 to 3600; the endpoints keep their names)
aws rds switchover-blue-green-deployment --blue-green-deployment-identifier <bgd id> --switchover-timeout 300

# 4. When the go-live is accepted: delete the deployment, later the old (blue) instances
aws rds delete-blue-green-deployment --blue-green-deployment-identifier <bgd id>

The switchover timeout is 30 to 3,600 seconds (default 300); when it is exceeded, RDS rolls back and nothing changes. AWS states that the switchover typically takes under a minute. Writes stop on both sides during the switchover, and clients that cache DNS for longer than a few seconds keep sending traffic to the old instance.

After the switchover the old environment stays, renamed with -old1, read-only and without replication: it is a fallback for reading, but writes made on the new environment do not reach it. Point-in-time recovery of the new instance starts at the creation of green, so keep the old instance as long as your recovery window requires.

Green is created from a snapshot and loads its blocks lazily, so run ANALYZE and warm up the database before the switchover. With heavy write traffic, the single apply worker may not keep up; AWS then points to AWS DMS.

pgloader: from MySQL or SQL Server to PostgreSQL

pgloader reads a MySQL or SQL Server database, creates the tables, indexes and foreign keys in PostgreSQL, converts the data types with its casting rules and loads the data in one run. It is an offline tool: the source must not change during the load.

Load a MySQL or SQL Server database with pgloader
# MySQL or MariaDB to PostgreSQL
pgloader mysql://<user>:<password>@<source-host>/<database> postgresql://<admin>:<password>@<target-host>/<database>

# SQL Server to PostgreSQL
pgloader mssql://<user>:<password>@<source-host>/<database> postgresql://<admin>:<password>@<target-host>/<database>

# with your own casting rules: a command file (pgloader migrate.load)
LOAD DATABASE
  FROM mysql://<user>:<password>@<source-host>/<database>
  INTO postgresql://<admin>:<password>@<target-host>/<database>
WITH include drop, create tables, create indexes, reset sequences, foreign keys
CAST type datetime to timestamptz drop default drop not null using zero-dates-to-null;

Changing engine is a different job from the moves in this guide. Stored procedures, functions, triggers and views are not converted, and data types such as unsigned integers, zero dates or datetimeoffset need casting rules of your own in a command file before the real run. Plan the conversion and the tests of the application first; the load itself is the smallest part. The guides on moving to PostgreSQL and on rewriting stored procedures go into that.

Collations and glibc: a checklist when the operating system changes

PostgreSQL sorts text with the collation of the operating system's C library (glibc on most Linux systems), unless a column or database uses ICU or, from PostgreSQL 17, the builtin provider. glibc 2.28 changed the sort order of many locales; Debian 10, Ubuntu 18.10 and RHEL 8 and their successors have the new data. A B-tree index built under the old rules is then silently out of order: queries can miss rows, and a unique index can accept duplicates.

  • Affected: every route that takes the data files to another operating system image: pg_upgrade on a new OS, a streaming standby or a pg_basebackup restored on another OS version, or an OS upgrade under an existing data directory.
  • Not affected: pg_dump and pg_restore and logical replication, because the target builds its indexes itself; columns with the C or POSIX collation; indexes that do not sort text, such as those on numbers or bytea.
  • Before the move: compare the glibc version of the old and the new image (ldd --version) and, from PostgreSQL 15 on, the collation version each database has recorded with the version the system provides.
  • After the move: rebuild every index on text columns with a libc collation before the application writes again (REINDEX, or REINDEX … CONCURRENTLY while the table stays available), check range-partitioned tables with a text partition key, then record the new version with ALTER DATABASE … REFRESH COLLATION VERSION.
  • ICU collations have the same problem when the ICU library version changes; ALTER COLLATION … REFRESH VERSION records the new version after the rebuild. The amcheck extension (bt_index_check) can find indexes that are out of order.
Find and rebuild the indexes that depend on the C library's collation
-- PostgreSQL 15 or later: collation version recorded per database and what the operating system provides now
SELECT datname, datcollversion, pg_database_collation_actual_version(oid) AS os_version FROM pg_database;

-- indexes that use a C library (libc) collation: rebuild them after a glibc change
SELECT DISTINCT i.indrelid::regclass AS table_name, i.indexrelid::regclass AS index_name
FROM pg_index i
JOIN pg_collation c ON c.oid = ANY (i.indcollation::oid[])
WHERE c.collprovider IN ('d', 'c') AND c.collname NOT IN ('C', 'POSIX');

-- rebuild (CONCURRENTLY keeps the table available; or REINDEX DATABASE in a maintenance window)
REINDEX INDEX CONCURRENTLY public.customer_name_idx;

-- then record that the database matches the operating system's collation version again
ALTER DATABASE <database> REFRESH COLLATION VERSION;

On managed services the provider controls the operating system image; check its release notes on whether an upgrade brings new collation data. When in doubt, logical replication or a dump and restore avoids the problem altogether.

Checks after every route

A migration is finished when the target has been checked, not when the last command has run. Run the same queries on the source (before the switch) and on the target, and compare the results:

  • Row counts per table, exact with COUNT(*): pg_class.reltuples is only an estimate.
  • Object counts per schema and kind (tables, indexes, sequences, views, functions), and no invalid indexes.
  • Extensions present, at the expected version.
  • Sequences at or above the highest value in their columns.
  • Statistics gathered (ANALYZE or vacuumdb), and a few heavy queries compared in plan and time.
  • Roles, rights and settings: logins work, application users have their rights, and server settings such as timezone, search_path and the memory settings match.
  • The server log of the target, during the restore and the first business day.
Comparison queries (run on source and target)
-- object counts per schema and kind (r table, p partitioned table, i index, S sequence, v view, m materialized view)
SELECT n.nspname, c.relkind, count(*)
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema') AND n.nspname NOT LIKE 'pg_toast%'
GROUP BY 1, 2 ORDER BY 1, 2;

-- functions and procedures per schema
SELECT n.nspname, count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema') GROUP BY 1 ORDER BY 1;

-- extensions and their versions
SELECT extname, extversion FROM pg_extension ORDER BY 1;

-- exact row counts (reads every table; one line per table)
SELECT 'public.customer' AS table_name, COUNT(*) AS row_count FROM public.customer
UNION ALL SELECT 'public.orders', COUNT(*) FROM public.orders
ORDER BY 1;

-- target: invalid indexes (a failed CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY)
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;

-- target: a sequence behind its column (example for one table)
SELECT (SELECT max(id) FROM public.orders) AS max_id, last_value
FROM pg_sequences WHERE schemaname = 'public' AND sequencename = 'orders_id_seq';

Common pitfalls

The errors that come up most often, their cause and the part of this guide with the fix:

SymptomCauseFix
cannot update table … because it does not have a replica identity and publishes updatesA table without a primary key in a publicationPrimary key or replica identity (logical replication)
The disk of the source fills up, pg_wal keeps growingA replication slot that is no longer readDrop the subscription or the slot; max_slot_wal_keep_size
duplicate key value violates unique constraint right after the switchSequences not set on the targetSequence sync at the switch (logical replication)
role … does not exist or must be owner of … during the restoreRoles not created first, or ownership that a managed service does not allowpg_dumpall --roles-only; --no-owner --role= (pg_dump)
extension … is not available or could not access file "$libdir/…"Extension not installed, not allow-listed or not in shared_preload_librariesExtensions on the target first (pg_dump, pg_upgrade)
Slow queries just after the migrationNo planner statistics yetvacuumdb --analyze-in-stages or ANALYZE
pg_upgrade --check reports a checksum or locale mismatchNew cluster created with other settings (checksums are on by default from 18)initdb with the old cluster's settings (pg_upgrade)
Missing rows, or duplicates in a unique index, after a move to a new OS imageChanged glibc collation dataREINDEX of text indexes (collations)
The blue/green deployment shows replication degradedDDL, GRANT or a large-object change on blueDDL freeze; recreate the deployment (blue/green)
The initial copy takes days and the lag keeps growingLarge tables copied a few at a time, a single apply workermax_sync_workers_per_subscription; or pg_createsubscriber (logical replication)

Questions

Is pg_upgrade or pg_dump faster for a major version upgrade?

On the same server, pg_upgrade with --link or --clone is much faster: it takes minutes, because it only rebuilds the system catalogue and reuses the data files. pg_dump and pg_restore copy every row and rebuild every index, so their time grows with the size of the database. A dump is the choice when the server, the operating system or the platform changes as well.

Can I go back after pg_upgrade --link?

Only as long as the new cluster has not been started: then you remove the .old suffix from global/pg_control in the old data directory and start the old cluster. Once the new cluster has run, the way back is the backup taken before the upgrade. Use --clone or the copy mode when you need the old cluster as a fallback.

Does logical replication work between different major versions?

Yes. Native logical replication exists since PostgreSQL 10, and the subscriber may run a newer major version than the publisher, which makes it suitable for upgrades with minimal downtime. Synchronising sequences through the subscription needs a publisher on PostgreSQL 19 or later; with an older source you set them with setval at the switch.

Does every table need a primary key for logical replication?

Every table that gets updates or deletes needs a primary key or another replica identity; without one, the source refuses those updates and deletes once the table is published. Insert-only tables work without. REPLICA IDENTITY FULL is possible as a last resort, but slow on large tables.

Does pg_upgrade keep the planner statistics?

When the new version is PostgreSQL 18 or later, pg_upgrade carries over most optimizer statistics; then run vacuumdb --all --analyze-in-stages --missing-stats-only followed by vacuumdb --all --analyze-only. With an older new version, the cluster starts without statistics and vacuumdb --all --analyze-in-stages is needed straight after the upgrade.

Can I use pg_upgrade to move to Amazon RDS, Azure or Cloud SQL?

No. pg_upgrade needs access to the data files of both clusters on one server, which managed services do not give. To move onto a managed service, use pg_dump and pg_restore, logical replication or the provider's migration service; for a version upgrade on the service, use its own upgrade function or, on RDS and Aurora, a blue/green deployment.

Read next

Run the free read-only scan to see which of these routes fit your database and target, and which tables stand in the way of logical replication. Nothing leaves your browser.

Start the free scan