← Back to SQL, page 24

sql-0473 · Hard senior

How would you upgrade a production PostgreSQL database to a new major version with little downtime?

Two common paths: pg_upgrade with --link, which rewrites catalogs and reuses data files, giving downtime of minutes for most sizes; or logical replication into a new-version server, then a quick switchover, giving downtime of seconds at the cost of more setup and limits (sequences and DDL are not replicated). Rehearse on a copy and have a rollback plan either way.

Full answer

pg_upgrade:

  1. Install the new version alongside the old.
  2. Run pg_upgrade --check, then stop the old server and run pg_upgrade --link.
  3. Start the new server, run vacuumdb --analyze-in-stages to rebuild statistics, which are not carried over in older releases.
  4. Rollback after --link is hard once the new server has started, so take a backup or snapshot first.

Logical replication:

  1. Create the new cluster with the schema.
  2. Publish tables on the old server and subscribe from the new; initial copy then streaming changes.
  3. At cut-over: stop writes, wait for the subscriber to catch up, copy sequence values, point the application at the new server.
  4. The old server remains intact as a fallback.

Either way: test the application against the new version, check extensions are available, and rehearse the steps with timing on a production-sized copy. Described from documentation, not run here.

Key points

  • pg_upgrade --link gives short downtime
  • Logical replication gives near-zero downtime
  • Sequences and DDL need manual handling with logical replication
  • Analyze after upgrading
  • Rehearse and plan rollback

Common mistakes

  • Upgrading in place without a backup
  • Forgetting to copy sequence values at cut-over

Follow-ups

  • What breaks with extensions during upgrades?
  • How would you verify data after switchover?

Tips

  • Compare downtime and rollback for both