---
title: "Migrate to Managed PostgreSQL"
description: "Migrate an existing PostgreSQL database to Exoscale Managed PostgreSQL with the built-in migration job or with pg_dump and pg_restore."
url: https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/migrate-to-managed-postgresql/
product: "PostgreSQL"
section: product
last_updated: 2026-11-12
---
> For AI agents: the documentation index is at https://community.exoscale.com/llms.txt. Every page is available as markdown at `<page URL>index.md` or with `Accept: text/markdown`.

# 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](#check-the-source-before-you-start) 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](#migrate-with-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:

1. [Create the target](#create-the-target) without migration flags.
2. [Allow the target to reach the source](#allow-the-target-to-reach-the-source).
3. [Prepare the source](#prepare-the-source) for logical replication.
4. [Run the pre-check](#check-the-source-before-you-start) and fix what it reports, including the
   workers of the target.
5. [Start the migration](#start-the-migration) on the target with `exo dbaas update`.
6. [Follow the migration](#follow-the-migration) until every database reads `syncing`, without
   [changing the schema](#avoid-schema-changes-during-replication) of the source.
7. [Cut over and stop the migration](#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](https://community.exoscale.com/product/dbaas/how-to/scaling/index.md) the plan afterwards.
- An empty target, see the caution at the end of
  [Cut Over and Stop the Migration](#cut-over-and-stop-the-migration).
- For `replication`, enough logical replication workers, see
  [Raise the Replication Workers](#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 with `SELECT name FROM pg_available_extensions;`
  on the target. The migration creates them on the target.
- A user that can read everything you migrate: `CONNECT` on each database and `SELECT` on all
  tables and sequences, including tables created by other roles. A single unreadable table fails
  its whole database. For `replication`, this user must be a superuser, or the `aiven_extras`
  extension must be installed in every source database.
- The source must accept connections from the target, see
  [Allow the Target to Reach the Source](#allow-the-target-to-reach-the-source).

## Create the Target

```bash
exo dbaas create pg PLAN SERVICE_NAME -z ZONE --pg-ip-filter CIDR
```

Parameters:

- `PLAN`: plan of the target service, for example `startup-4`.
- `SERVICE_NAME`: name of the target service, for example `my-postgresql`.
- `ZONE`: zone of the target service, for example `ch-gva-2`. Pass `-z` on 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 example `203.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:

```bash
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:

```bash
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:

```text
# TYPE  DATABASE  USER            ADDRESS          METHOD
host    all       MIGRATION_USER  TARGET_IP/32     scram-sha-256
```

If 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](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/restrict-connections/index.md).

## 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:

```bash
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 ZONE
```

Parameters:

- `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:

```bash
exo api get-dbaas-task SERVICE_NAME TASK_ID -z ZONE
```

Parameters:

- `TASK_ID`: the `reference.id` returned by the previous command.

A source ready for `replication` returns:

```text
"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:

```text
"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:

```bash
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=true
```

Parameters:

- `SOURCE_HOST`, `SOURCE_PORT`, `SOURCE_USERNAME`, `SOURCE_PASSWORD`, `SOURCE_DATABASE`: as in the
  pre-check.

Other migration flags:

- `--pg-migration-ssl=true` connects to the source over TLS. Keep it unless the source has no TLS.
- `--pg-migration-ignore-dbs` takes 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](#restart-a-failed-migration).

## Follow the Migration

```bash
exo dbaas migration status SERVICE_NAME -z ZONE
```

The same information as JSON, easier to poll from a script:

```bash
exo api get-dbaas-migration-status SERVICE_NAME -z ZONE
```

For 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:

```json
{
  "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, and `details` is 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, `replication` method 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, `dump` method: the copy is finished. The method is reported as `pg_dump`.
- `failed`: read the `error` field, on the top level and, when present, per database. For the
  detailed cause, read the logs of the target with `exo 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:

```sql
SELECT subname FROM pg_subscription
WHERE subdbid = (SELECT oid FROM pg_database WHERE datname = current_database());
```

Then refresh it:

```sql
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:

```sql
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.

1. Stop writes on the source, for example by putting the application in maintenance mode.
2. Check that every database in `details` is still `syncing`, or `done` for a dump, without error.
3. Stop the migration. This removes the replication objects it created, the subscriptions on the
   target and the publications and replication slots on the source:

   ```bash
   exo dbaas migration stop SERVICE_NAME -z ZONE
   ```

   A few seconds after the stop, `exo dbaas migration status` reports that no migration exists.

4. After a `replication` migration, reset the sequences. Logical replication copies rows, not
   sequence values, so sequences on the target are still at their start value and the first
   `INSERT` fails with `duplicate key value violates unique constraint`. In `psql`, connected to
   each migrated database on the target, generate and run one `setval` per sequence owned by a
   column:

   ```sql
   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
   \gexec
   ```

   This covers `serial`, `bigserial` and identity columns. A sequence used only through `nextval()`
   in application code needs its own `setval()`, with the value read on the source. A `dump`
   migration copies sequence values, so this step is not needed.

5. Refresh the planner statistics in each migrated database:

   ```sql
   ANALYZE;
   ```

   The warnings about system catalogs, such as `permission denied to analyze "pg_authid"`, are
   expected.

6. 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 with
   `ALTER ROLE ROLE_NAME PASSWORD 'NEW_PASSWORD';`, and change the owner of the objects your
   application must own. The administrative user of the target is `avnadmin`, with a password
   generated by Exoscale.

7. Read the connection URI of the target and point your application to it:

   ```bash
   exo dbaas show SERVICE_NAME -z ZONE --uri
   ```

8. On the source, check that no replication slot is left behind:

   ```sql
   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 ones
   `pg_<number>_sync_<number>_<number>`. A slot left behind keeps WAL on the source until its disk
   fills up. Drop a leftover one with `SELECT pg_drop_replication_slot('SLOT_NAME');`. If the
   source is an Exoscale service, leave its `pghoard_local` slot alone.

9. Remove the temporary firewall and `pg_hba.conf` rules 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:

```bash
pg_dump -d "SOURCE_URI" --format directory --jobs JOBS -f DUMP_DIR
```

Import it into the target:

```bash
pg_restore -d "TARGET_URI" --no-owner --no-acl --jobs JOBS DUMP_DIR
```

Parameters:

- `SOURCE_URI`: connection URI of the source database.
- `TARGET_URI`: connection URI of the target database. Start from
  `exo dbaas show SERVICE_NAME -z ZONE --uri` and replace `defaultdb` with the database you created.
- `JOBS`: number of tables exported or imported in parallel, for example `4`. 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](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/disable-constraints/index.md).

## 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](#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](#allow-the-target-to-reach-the-source), then [restart the migration](#restart-a-failed-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](#allow-the-target-to-reach-the-source) 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](#check-the-source-before-you-start) 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](#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](#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](#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. |

## Related Pages

- [Restrict Connections to a Service](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/restrict-connections/index.md)
- [Disable Constraints During a Bulk Load](https://community.exoscale.com/product/dbaas/service-specific/postgresql/how-to/disable-constraints/index.md)
- [Manage Backups and Restores](https://community.exoscale.com/product/dbaas/how-to/backups-restore/index.md)
- [Scale DBaaS Services](https://community.exoscale.com/product/dbaas/how-to/scaling/index.md)
- [pg_dump in the PostgreSQL documentation](https://www.postgresql.org/docs/18/app-pgdump.html) ↗

