Migrating a PostgreSQL Database to Managed Cloud with Less Than 5 Minutes of Downtime
Moving a production PostgreSQL instance from a self-hosted StatefulSet (or a bare-metal VM) to RDS, Cloud SQL or Azure Database is one of those migrations everyone postpones, because the default plan is "pg_dump on Saturday at 2 a.m. and pray". For a 400 GB database that plan means a four-hour outage, a tired on-call engineer, and no realistic rollback.
There is a better option that has been available since PostgreSQL 10: logical replication. You keep the old database serving traffic while the new managed instance catches up in the background, then you flip the connection string during a short, controlled freeze. This article is the concrete runbook: prerequisites, bootstrap, lag control, the cutover itself, and the rollback path.
Context: why the dump-and-restore window kills you
A pg_dump/pg_restore migration has a downtime cost that scales linearly with data volume and index count. Roughly:
- dump: 10–20 minutes per 100 GB with
-Fd -j 4 - transfer to the cloud: bounded by your egress bandwidth
- restore: index rebuild dominates, often 2–3× the dump time
- post-restore
ANALYZE: another 5–20 minutes before the planner behaves
You cannot accept writes during any of that. And if something goes wrong at minute 180, your rollback is "restart the old database" — which is fine, except you just burned the whole maintenance window.
Logical replication inverts the cost model. The expensive part (initial copy + catch-up) happens while the source is live. The only thing left in the maintenance window is: stop writes, wait for the last WAL bytes to be applied, fix sequences, switch the app. That is a 2–5 minute operation, doable at 11 a.m. on a Tuesday.
The budget we are targeting:
| Step | Target |
|---|---|
| Freeze writes (scale down / PgBouncer PAUSE) | 20 s |
| Drain replication lag to 0 | 30–60 s |
| Sync sequences | 10 s |
| Switch DSN + rollout | 60–120 s |
| Smoke tests | 60 s |
Step 0: pre-flight checks
Source prerequisites
Logical replication requires wal_level = logical on the source. On a self-managed instance this is a restart-only parameter — plan it a few days ahead, it is the only mandatory restart of the whole migration.
# On the source (psql as superuser) psql -c "SHOW wal_level;" # must be 'logical' psql -c "SHOW max_replication_slots;" # >= existing slots + 1 psql -c "SHOW max_wal_senders;" # >= existing senders + 1 psql -c "SHOW max_slot_wal_keep_size;" # PG13+: cap WAL retention, e.g. '50GB' For a StatefulSet-managed Postgres, patch the config and do a rolling restart:
apiVersion: v1 kind: ConfigMap metadata: name: postgres-tuning namespace: data data: 99-logical.conf: | wal_level = logical max_replication_slots = 10 max_wal_senders = 10 max_slot_wal_keep_size = 50GB Then validate that every table you intend to replicate has a primary key. Logical replication applies UPDATE/DELETE by replica identity; a table without a PK silently breaks the subscription.
SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog','information_schema') AND c.relreplident = 'd' AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary); Fix each hit with a PK, or ALTER TABLE x REPLICA IDENTITY FULL; (acceptable only for small, low-churn tables — it is expensive).
Target prerequisites
- RDS: set
rds.logical_replication = 1in the parameter group (static, requires reboot) and grantrds_replicationto the migration role. For RDS acting as subscriber you needrds_superuser. - Cloud SQL: enable the
cloudsql.logical_decodingflag andcloudsql.enable_pglogicalif you use pglogical; the migration user needs theREPLICATIONattribute (cloudsqlsuperuser). - Match major versions, or go source ≤ target. Logical replication tolerates a newer subscriber; the reverse is unsupported.
Network path
This trips up most teams: the subscriber connects to the publisher, not the other way around. Your RDS instance must be able to open a TCP session to your source Postgres. In practice that means a VPN/Direct Connect, a public endpoint restricted by security group, or an SSH/stunnel bastion. Validate it before writing a single line of SQL.
# From a pod in the target VPC oc run netcheck --rm -it --image=registry.redhat.io/rhel9/support-tools -- \ bash -c 'timeout 5 bash -c "</dev/tcp/pg-source.internal/5432" && echo OPEN || echo BLOCKED' Step 1: bootstrap the schema
Native logical replication copies data only. Schema, indexes, sequences, extensions and grants are your job. Dump with a client matching the target major version.
PGSSLMODE=require pg_dump \ --schema-only --no-owner --no-privileges \ --exclude-schema='pg_*' \ -h pg-source.internal -U migrator -d appdb \ -f schema.sql # Review it: strip anything the managed service rejects grep -nE 'CREATE EXTENSION|ALTER .* OWNER|tablespace' schema.sql psql "host=appdb.abc123.eu-west-1.rds.amazonaws.com user=migrator dbname=appdb sslmode=verify-full" \ -v ON_ERROR_STOP=1 -f schema.sql Run it as a Job so it is reproducible and auditable:
apiVersion: batch/v1 kind: Job metadata: name: pg-schema-bootstrap namespace: data spec: backoffLimit: 1 template: spec: restartPolicy: Never containers: - name: psql image: quay.io/enterprisedb/postgresql:16 command: ["/bin/bash", "-c"] args: - | set -euo pipefail pg_dump --schema-only --no-owner --no-privileges \ -d "$SOURCE_URL" -f /tmp/schema.sql psql -v ON_ERROR_STOP=1 -d "$TARGET_URL" -f /tmp/schema.sql env: - name: SOURCE_URL valueFrom: { secretKeyRef: { name: pg-migration, key: source-url } } - name: TARGET_URL valueFrom: { secretKeyRef: { name: pg-migration, key: target-url } } securityContext: allowPrivilegeEscalation: false runAsNonRoot: true capabilities: { drop: ["ALL"] } seccompProfile: { type: RuntimeDefault } Performance tip: for databases above ~200 GB, restore the schema without secondary indexes (pg_dump --schema-only then filter CREATE INDEX), let the initial copy run, and create the indexes afterwards with CREATE INDEX CONCURRENTLY. Initial copy into an index-free table is 3–5× faster.
Step 2: start replication
Native logical replication (PostgreSQL 10+)
On the source:
CREATE PUBLICATION mig_pub FOR ALL TABLES; -- or, scoped: CREATE PUBLICATION mig_pub FOR TABLE public.orders, public.customers; On the target (RDS/Cloud SQL):
CREATE SUBSCRIPTION mig_sub CONNECTION 'host=pg-source.internal port=5432 dbname=appdb user=repl password=... sslmode=verify-full' PUBLICATION mig_pub WITH (copy_data = true, create_slot = true, slot_name = 'mig_slot', streaming = on); This creates a replication slot on the source named mig_slot. From that instant, the source retains WAL for the subscriber. That is exactly what guarantees zero data loss — and exactly what fills your source disk if the subscription stalls. Set max_slot_wal_keep_size and alert on retained bytes (next section).
Initial copy progress is visible on the subscriber:
SELECT srsubid, srrelid::regclass AS table, srsubstate -- i=init, d=copying, f=finished, r=ready FROM pg_subscription_rel ORDER BY srsubstate; When to use pglogical instead
pglogical is worth the extra extension when:
- the source runs PostgreSQL 9.4–9.6 (native logical replication does not exist there);
- you need sequence replication (
pglogical.create_replication_set(..., )pluspglogical.synchronize_sequence()), which native logical replication does not provide; - you want row/column filtering and conflict resolution policies on PG < 15.
Both RDS and Cloud SQL ship pglogical. Setup is symmetric: pglogical.create_node() on both sides, pglogical.create_subscription() on the target.
When to use DMS
AWS DMS is the right tool for heterogeneous migrations (Oracle → Postgres) or when the source version is too old for logical decoding. For Postgres → Postgres, DMS CDC adds a moving part, remaps types imperfectly, and still does not handle sequences or DDL. Prefer native replication; keep DMS as the fallback.
Step 3: treat replication lag as an SLO
You cannot cut over blind. Two queries matter.
On the source, how far behind is the subscriber:
SELECT application_name, state, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn)) AS send_lag, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS total_lag, write_lag, flush_lag, replay_lag FROM pg_stat_replication WHERE application_name = 'mig_sub'; SELECT slot_name, active, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal FROM pg_replication_slots; On the target:
SELECT subname, latest_end_lsn, latest_end_time, now() - latest_end_time AS staleness FROM pg_stat_subscription; Wire this into Prometheus with postgres_exporter and a custom query, then alert:
apiVersion: monitoring.coreos.com/v1 kind: PrometheusRule metadata: name: pg-migration-lag namespace: data labels: role: alert-rules spec: groups: - name: pg-migration rules: - alert: PgLogicalReplicationLagHigh expr: pg_replication_lag_bytes{application_name="mig_sub"} > 5.24288e+08 for: 5m labels: { severity: warning } annotations: summary: "Subscriber mig_sub is more than 500 MB behind" - alert: PgReplicationSlotRetainingWal expr: pg_replication_slot_retained_bytes{slot_name="mig_slot"} > 2.0e+10 for: 10m labels: { severity: critical } annotations: summary: "mig_slot retains >20 GB of WAL — source disk at risk" - alert: PgSubscriptionInactive expr: pg_replication_slot_active{slot_name="mig_slot"} == 0 for: 2m labels: { severity: critical } Let the subscription run for at least 24 hours before cutover. You want to see it survive your nightly batch, your VACUUM window, and a deploy.
Step 4: the cutover runbook
1. Freeze writes
The cleanest freeze in Kubernetes/OpenShift is to scale the writers to zero and park the connection pooler:
# Record current replicas for rollback oc get deploy -n app -o jsonpath='{range .items[*]}{.metadata.name}={.spec.replicas}{"\n"}{end}' > replicas.txt oc scale deploy/api deploy/worker deploy/scheduler -n app --replicas=0 oc wait --for=delete pod -l 'app in (api,worker,scheduler)' -n app --timeout=90s Belt and braces on the source — block anything that slipped through:
ALTER DATABASE appdb SET default_transaction_read_only = on; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'appdb' AND pid <> pg_backend_pid() AND usename <> 'repl'; 2. Drain the lag to zero
psql -d "$SOURCE_URL" -At -c " SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) FROM pg_stat_replication WHERE application_name='mig_sub';" Loop until it returns 0. With writes stopped this takes seconds.
3. Synchronise sequences
This is the step people forget, and it produces duplicate-key errors ten minutes after go-live. Generate the setval statements on the source and replay them on the target:
psql -d "$SOURCE_URL" -At -c " SELECT format('SELECT setval(%L, %s, true);', schemaname||'.'||sequencename, COALESCE(last_value, 1)) FROM pg_sequences WHERE schemaname NOT IN ('pg_catalog','information_schema');" \ | psql -v ON_ERROR_STOP=1 -d "$TARGET_URL" 4. Switch the application
Keep the DSN in a Secret so the switch is one oc patch + rollout, not a code change.
apiVersion: external-secrets.io/v1beta1 kind: ExternalSecret metadata: name: app-db namespace: app spec: refreshInterval: 1h secretStoreRef: name: aws-secretsmanager kind: ClusterSecretStore target: name: app-db creationPolicy: Owner data: - secretKey: DATABASE_URL remoteRef: key: prod/appdb/dsn # value updated to the RDS endpoint at cutover # Flip the pointer, then bring the app back oc annotate externalsecret/app-db -n app force-sync="$(date +%s)" --overwrite oc scale deploy/api -n app --replicas=6 oc rollout status deploy/api -n app --timeout=180s 5. Verify, then detach
# Row-count parity on the top tables for t in orders customers invoices; do s=$(psql -At -d "$SOURCE_URL" -c "SELECT count(*) FROM $t") d=$(psql -At -d "$TARGET_URL" -c "SELECT count(*) FROM $t") printf "%-12s source=%-10s target=%-10s %s\n" "$t" "$s" "$d" \ "$([ "$s" = "$d" ] && echo OK || echo MISMATCH)" done psql -d "$TARGET_URL" -c "ANALYZE;" Only after the application is healthy:
-- On the target ALTER SUBSCRIPTION mig_sub DISABLE; -- Later, once rollback is no longer an option: DROP SUBSCRIPTION mig_sub; -- also drops the slot on the source Do not drop the subscription immediately — DROP SUBSCRIPTION removes the replication slot, and with it your cheap rollback.
Step 5: rollback
Two tiers, pick based on risk appetite.
Tier 1 — within the first minutes. The source is still intact and read-only. Revert the DSN, re-enable writes, scale back up:
psql -d "$SOURCE_URL" -c "ALTER DATABASE appdb SET default_transaction_read_only = off;" # restore previous DSN in the secret store, then oc annotate externalsecret/app-db -n app force-sync="$(date +%s)" --overwrite oc rollout restart deploy/api -n app Cost: you lose any writes already committed to the target. Acceptable only in the first minutes, which is why smoke tests must be fast and automated.
Tier 2 — reverse replication. Before re-opening writes, create a publication on the target and a subscription on the source with copy_data = false. Writes then flow back, and rollback becomes lossless for hours. This doubles the setup work and requires the reverse network path, but for a payments or ordering database it is worth it.
-- On the target (new primary) CREATE PUBLICATION back_pub FOR ALL TABLES; -- On the old source CREATE SUBSCRIPTION back_sub CONNECTION 'host=appdb.abc123.eu-west-1.rds.amazonaws.com dbname=appdb user=repl sslmode=verify-full' PUBLICATION back_pub WITH (copy_data = false, slot_name = 'back_slot'); Remember to re-run the sequence sync in the reverse direction if you ever use it.
Security best practices
Dedicated replication role, least privilege. Do not reuse the application user. The source role needs only REPLICATION plus SELECT on replicated tables:
CREATE ROLE repl WITH LOGIN REPLICATION PASSWORD :'pw'; GRANT CONNECT ON DATABASE appdb TO repl; GRANT USAGE ON SCHEMA public TO repl; GRANT SELECT ON ALL TABLES IN SCHEMA public TO repl; Force TLS end to end. Logical replication streams plaintext row data. Use sslmode=verify-full with an explicit sslrootcert, never require (which does not verify the hostname). Set rds.force_ssl=1 / cloudsql requireSsl on the target, and hostssl only in the source pg_hba.conf:
hostssl appdb repl 10.42.0.0/16 scram-sha-256 Never put the DSN in a manifest. Use External Secrets, Vault, or at minimum a sealed secret. The CREATE SUBSCRIPTION connection string containing the password is stored in pg_subscription and visible to superusers — rotate that password right after cutover.
Restrict the network path. The source must only be reachable from the target's NAT egress IPs, and the migration Jobs must only reach the two databases:
apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: allow-migration-egress namespace: data spec: podSelector: matchLabels: { job-name: pg-schema-bootstrap } policyTypes: ["Egress"] egress: - to: - ipBlock: { cidr: 10.42.10.0/24 } # source Postgres - ipBlock: { cidr: 10.43.20.0/24 } # RDS subnet ports: - protocol: TCP port: 5432 - to: - namespaceSelector: matchLabels: { kubernetes.io/metadata.name: openshift-dns } ports: - { protocol: UDP, port: 53 } Harden the pods. The Job above runs runAsNonRoot, drops all capabilities and uses RuntimeDefault seccomp, so it passes the restricted-v2 SCC without exceptions. Never run migration tooling as a cluster-admin service account.
Keep an audit trail. Enable log_replication_commands = on on the source during the migration window, and snapshot the source (EBS snapshot / volume snapshot) immediately before the freeze. Replication is not a backup.
Key takeaways
- Logical replication moves the expensive work out of the maintenance window. The only serialised steps are freeze, drain, sequences, switch — 2 to 5 minutes regardless of database size.
-
wal_level = logicalis your only mandatory restart. Schedule it days ahead and the cutover itself needs no restart at all. - Replication slots are a loaded gun. They guarantee durability and they fill your source disk. Set
max_slot_wal_keep_size, alert on retained WAL, and never leave an inactive slot behind. - Sequences and indexes are not replicated. Script the
setvalsync, and build secondary indexes after the initial copy withCREATE INDEX CONCURRENTLY. - Monitor with
pg_stat_replicationandpg_stat_subscription, not with hope. Cut over only when the byte lag is literally zero. - Keep the subscription disabled, not dropped, for 24–48 hours. Dropping it destroys the slot and your fast rollback. For high-stakes data, invest in reverse replication before re-opening writes.
- pglogical for old sources and sequence replication, DMS for heterogeneous migrations, native logical replication for everything else.
Rehearse the whole runbook against a restored snapshot first. The second time you execute it, five minutes will feel generous.