Migrate to Managed PostgreSQL
Move an existing PostgreSQL database into a Managed PostgreSQL service, with the source online
until the moment you cut over. The built-in migration job copies the data and keeps it in sync;
pg_dump and pg_restore are the alternative when you want to control every step.
A migration always involves a source server outside the control of Exoscale, so migrations are supported on a best-effort basis.
Choose a Method
The built-in migration job has two methods, selected with --pg-migration-method:
| Method | How it works | Source during the migration | Use it for |
|---|---|---|---|
replication | Copies the data, then keeps the target up to date with logical replication until you stop the migration. | Stays online and writable. | Production databases, where you choose the moment to cut over. |
dump | Copies a snapshot of each database once. | Writes made after the copy starts are lost. Stop them first. | Small databases, or when a short write freeze is acceptable. |
With --pg-migration-method replication, every source database must meet the requirements of
logical replication: a database that does not fails, and the whole migration reports failed.
The pre-check tells you, before you start, which method each
database would get. Fix the source until it announces replication.
To control every step yourself, or when the source cannot accept connections from Exoscale, use pg_dump and pg_restore instead.
Steps at a Glance
The pre-check runs on the target, and the source must allow the address of the target, which exists only once the target is created. The order that avoids a failed first attempt is:
- Create the target without migration flags.
- Allow the target to reach the source.
- Prepare the source for logical replication.
- Run the pre-check and fix what it reports, including the workers of the target.
- Start the migration on the target with
exo dbaas update. - Follow the migration until every database reads
syncing, without changing the schema of the source. - Cut over and stop the migration.
Prerequisites
On the target:
- A Managed PostgreSQL service with a major version equal to or higher than the source. A migration from PostgreSQL 15 to 18 works directly.
- Enough disk for the source data, with headroom. You can scale the plan afterwards.
- An empty target, see the caution at the end of Cut Over and Stop the Migration.
- For
replication, enough logical replication workers, see Raise the Replication Workers.
On the source:
- Every extension used by your databases must be available on the target: compare
SELECT extname FROM pg_extension;on the source withSELECT name FROM pg_available_extensions;on the target. The migration creates them on the target. - A user that can read everything you migrate:
CONNECTon each database andSELECTon all tables and sequences, including tables created by other roles. A single unreadable table fails its whole database. Forreplication, this user must be a superuser, or theaiven_extrasextension must be installed in every source database. - The source must accept connections from the target, see Allow the Target to Reach the Source.
Create the Target
exo dbaas create pg PLAN SERVICE_NAME -z ZONE --pg-ip-filter CIDRParameters:
PLAN: plan of the target service, for examplestartup-4.SERVICE_NAME: name of the target service, for examplemy-postgresql.ZONE: zone of the target service, for examplech-gva-2. Pass-zon every command of this page; without it, the CLI uses the default zone of your account.CIDR: the networks of the clients that will use the target, for example203.0.113.0/24.
--pg-ip-filter controls who can connect to the target. It is not used by the migration and
does not need to include the source.
Raise the Replication Workers
For replication, the target needs max_logical_replication_workers set to at least twice the
number of source databases, and max_worker_processes set higher than that value. Both are 4
and 8 by default, which is enough for two databases, defaultdb included.
To migrate four databases, for example:
exo dbaas update SERVICE_NAME -z ZONE -f --pg-settings='{"max_logical_replication_workers":8,"max_worker_processes":9}'This restarts the target, so do it before you start the migration.
Allow the Target to Reach the Source
The migration is an outgoing connection from the target service to the source. It comes from the public IP address of the target, the address its hostname resolves to:
dig +short "$(exo dbaas show SERVICE_NAME -z ZONE -O json | jq -r .pg.uri_params.host)"Allow this address, and only this address, in every firewall, security group and pg_hba.conf
rule between the target and the source, for the duration of the migration.
If the source uses pg_hba.conf, add a rule for the migration user and the address of the
target, and reload the configuration:
# TYPE DATABASE USER ADDRESS METHOD
host all MIGRATION_USER TARGET_IP/32 scram-sha-256If the source is another Exoscale Database Service, add the address of the target to the IP filter of the source, as described in Restrict Connections to a Service.
Prepare the Source
For the replication method, check these settings on the source:
| Setting | Check with | Required value | Notes |
|---|---|---|---|
wal_level | SHOW wal_level; | logical | Needs a restart. Managed PostgreSQL sources already use logical. |
max_replication_slots | SHOW max_replication_slots; | At least three free slots per database to migrate | The migration keeps one logical slot per database, and uses up to two more per database during the initial copy. Needs a restart. |
listen_addresses | SHOW listen_addresses; | An address reachable from the internet, or * | Needs a restart. |
On a self-managed server, change them as a superuser with ALTER SYSTEM SET, then restart
PostgreSQL. On Amazon
RDS and Aurora, set rds.logical_replication to 1 in the parameter group of the instance or
cluster; on Google Cloud SQL, set the cloudsql.logical_decoding flag to on. Follow the
documentation of your provider to apply the change.
Check the Source Before You Start
The API runs the migration pre-checks on the target without starting anything. Pass the source as a URI with the credentials of the migration user:
echo '{"source-service-uri":"postgres://SOURCE_USERNAME:SOURCE_PASSWORD@SOURCE_HOST:SOURCE_PORT/SOURCE_DATABASE?sslmode=require"}' | \
exo api create-dbaas-task-migration-check SERVICE_NAME -z ZONEParameters:
SERVICE_NAME: the Managed PostgreSQL service that will receive the data.ZONE: zone of that service.SOURCE_USERNAME,SOURCE_PASSWORD: credentials of the migration user. URL-encode the password if it contains special characters.SOURCE_HOST,SOURCE_PORT: address and port of the source server.SOURCE_DATABASE: a database on the source used for the initial connection.
The response contains a task ID under reference.id. Read the result a few seconds later:
exo api get-dbaas-task SERVICE_NAME TASK_ID -z ZONEParameters:
TASK_ID: thereference.idreturned by the previous command.
A source ready for replication returns:
"result": "Migration method will be 'replication'.",
"result-codes": [],
"success": true,Otherwise, result names the method the migration would use and lists what is missing, database
by database, for example:
"result": "Migration method will be 'dump', missing requirements for logical replication are:
- User cannot manage replication slots in database 'defaultdb': use superuser or install aiven_extras",success: true means the check ran; success: false means it could not run, for example when the
source does not accept connections from the target. The requirement on the workers of the target
only appears once every source database passes. Fix what is reported and run the check again
until result announces replication.
Start the Migration
On the target created above:
exo dbaas update SERVICE_NAME -z ZONE -f \
--pg-migration-host SOURCE_HOST \
--pg-migration-port SOURCE_PORT \
--pg-migration-username SOURCE_USERNAME \
--pg-migration-password SOURCE_PASSWORD \
--pg-migration-dbname SOURCE_DATABASE \
--pg-migration-method replication \
--pg-migration-ssl=trueParameters:
SOURCE_HOST,SOURCE_PORT,SOURCE_USERNAME,SOURCE_PASSWORD,SOURCE_DATABASE: as in the pre-check.
Other migration flags:
--pg-migration-ssl=trueconnects to the source over TLS. Keep it unless the source has no TLS.--pg-migration-ignore-dbstakes a comma-separated list of source databases to skip.
The same --pg-migration-* flags exist on exo dbaas create pg, to create the target and start
the migration in one command. A new service only gets its address when it is created, so the
source cannot allow it in advance: if that first attempt fails with connection timeout expired,
allow the address, then restart the migration.
Follow the Migration
exo dbaas migration status SERVICE_NAME -z ZONEThe same information as JSON, easier to poll from a script:
exo api get-dbaas-migration-status SERVICE_NAME -z ZONEFor a few seconds after the start, both commands report that no migration exists. Then the payload
has an overall status, method and error, and a details array with the dbname, method,
status and error of each database. For example, a replication migration of three databases
that finished its initial copy reads:
{
"details": [
{"dbname": "appdb", "method": "replication", "status": "syncing"},
{"dbname": "defaultdb", "method": "replication", "status": "syncing"},
{"dbname": "reporting", "method": "replication", "status": "syncing"}
],
"method": "replication",
"status": "done"
}The statuses:
running: the initial copy is in progress, anddetailsis still empty. Do not stop the migration in this state.done, on the top level: the initial copy of every database is finished.syncing, per database,replicationmethod only: the copy is finished and logical replication keeps the database up to date. This is the state to cut over from.done, per database,dumpmethod: the copy is finished. The method is reported aspg_dump.failed: read theerrorfield, on the top level and, when present, per database. For the detailed cause, read the logs of the target withexo dbaas logs SERVICE_NAME -z ZONE, and those of the source.
When one database of a replication migration fails, the migration stops replicating every
database, including those still reported as syncing. Treat a top-level failed as a failure of
the whole migration.
Restart a Failed Migration
A failed migration is not restarted by sending the same settings again. Fix the cause, then run
the exo dbaas update command again with at least one migration setting changed, for example
another --pg-migration-dbname.
Avoid Schema Changes During Replication
Warning
Logical replication does not copy schema changes. While a replication migration runs, do not
change the schema on the source. After a table is created on the source, or a column is added to
a source table, replication of that whole database stops at the next write to it, while the
status still reads syncing. Also leave wal_level, the replication slots, the listen address
and the firewall of the source unchanged until the cutover.
If a schema change cannot wait, apply it on the target first, then on the source. For a new table, also refresh the subscription of that database on the target, or the rows of the new table are never copied. Find the subscription of the current database:
SELECT subname FROM pg_subscription
WHERE subdbid = (SELECT oid FROM pg_database WHERE datname = current_database());Then refresh it:
ALTER SUBSCRIPTION SUBSCRIPTION_NAME REFRESH PUBLICATION;Parameters:
SUBSCRIPTION_NAME: the name returned by the previous query.
To detect a stopped replication, run this on each database of the target. A growing
apply_error_count means the changes of that database are no longer applied; a growing
sync_error_count means the initial copy of a table keeps failing:
SELECT s.subname, st.apply_error_count, st.sync_error_count
FROM pg_subscription s
JOIN pg_stat_subscription_stats st ON st.subid = s.oid
WHERE s.subdbid = (SELECT oid FROM pg_database WHERE datname = current_database());Cut Over and Stop the Migration
Stop the migration only from a safe state: every database done for the dump method, or every
database syncing for the replication method, with no error counts growing. Stopping during the
initial copy can leave the target incomplete.
Stop writes on the source, for example by putting the application in maintenance mode.
Check that every database in
detailsis stillsyncing, ordonefor a dump, without error.Stop the migration. This removes the replication objects it created, the subscriptions on the target and the publications and replication slots on the source:
exo dbaas migration stop SERVICE_NAME -z ZONEA few seconds after the stop,
exo dbaas migration statusreports that no migration exists.After a
replicationmigration, reset the sequences. Logical replication copies rows, not sequence values, so sequences on the target are still at their start value and the firstINSERTfails withduplicate key value violates unique constraint. Inpsql, connected to each migrated database on the target, generate and run onesetvalper sequence owned by a column:SELECT format('SELECT setval(%L, COALESCE((SELECT max(%I) FROM %I.%I), 0) + 1, false);', s.seqrelid::regclass, a.attname, n.nspname, c.relname) FROM pg_sequence s JOIN pg_depend d ON d.objid = s.seqrelid AND d.classid = 'pg_class'::regclass AND d.deptype IN ('a', 'i') JOIN pg_class c ON c.oid = d.refobjid JOIN pg_namespace n ON n.oid = c.relnamespace JOIN pg_attribute a ON a.attrelid = d.refobjid AND a.attnum = d.refobjsubid \gexecThis covers
serial,bigserialand identity columns. A sequence used only throughnextval()in application code needs its ownsetval(), with the value read on the source. Adumpmigration copies sequence values, so this step is not needed.Refresh the planner statistics in each migrated database:
ANALYZE;The warnings about system catalogs, such as
permission denied to analyze "pg_authid", are expected.Set up the roles of your application. The migration creates the roles of the source on the target, with their grants on the migrated tables, but not their passwords, and the migrated objects are owned by
avnadmin. Set a password for each login role withALTER ROLE ROLE_NAME PASSWORD 'NEW_PASSWORD';, and change the owner of the objects your application must own. The administrative user of the target isavnadmin, with a password generated by Exoscale.Read the connection URI of the target and point your application to it:
exo dbaas show SERVICE_NAME -z ZONE --uriOn the source, check that no replication slot is left behind:
SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal FROM pg_replication_slots;The migration slots are named
aiven_db_migrate_<hash>_slot, and temporary onespg_<number>_sync_<number>_<number>. A slot left behind keeps WAL on the source until its disk fills up. Drop a leftover one withSELECT pg_drop_replication_slot('SLOT_NAME');. If the source is an Exoscale service, leave itspghoard_localslot alone.Remove the temporary firewall and
pg_hba.confrules from the source.
Caution
Do not start a migration, with either method, into a target that already holds the data, for
example to retry after a completed one. Tables without a primary key get their rows a second
time, and with replication the tables with a primary key never finish their initial copy and
stop receiving changes, while the status still reads syncing. Delete the target, or drop its
migrated databases, before you start again.
Migrate with pg_dump and pg_restore
The standard PostgreSQL client tools copy a snapshot of one database. Stop writes on the source first, or run the procedure once as a rehearsal to measure how long it takes. Use client tools at least as recent as the target version.
Create the database on the target first, for example with CREATE DATABASE appdb; as avnadmin.
Then export the source database into a local directory:
pg_dump -d "SOURCE_URI" --format directory --jobs JOBS -f DUMP_DIRImport it into the target:
pg_restore -d "TARGET_URI" --no-owner --no-acl --jobs JOBS DUMP_DIRParameters:
SOURCE_URI: connection URI of the source database.TARGET_URI: connection URI of the target database. Start fromexo dbaas show SERVICE_NAME -z ZONE --uriand replacedefaultdbwith the database you created.JOBS: number of tables exported or imported in parallel, for example4. A parallel export needs--format directory.DUMP_DIR: a local directory that does not exist yet.
--no-owner and --no-acl skip the ownership and permission statements of the dump, which fail
on the target even for roles that exist there. Set ownership and grants for your application roles
afterwards.
Then run ANALYZE; on the target, as in step 5 above.
If an import trips over foreign keys or triggers, see Disable Constraints During a Bulk Load.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
With your current source and target settings, you can only migrate 2 databases at a time | The target has too few logical replication workers for the number of source databases. | Raise the replication workers. |
The migration stays in running for a few minutes, then fails with connection timeout expired | The source does not accept connections from the address of the target, for example an Exoscale source whose IP filter does not include it. | Allow the target, then restart the migration. |
The pre-check returns success: false | The check could not run, for example because the source does not accept connections from the target. | Allow the target and run the check again. |
The pre-check reports User cannot manage replication slots in database '...' | The migration user is not a superuser, and aiven_extras is not installed in that database. | Use a superuser, or install aiven_extras in every source database. |
A database reads failed, although its data was copied | --pg-migration-method was left out and the database did not meet the requirements of logical replication, so it was copied with dump instead. | Run the pre-check and fix the source until it announces replication. |
Sending the same exo dbaas update again does not restart the migration | A failed migration only restarts when a migration setting changes. | Change at least one setting, see Restart a Failed Migration. |
The status reads syncing, but changes on the source no longer reach the target | A schema change on the source stopped the replication of that database. | See Avoid Schema Changes During Replication. |
sync_error_count grows, and the copy fails with role "avnadmin" cannot SET ROLE to "postgres" | With PostGIS, the initial copy of the spatial_ref_sys table fails repeatedly. The extension creates the same table on the target, so the data is not affected. | Nothing to fix: stopping the migration removes the leftover slot. Copy any custom spatial reference systems yourself. |
The first INSERT after the cutover fails with duplicate key value violates unique constraint | Logical replication does not copy sequence values. | Reset the sequences, step 4 of Cut Over and Stop the Migration. |
pg_restore reports must be able to SET ROLE "postgres" or permission denied for schema public | The ownership and permission statements of the dump fail on the target. The data is imported either way. | Pass --no-owner and --no-acl, then set ownership and grants yourself. |