How-To Guides

Mastering PostgreSQL Database Migration: A Practical Guide for Developers

Migrating a PostgreSQL database is rarely just about moving data; it’s about maintaining zero downtime, ensuring data integrity, and adapting to new infrastructure without breaking your application stack. Whether you are moving from self-hosted on-premises servers to AWS RDS, upgrading major versions, or switching from a legacy system to a modern cloud provider, the approach you take depends heavily on your tolerance for downtime and the size of your data.

Assess Your Migration Strategy

Before writing a single command, you must decide on your method. The three most common strategies are:

  • Dump and Restore (pg_dump): Best for small-to-medium databases (< 100GB) where short downtime is acceptable.
  • Logical Replication: Ideal for zero-downtime migrations to a newer version of PostgreSQL or a different host.
  • Physical Copy (rsync/backup): Fastest for large datasets but requires identical OS environments and version compatibility.

For this guide, we will focus on the most versatile method: Logical Replication for seamless, low-downtime migrations, followed by the classic pg_dump for simpler scenarios.

Method 1: Zero-Downtime Migration via Logical Replication

Logical replication allows the target database to stay in sync with the source in real-time. Once the lag reaches zero, you can switch your application over to the new database with minimal disruption.

Step 1: Prepare the Source Database

Ensure your source database supports logical replication by setting the following in postgresql.conf or via ALTER SYSTEM:


ALTER SYSTEM SET wal_level = 'logical';
ALTER SYSTEM SET max_replication_slots = 4;
ALTER SYSTEM SET max_wal_senders = 4;

Restart PostgreSQL for these changes to take effect. Then, create a publication that includes all your tables:


CREATE REPLICA IDENTITY DEFAULT;
CREATE PUBLICATION migration_pub FOR ALL TABLES;

Step 2: Set Up the Target Database

On your new PostgreSQL instance (e.g., AWS RDS), create a subscription pointing to the source:


CREATE SUBSCRIPTION migration_sub
CONNECTION 'host=source-ip port=5432 user=replicator password=secret dbname=mydb'
PUBLICATION 'migration_pub';

Step 3: Validate and Switch

Monitor the replication lag using:


SELECT * FROM pg_stat_subscription;

Once latest_end_lsn matches the source’s current WAL position, pause writes on the source, wait for the final sync, and update your application’s connection string to point to the new database.

Method 2: The Classic pg_dump Approach

For smaller databases or when version differences prevent logical replication, pg_dump is your reliable friend. Use custom format (-Fc) for faster parallel restores.

Export:


pg_dump -Fc -h source-host -U username -d mydb -f mydb_backup.dump

Import:


pg_restore -d new_db -p 5432 -U new_user -j 4 mydb_backup.dump

The -j 4 flag enables parallel restore using 4 jobs, significantly speeding up the process on multi-core machines. Remember to stop your application before running the dump to ensure consistency.

Post-Migration Checklist

  1. Verify Data Counts: Compare row counts in critical tables between source and target.
  2. Check Constraints: Ensure foreign keys and indexes were restored correctly.
  3. Update DNS/Configs: Point your app to the new endpoint.
  4. Monitor Performance: Watch for slow queries or connection spikes after the switch.
  5. Keep Source Read-Only: Do not delete the old database immediately. Keep it available for rollback for at least 48 hours.

Conclusion

Migrating a PostgreSQL database is a critical operation that demands precision. By choosing the right strategy—logical replication for zero downtime or pg_dump for simplicity—and following a rigorous validation process, you can minimize risk and ensure a smooth transition. Always test your migration plan in a staging environment that mirrors production traffic before going live.

Share: