Skip to content
All posts

Moving a live Postgres twice: to a new cluster, then to a new name

, 20 min read

Tags:postgres, cloudnativepg, kubernetes, migration

This autumn I moved a production Postgres twice in two weeks. The first move took it from a managed Kubernetes cluster (Oracle's OKE) to a Talos cluster I run myself. The second, inside that new cluster, was a rename. A day after that, one of the databases inside it got renamed too.

Neither move used a dump and restore for the main data. Both used the same CloudNativePG feature: a replica cluster that streams from the primary, then a switchover where the old primary hands the new one a token. This post goes through both, with the commands as they were run, what the rehearsal measured, and what went wrong anyway.

What was being moved

  • One CloudNativePG (CNPG) Cluster, app-db: three instances, Postgres 17, PgBouncer in front in transaction mode.
  • An API and a few smaller services write to it all day, and the API gives every database call a deadline of a few seconds.
  • Backups go through the Barman Cloud plugin to object storage, one prefix per lineage (app-db-v3, app-db-v4, ...).

That deadline settles the first question. Moving a primary between clusters means some window where nothing accepts writes, and anything longer than the deadline is an error the API returns. Zero errors would have meant building a proxy layer the apps could fail over through, plus retries in the API. I chose a short burst of errors instead: seconds, measured in advance, with nobody paged for it.

The apps never dial the database directly. They dial two ExternalName Services in the database namespace:

# app-db-active     -> PgBouncer (runtime traffic)
# app-db-active-rw  -> the primary (migrations, jobs that need a session)
apiVersion: v1
kind: Service
metadata:
  name: app-db-active
spec:
  type: ExternalName
  externalName: app-db-pooler-rw.app-db.svc.cluster.local
  ports:
    - name: postgres
      port: 5432

An ExternalName is only a DNS CNAME, so repointing it is one kubectl patch. It reaches a client only when the client next connects, which matters later.

The pattern: a distributed topology

CloudNativePG (1.30 here) can join two Cluster objects into one database, a "distributed topology" (CNPG docs, Replica clusters). Each side gets the same replica stanza:

replica:
  self: app-db-oke       # this side
  primary: app-db-oke    # who is primary right now
  source: app-db-talos   # where to stream from when not primary

When primary equals self, the cluster is an ordinary primary. Otherwise it is a replica cluster: its "designated primary" streams from source and archives what it receives to its own lineage in the bucket.

The switch goes like this:

  1. Set primary to the other side on the current primary. It does a fast shutdown, archives its last WAL segment as .partial, restarts as a replica, and publishes status.demotionToken.
  2. Copy that token into replica.promotionToken on the other side, in the same write that sets primary to itself.
  3. The other side waits until it has replayed exactly up to the LSN in the token, then promotes.

The token is the safety catch. It carries the system identifier, timeline and checkpoint LSN from pg_controldata, so it is not a secret. CNPG accepts it only when its LSN equals the promoting side's replay LSN. A stale token is refused, never applied early, so the old primary can never have written anything the new one does not hold. If you promote without a token, CNPG does a failover instead, and the old side has to be rebuilt from scratch.

Why physical replication and not a dump? Both sides run the same Postgres major. Roles, extensions, sequences and every database move together. The copy stays current until the moment of the switch, and the same exchange run backwards is the rollback.

Move 1: OKE to Talos

Rehearsal first

Before touching production I built the whole exchange on the new cluster with throwaway data:

  • Two CNPG clusters named pg in namespaces pg-rehearsal-a (playing OKE) and pg-rehearsal-b (playing the new cluster), three instances each.
  • ExternalName Services standing in for the network path between them.
  • A small Go probe that wrote a row every 100 ms through two pgx pools shaped like the API's: one through PgBouncer, one straight to the primary.

Every step printed a UTC time, so the probe's log lined up with the commands.

The first thing to prove was that adding the replica stanza to a running primary does nothing. On production that stanza goes onto OKE's live primary, and if it rolled the instances, that would be an unplanned switchover. So I took a snapshot of pod UIDs, restart counts, postmaster start time and timeline, applied the stanza, waited five minutes and compared:

snap() {  # <namespace> <cluster> <context>
  kubectl get pods -n "$1" --context "$3" -l cnpg.io/podRole=instance -o jsonpath=\
'{range .items[*]}{.metadata.name} {.metadata.uid} {range .status.containerStatuses[*]}{.name}={.restartCount} {end}{"\n"}{end}'
  kubectl cnpg psql "$2" -n "$1" --context "$3" -- -Atc \
    "select pg_postmaster_start_time(), timeline_id from pg_control_checkpoint()"
  kubectl get cluster "$2" -n "$1" --context "$3" -o jsonpath='{.status.phase}{"\n"}'
}
snap pg-rehearsal-a pg new > /tmp/noop-before.txt
kubectl apply -k rehearsal/a-distributed --context new
sleep 300
snap pg-rehearsal-a pg new > /tmp/noop-after.txt
diff /tmp/noop-before.txt /tmp/noop-after.txt && echo NO-OP

It printed NO-OP. The same snap later ran against production before and after the real stanza went in, with the same result.

Then the switch itself, as one block:

OLD=$(kubectl get cluster pg -n pg-rehearsal-a --context new -o jsonpath='{.status.demotionToken}')
# demote a, writes start failing here
kubectl patch cluster pg -n pg-rehearsal-a --context new --type merge --field-manager cutover \
  -p '{"spec":{"replica":{"primary":"pg-b"}}}'
# wait for a new token
until TOKEN=$(kubectl get cluster pg -n pg-rehearsal-a --context new -o jsonpath='{.status.demotionToken}') \
  && [ -n "$TOKEN" ] && [ "$TOKEN" != "$OLD" ]; do sleep 0.5; done
# promote b with it (same write as primary)
kubectl patch cluster pg -n pg-rehearsal-b --context new --type merge --field-manager cutover \
  -p "{\"spec\":{\"replica\":{\"primary\":\"pg-b\",\"promotionToken\":\"$TOKEN\"}}}"
# repoint
kubectl patch svc pg-active -n pg-rehearsal-b --context new --type merge \
  -p '{"spec":{"externalName":"pg-pooler-rw.pg-rehearsal-b.svc.cluster.local"}}'
kubectl patch svc pg-active-rw -n pg-rehearsal-b --context new --type merge \
  -p '{"spec":{"externalName":"pg-rw.pg-rehearsal-b.svc.cluster.local"}}'
# wait until b takes writes
until kubectl cnpg psql pg -n pg-rehearsal-b --context new -- -Atc 'select not pg_is_in_recovery()' \
  2>/dev/null | grep -qx t; do sleep 0.5; done

I ran it a to b, b to a and a to b again, and measured from the probe and from the rows it wrote:

StepResult
a up, first base backupReady in 2 min, backup in 11 s
b bootstrapped from a's lineage72 s to streaming, 3 ms lag
demote to token3.5 to 5 s
token to promoted6 to 8 s
failed writes per switch9.7 to 12.4 s on both paths
longest gap between committed rows9.8 to 11.7 s
second gap, about 30 s laterabout 15 s

Two things in that table needed work before production.

Stale sockets

Repointing a CNAME moves new connections only. An open connection from the pool still goes to the old side's PgBouncer, which now fronts a read-only replica. pgx does not drop a connection for an SQL error, so the pool kept failing with errors like these until something cut the socket:

25006 cannot execute INSERT in a read-only transaction
57P03 the database system is shutting down
08P01 server conn crashed?
57P01 terminating connection due to administrator command

The fix is to cut them on purpose, right after the repoint. Deleting the old PgBouncer pods closes their client sockets with a FIN. pgxpool then finds them dead at the next acquire and redials through the new CNAME. Any session still open on the old primary gets terminated:

kubectl delete pod -n pg-rehearsal-a --context new -l cnpg.io/poolerName=pg-pooler-rw --wait=false
kubectl cnpg psql pg -n pg-rehearsal-a --context new -- -c \
  "select pg_terminate_backend(pid) from pg_stat_activity where usename = 'probe'"

With the cut issued right after the repoint, both paths were back within 1.5 s of every promotion.

The second gap

About 30 seconds after every promotion, writes failed again for about 15 seconds. The cause is archive_mode. A designated primary runs archive_mode = always, because it archives the WAL it receives. A normal primary runs on. The setting changes only with a restart. A demotion restarts Postgres anyway, so the demoted side picks up the change silently. A promotion does not, so the new primary reports pending_restart. The operator then restarts the replicas one at a time and finally switches over to one of them, to restart the old primary:

The primary needs to be restarted, we'll trigger a switchover to do that

I tried primaryUpdateMethod: restart to avoid the switchover, and it was worse. The instance manager tries a smart shutdown first, which waits up to 180 s for open sessions while refusing every new connection, then shuts down fast anyway: 3 minutes of refused connections, then 12 s. So switchover stayed. The production plan expected both gaps, and the switchover script waits until the new side reports this before it calls the move settled:

kubectl cnpg psql app-db -n app-db --context new -- -Atc \
  "select current_setting('archive_mode'), count(*) filter (where pending_restart) from pg_settings"
# on|0 means settled

The rehearsal also showed why three instances matter. With two, and dataDurability: required, the replica restart after a promotion blocks every commit until the replica rejoins.

The network path, and a Cilium surprise

OKE and the new cluster share no private network. Tailscale connects them. On OKE, a LoadBalancer Service of class tailscale exposes the primary and PgBouncer as tailnet devices:

apiVersion: v1
kind: Service
metadata:
  name: app-db-oke-rw-ts
  annotations:
    tailscale.com/hostname: app-db-oke-rw
    tailscale.com/tags: "tag:old-cluster"
spec:
  type: LoadBalancer
  loadBalancerClass: tailscale
  selector:
    cnpg.io/cluster: app-db
    cnpg.io/instanceRole: primary
  ports:
    - name: postgres
      port: 5432
      targetPort: 5432

On the new cluster, an egress Service makes that device reachable under a cluster-local name, which the server certificate also carries:

apiVersion: v1
kind: Service
metadata:
  name: app-db-oke-rw
  annotations:
    tailscale.com/tailnet-fqdn: app-db-oke-rw.<tailnet>.ts.net
spec:
  type: ExternalName
  externalName: placeholder   # the Tailscale operator rewrites this
  ports:
    - name: postgres
      port: 5432

For a rollback, OKE has to stream from the new cluster, so the same pair also exists in reverse. That is where the rehearsal failed. The new cluster is Talos with Cilium replacing kube-proxy. A Tailscale ingress proxy there answered tailscale ping, but TCP to port 5432 timed out with nothing logged anywhere. cilium-dbg monitor -v on the proxy's node showed the forwarded SYN leaving for the ClusterIP untranslated. It was classed as world, masqueraded to the node IP and sent out into the cloud network. This is tailscale/tailscale#11552. With socket load balancing on in pod namespaces, Cilium translates a ClusterIP when a socket connects to it. The proxy DNATs packets it forwards inside its own network namespace, so they never pass that point and nothing translates them. OKE had the same Cilium settings but still ran kube-proxy beside it, and its iptables rules most likely covered the gap.

The fix is one Helm value, so socket LB applies to the host namespace only and the datapath handles pod traffic:

# Cilium Helm values
socketLB:
  hostNamespaceOnly: true
helm upgrade cilium . -n kube-system --kube-context new
kubectl -n kube-system rollout status ds/cilium --timeout=15m --context new
# want: Socket LB Coverage: Hostns-only
kubectl exec -n kube-system ds/cilium --context new -- cilium-dbg status --verbose | grep 'Socket LB'

After that, the same test passed: nc connected, and openssl s_client -starttls postgres showed the expected server certificate.

Copying identities before the replica exists

Streaming replication between two CNPG clusters needs a few things to match on both sides:

  • The client CA that signs streaming_replica certificates.
  • The streaming_replica certificate itself.
  • The server CA.
  • Every role's password, because the replica is a byte copy and gets the roles from the stream, not from its own Secrets.

So these Secrets were copied from OKE into the new namespace before the new Cluster existed. Once a Cluster is created, its operator mints its own CA if none is there. When one already exists under the default name, it adopts that one and later renews it with the same key, so both sides keep trusting each other.

The copy is a pipe from one cluster to the other, condensed here from the script that did it. Only type, data and the cnpg.io/reload label survive, applied server-side, because a client-side apply would store the whole Secret, data included, in the last-applied-configuration annotation. Nothing is printed. Each key is then compared by sha256, and the script prints only match or MISMATCH:

pipe() {  # copy a secret old -> new, never printed
  kubectl get secret "$1" -n app-db --context old -o json \
    | jq '{apiVersion, kind, type, data, metadata: {name: .metadata.name, namespace: .metadata.namespace,
           labels: ((.metadata.labels // {}) | with_entries(select(.key == "cnpg.io/reload")))}}' \
    | kubectl apply --context new --server-side --force-conflicts --field-manager=db-copy -f - >/dev/null
}
h() {  # sha256 of one key: h <ctx> <secret> <key>
  kubectl get secret "$2" -n app-db --context "$1" -o json | jq -r --arg k "$3" '.data[$k]' | shasum -a 256
}
for s in app-db-server-ca app-db-ca app-db-replication; do pipe "$s"; done
[ "$(h old app-db-ca ca.key)" = "$(h new app-db-ca ca.key)" ] && echo match || echo MISMATCH

The replica cluster on the new side

The new Cluster bootstraps from OKE's newest base backup in the bucket, replays WAL up to the present, and then streams through the bridge:

replica:
  self: app-db-talos
  primary: app-db-oke
  source: app-db-oke
bootstrap:
  recovery:
    source: app-db-oke
    database: app
    owner: app
    secret:
      name: app-db-app   # the piped one, so no new password is minted
externalClusters:
  - name: app-db-oke
    plugin:                   # its WAL archive, for the bootstrap
      name: barman-cloud.cloudnative-pg.io
      parameters:
        barmanObjectName: app-db-backups
        serverName: app-db-v3
    connectionParameters:     # the stream, through the bridge
      host: app-db-oke-rw.app-db.svc
      port: "5432"
      user: streaming_replica
      dbname: postgres
      sslmode: verify-full
      application_name: app-db-talos
    sslCert: { name: app-db-replication, key: tls.crt }
    sslKey: { name: app-db-replication, key: tls.key }
    sslRootCert: { name: app-db-ca-crt, key: ca.crt }

secret: app-db-app deserves a word. Without it, a Cluster bootstrapped by recovery mints a random password for the application owner. Its first promotion would then ALTER ROLE app to that random password, and the app would lock itself out at the worst possible moment.

The new side went from Setting up primary to Cluster in healthy state with three instances in about 6 minutes. OKE then listed it as an async standby:

kubectl cnpg psql app-db -n app-db --context old -- -Atc \
  "select application_name, state, sync_state, replay_lag from pg_stat_replication"
# app-db-talos|streaming|async|00:00:00.19

It is async on purpose. OKE's synchronous standby list names only its own instances, so a slow tailnet never blocks a commit on OKE.

The switch on production

All app traffic had already moved to the new cluster before this point, still writing to OKE's primary through the bridge, and OKE's own app Deployments were at zero. Both ArgoCD Applications for the database were in manual sync. The switch is a set of live kubectl patch calls, and an auto-sync of an older git revision in the middle of it could point both halves at themselves. Then:

OLD=$(kubectl get cluster app-db -n app-db --context old -o jsonpath='{.status.demotionToken}')
kubectl patch cluster app-db -n app-db --context old --type merge --field-manager cutover \
  -p '{"spec":{"replica":{"primary":"app-db-talos"}}}'
until TOKEN=$(kubectl get cluster app-db -n app-db --context old -o jsonpath='{.status.demotionToken}') \
  && [ -n "$TOKEN" ] && [ "$TOKEN" != "$OLD" ]; do sleep 0.5; done
kubectl patch cluster app-db -n app-db --context new --type merge --field-manager cutover \
  -p "{\"spec\":{\"replica\":{\"primary\":\"app-db-talos\",\"promotionToken\":\"$TOKEN\"}}}"
kubectl patch svc app-db-active -n app-db --context new --type merge \
  -p '{"spec":{"externalName":"app-db-pooler-rw.app-db.svc.cluster.local"}}'
kubectl patch svc app-db-active-rw -n app-db --context new --type merge \
  -p '{"spec":{"externalName":"app-db-rw.app-db.svc.cluster.local"}}'
# kill old pgbouncer so pooled clients reconnect
kubectl delete pod -n app-db --context old -l cnpg.io/poolerName=app-db-pooler-rw --wait=false
until kubectl cnpg psql app-db -n app-db --context new -- -Atc 'select not pg_is_in_recovery()' \
  2>/dev/null | grep -qx t; do sleep 0.5; done
kubectl cnpg psql app-db -n app-db --context old -- -c \
  "select pg_terminate_backend(pid) from pg_stat_activity
   where backend_type = 'client backend' and usename not in ('postgres', 'streaming_replica')"

The script that ran this saved the token to a file instead of printing it, so it could go into git without passing through a terminal. The timeline:

+0.0s   last write on OKE
+1s     OKE demoted
+35s    promotion requested with OKE's token
+42.7s  first write on the new cluster

The write gap was 42.7 s, not the 10 to 12 s from the rehearsal. Almost all of the difference was the demotion: OKE took about 34 s to publish its token, against 3.5 to 5 s for the rehearsal clusters. A demotion is a fast shutdown plus archiving the last WAL as .partial to the bucket, and I have not pinned down which of the two took the time on the real cluster. Token to promotion took 7 s, as rehearsed, and the errors stopped as soon as the new primary took writes.

Then git caught up, in two pushes and in this order:

  1. The values files on both sides get the new primary, and the new side gets the token as promotionToken. Then I synced both Applications by hand, and both showed Synced with no diff.
  2. Only after that, a separate push takes the database out of manual sync.

Doing both in one push risks ArgoCD turning auto-sync back on before it has the new revision. A sync of the old values would then tell OKE it is the primary again.

One more failure showed up here. A PostSync hook that applies grants ran on OKE, now a read-only replica, and failed with Job has reached the specified backoff limit. The template now renders that Job only on the side that is the primary.

Rollback, and then no rollback

The rollback is the same exchange in reverse. There is one detail: the new side's token is in its spec, and the webhook rejects a token on a replica cluster, so it has to go in the same write that points primary away:

kubectl patch cluster app-db -n app-db --context new --type merge --field-manager cutover \
  -p '{"spec":{"replica":{"primary":"app-db-oke","promotionToken":null}}}'

The plan was to keep OKE as a streaming replica for a few quiet days. In the end I watched the new primary for about three hours: error rates back to zero, OKE replaying from it as a replica, a fresh base backup on the new lineage, every app Synced and Healthy. Nothing moved, so I decommissioned OKE that afternoon. From that point the only way back was a restore from the bucket.

Move 2: into a cluster with a new name

Two weeks later the cluster got a new name, core-db. CNPG cannot rename a Cluster in place, and a namespace cannot be renamed at all. So the rename was the same pattern again: a new Cluster called core-db in a new namespace, inside the same Kubernetes cluster.

Being in one cluster made it simpler. There was no bridge, and no need to bootstrap from the bucket: the new cluster could take a pg_basebackup straight from the live primary over the cluster network.

replica:
  self: core-db
  primary: app-db-talos     # the old cluster's name in the topology
  source: app-db-talos
bootstrap:
  pg_basebackup:
    source: app-db-talos
    database: app
    owner: app
    secret:
      name: app-db-app
externalClusters:
  - name: app-db-talos
    plugin:
      name: barman-cloud.cloudnative-pg.io
      parameters:
        barmanObjectName: core-db-backups
        serverName: app-db-v4
    connectionParameters:
      host: app-db-rw.app-db.svc
      port: "5432"
      user: streaming_replica
      dbname: postgres
      sslmode: verify-full
      application_name: core-db
    sslCert: { name: core-db-replication, key: tls.crt }
    sslKey: { name: core-db-replication, key: tls.key }
    sslRootCert: { name: core-db-ca-crt, key: ca.crt }

The order was the same as before:

  1. Create the app with cluster.enabled: false.
  2. Copy the CAs and the replication certificate in under the new cluster's default names, core-db-ca and core-db-replication, and compare them by sha256.
  3. Turn the Cluster on.

Because the copies existed before the Cluster did, the operator adopted them instead of minting its own. The pg_basebackup pod ran, and the cluster reached three healthy instances about three and a half minutes later, streaming with 3.7 ms of lag. Adding core-db as the old cluster's peer was checked with snap again: no restart.

One step failed. The first scheduled base backup of the new lineage, taken on the designated primary, stopped with:

Error issuing pg_backup_stop command: canceling statement due to conflict with recovery

A base backup on a hot standby can lose to WAL replay like that. An on-demand backup a minute later went through:

kubectl cnpg backup core-db -n core-db --context new \
  --method plugin --plugin-name barman-cloud.cloudnative-pg.io --backup-name core-db-manual

The switch was a script this time, with a preflight and a rollback built in. The preflight checks:

  • Both Applications are in manual sync and both clusters are healthy with three instances.
  • The stream is up, the new side is in recovery and the old one is not.
  • WAL archiving works on both sides, and the new lineage has at least one completed base backup.
./switchover.sh check    # preflight: OK
./switchover.sh switch   # runs the preflight again, then asks for "yes"

The exchange inside it is the one above with new names. It demotes app-db (with promotionToken: null in the same write), waits for the token and promotes core-db with it. Then it repoints app-db-active(-rw), deletes the old PgBouncer pods and terminates leftover sessions:

+0s   1. demote app-db (writes fail from here)
+4s   2. demotion token published
+4s   3. promote core-db with it
+5s   4. repoint app-db-active, app-db-active-rw
+5s   5. cut the stale sockets: app-db-pooler-rw pods restart
+14s  6. core-db-1 is primary; first write
+15s  7. terminated: 0

That was 14 seconds of failed writes. The archive_mode restart followed a minute later as expected, with core-db-2 becoming primary. After that the apps moved to the new core-db-active(-rw) names, and app-db was deleted the same night:

kubectl delete cluster app-db -n app-db --context new --wait=true \
  && kubectl delete namespace app-db --context new --wait=true

Before that delete, pg_stat_replication on the new primary showed no stream and no slot from the old cluster.

Traps that showed up after the switch

Touching a role Secret breaks PgBouncer logins

Half an hour after the move, PgBouncer started refusing new server logins for three app roles:

server login failed: FATAL password authentication failed for user "api_user"

The passwords had not changed. I had only edited annotations on the role Secrets while moving them under the new cluster's chart. CNPG watches those Secrets, and any new resourceVersion makes it set the role's password again. Setting the same password again produces a new SCRAM salt. PgBouncer had derived its keys from the old salt and kept using them for new server connections, while clients still authenticated fine against PgBouncer itself. Users did not notice, and it cleared at the next real rotation about half an hour later. Restarting the pooler pods clears it at once:

kubectl delete pod -n core-db -l cnpg.io/poolerName=core-db-pooler-rw

The rule now: never touch the metadata of a CNPG role Secret. A real rotation is safe. A label or an annotation is not.

kubernetes-replicator never forgets a source

The apps get their database credentials as copies made by kubernetes-replicator. After the copies were repointed from the old Secrets to the new ones, the replicator (v2.12.4) still kept each copy registered as a dependent of the old source too. Deleting the old namespace would have deleted the old sources, and the replicator would have patched every app's copy to empty. Restarting the replicator before the delete made it forget the old links.

Backup metrics that stop moving

With the Barman Cloud plugin, the in-tree status.lastSuccessfulBackup and the cnpg_collector_*backup* metrics freeze at whatever they last were. Backup alerts built on them would go quiet and stay quiet. The alert rules now match the plugin's own metrics and the ObjectStore timestamps by name, and a weekly job restores the latest backup from an offsite copy, as a check that the backups actually restore.

A database rename, done as a copy

The next day one database inside the cluster got a new name as well, together with its role. Call them codename and product here. The first plan was the obvious one:

ALTER DATABASE codename RENAME TO product;

I dropped it. CNPG manages both the database (a Database resource) and the role (managed.roles), so renaming underneath them races the operator's own reconcile. A rename also leaves nothing to go back to. A copy keeps the old database untouched until the new one has proven itself.

So the new database and role were declared next to the old ones, empty:

apiVersion: postgresql.cnpg.io/v1
kind: Database
metadata:
  name: product-db
spec:
  name: product
  owner: product_user
  cluster:
    name: core-db
  ensure: present
  databaseReclaimPolicy: retain

Then a script ran the cutover:

  1. Scale the app to zero, and check that its role has no sessions left.
  2. Copy inside the primary's container, so nothing leaves the pod. --no-owner --no-acl --role makes every restored object belong to the new role:
kubectl exec "$PRIMARY" -n core-db -c postgres -- bash -c \
  "set -o pipefail; pg_dump -Fc -d codename | pg_restore -d product --no-owner --no-acl --role=product_user --exit-on-error"
  1. Compare exact row counts of every table on both sides. The script builds one count(*) per table, sorts the output, and compares the two by sha256, so no row data is ever printed:
select string_agg(format('select %L, count(*) from public.%I', tablename, tablename),
                  ' union all ' order by tablename)
from pg_tables where schemaname = 'public';
  1. Check that no relation in the new database is owned by anyone but product_user.
  2. Push the renamed Kubernetes app, wait for the new pods, then run smoke checks.
+0s   scale the app to 0
+8s   codename -> product inside core-db-2
      row counts of every table: match
      relations not owned by product_user: 0
+84s  smoke checks: 200

The app was down for about a minute and a half; the copy itself took under 10 seconds. The old database stayed in place for a day, then went with a plain DROP DATABASE codename; once nothing had connected to it. The old role could only be removed after that: CNPG reported could not perform DELETE on role codename_user: owner of database codename until the database was gone.

For a small database, a short stop and a verified copy was the right tool. For the main one, with constant writes, the replica cluster was.

The numbers side by side

RehearsalOKE to Talosapp-db to core-db
Replica bootstrap72 s (from bucket)about 6 min (from bucket, plus WAL replay)about 3.5 min (pg_basebackup)
Demote to token3.5 to 5 s34 s4 s
First write gap9.7 to 12.4 s42.7 s14 s
Second gap (archive_mode restart)about 15 snot seen in the first probesyes, about a minute later

Checklist for the next one

  • Rehearse on the target cluster with a write probe, and record each number before production.
  • Put an ExternalName interface in front of the database long before you need it.
  • Copy CAs, the replication certificate and role passwords before the new Cluster exists, and compare them by hash, never by eye.
  • Prove the replica stanza is a no-op on the running primary.
  • Put both Applications in manual sync. Patch live, and let git catch up in two separate pushes.
  • Cut stale sockets right after the repoint: delete the old pooler pods, then terminate leftover sessions.
  • Expect the archive_mode restart after the promotion, and wait for archive_mode = on with nothing pending before calling it done.
  • Take an on-demand base backup if the first one on a designated primary fails.
  • Afterwards, do not touch role Secret metadata.