Workflow: Backups You Can Restore

Two Kinds of Backup, One Restore

PostgreSQL writes every change twice: first to the write-ahead log (WAL), then to the data files. CloudNativePG keeps a copy of both in an object store - through its Barman Cloud plugin, a sidecar in the database pod that writes to the environment’s ObjectStore (app-postgres-backups):

What it isHow oftenWhat it gives a restore
Base backupa full copy of the database filesdaily (ScheduledBackup), and on demand (Backup)the starting point
WAL archiveevery change since, in 16 MB segmentscontinuously - a segment is archived when it is full, or after archive_timeout (5 minutes) if anything was writtenthe way forward from the starting point, to any moment

A restore takes the newest base backup before the moment you want, and replays the archived WAL up to that moment. That is point-in-time recovery: the nightly backup is the starting line, the archive decides where you stop.

The develop cluster and its backup store

Show cluster.yaml
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: app-postgres
  namespace: develop
  annotations:
    cnpg.io/validation: "disabled"
    # Flux never deletes the database because it left Git (a moved folder, a profile that dropped
    # it, a bad revert): its data would go with it. Deleting it on purpose: remove it from Git first,
    # reconcile, then kubectl delete - while it is in Git, Flux re-creates it, empty (README.md).
    kustomize.toolkit.fluxcd.io/prune: disabled
spec:
  instances: 1
  # Pinned to a minor and its digest: the major tag (:17) moved to every new PostgreSQL minor by
  # itself. Changing this restarts the instance once - with one instance, a short outage.
  # The minimal Debian trixie image: the in-tree barman tools of the old "system" image are not needed
  # with the Barman Cloud plugin (its sidecar brings them).
  # A new MAJOR version here is an offline in-place upgrade: CNPG stops the instance and runs
  # pg_upgrade --link in a job - old and new image on the same distribution. Take a backup first; give
  # the archive a new serverName below in the same change (point-in-time restore does not cross major
  # versions); take a base backup right after (Chapter 12).
  # renovate: datasource=docker depName=ghcr.io/cloudnative-pg/postgresql
  imageName: ghcr.io/cloudnative-pg/postgresql:18.6-minimal-trixie@sha256:37ade18dbdddba430858c72725aceeec66f33fa5333e82ea1df4942f6c1c83a3
  primaryUpdateStrategy: unsupervised
  bootstrap:
    initdb:
      database: app
      owner: app
      secret:
        name: app-postgres-app
  storage:
    size: 10Gi
  # Base backups and the WAL archive go through the Barman Cloud plugin to the ObjectStore
  # app-postgres-backups (object-store.yaml); retention lives there too.
  plugins:
    - name: barman-cloud.cloudnative-pg.io
      isWALArchiver: true
      parameters:
        barmanObjectName: app-postgres-backups
        # One archive per major version AND per cluster: 17's backups and WAL stay under app-postgres
        # and still restore into a 17 cluster; 18 starts its own. BACKUP_CLUSTER_ID is the day and time
        # Terraform created this Kubernetes cluster (ConfigMap backup-s3): a rebuilt cluster starts an
        # empty archive next to the old one - the plugin refuses to archive into a used one ("Expected
        # empty archive") and the database runs without backups. The old archive stays for a restore
        # (Chapter 22); retention prunes only the live cluster's own.
        serverName: app-postgres-pg18-${BACKUP_CLUSTER_ID}
  resources:
    requests:
      cpu: 10m
      memory: 128Mi
    limits:
      cpu: 100m
      memory: 512Mi
  # initdb sets the owner's password only once. managed.roles keeps the app role's password equal to
  # the app-postgres-app Secret on every reconcile, so rotating the Secret (SOPS or Terraform) rotates
  # the database password too. The backend reads POSTGRES_PASSWORD as an env var at start: after a
  # rotation, roll it through Git (safeops.io/secrets-rotated in flux/apps/backend/develop) or new
  # connections fail - not kubectl rollout restart, which Flux undoes (docs/credential-rotation.md).
  managed:
    roles:
      - name: app
        ensure: present
        login: true
        passwordSecret:
          name: app-postgres-app

How Much Can You Lose, How Long Can You Wait

Two numbers decide whether a backup setup is good enough - and they are business decisions, not technical ones:

  • RPO (recovery point objective) - how much data you may lose. With a WAL archive it is about the last unarchived segment: minutes. With nightly backups only, it would be up to a day.
  • RTO (recovery time objective) - how long the service may be without its data. It is the time to decide, restore and prove - and the restore part grows with the database size and the WAL to replay since the base backup.

An RTO is a target; you cannot promise one you have never tested. The lab measures one restore on your cluster - from the apply to a database that is Ready - a small database, a short replay. That is the restore part only: proving the data and switching the application over come on top. A number for this setup, not a guarantee for production. A restore drill on the real size is how the number becomes honest.

Where the Backups Live

  • On kind: MinIO, inside the same cluster (bucket sre), its data in a directory on your machine (infra/terraform/kind_cluster/.minio-data). Enough to practise every step of a restore, and it survives make kind-destroy (Chapter 22 rebuilds the cluster from it) - but not the loss of your machine. Say so whenever someone calls the local setup “backed up”.
  • On the cloud cluster: Cloudflare R2, outside the cluster - a backup bucket of its own, with its own R2 token limited to that bucket - reached over HTTPS. Hetzner writes its etcd snapshots there too.
  • The credentials: Terraform writes the same Secret, cnpg-backup-s3, in each environment - the keys, BUCKET, ENDPOINT and REGION - and a ConfigMap, flux-system/backup-s3, from which Flux fills the endpoint, the bucket and the cluster’s id into the ObjectStore and Cluster manifests. The manifests do not change between kind and the platform; only those values do.
  • Not the state bucket. The Terraform state lives in Cloudflare R2, with the cluster’s kubeconfig and other credentials in it. The backup key has to live inside the cluster, where more people and pods can reach it. Separate buckets, each with its own key limited to it, mean that whoever reads cnpg-backup-s3 cannot read the state - whatever access-policy features a provider offers, this is the simplest way to be sure.
  • Not immutable. Nothing on the platform makes the archive write-once: whoever holds the backup key can also delete backups. Object Lock in compliance mode would close that; versioning alone would not - it keeps deleted objects, but whoever may delete versions can delete those too. A later step, named here so that it is not assumed.

Restore Next to It, Never Over It

A restore is a new cluster, app-postgres-restore, in the same namespace as the one it restores. The original keeps running - it is the evidence, and if the restore is wrong you can try again. The application is switched, or the lost rows copied back, only after the proof.

The platform script prints that cluster:

The restore cluster

Show postgres-restore-manifest.sh
#!/usr/bin/env bash
NAMESPACE=""
TARGET_TIME=""
CONTEXT="${KUBE_CONTEXT:-kind-sre-control-plane}"
SOURCE="app-postgres"
RESTORE="app-postgres-restore"
OBJECT_STORE="app-postgres-backups"

while [ $# -gt 0 ]; do
  case "$1" in
    -n) need_value "$@"; NAMESPACE="$2"; shift 2 ;;
    -c) need_value "$@"; CONTEXT="$2"; shift 2 ;;
    -t) need_value "$@"; TARGET_TIME="$2"; shift 2 ;;
    -h|--help) usage ;;
    *) echo "unknown option: $1" >&2; usage ;;
  esac
done
[ -n "$NAMESPACE" ] || { echo "-n <namespace> is required" >&2; usage; }
if [ -n "$TARGET_TIME" ] && ! [[ "$TARGET_TIME" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(Z|[+-][0-9]{2}:[0-9]{2})$ ]]; then
  echo "-t must be an RFC 3339 time, e.g. 2026-10-05T09:30:00Z (got '$TARGET_TIME')" >&2; exit 2
fi

k() { kubectl --context "$CONTEXT" -n "$NAMESPACE" "$@"; }

source_json=$(k get cluster.postgresql.cnpg.io "$SOURCE" -o json) \
  || { echo "cannot read Cluster $SOURCE in $NAMESPACE ($CONTEXT)" >&2; exit 1; }
image=$(jq -r '.spec.imageName' <<<"$source_json")
server=$(jq -r --arg s "$SOURCE" '[.spec.plugins[]? | select(.name == "barman-cloud.cloudnative-pg.io") | .parameters.serverName // empty][0] // $s' <<<"$source_json")
size=$(jq -r '.spec.storage.size' <<<"$source_json")
resources=$(jq -c '.spec.resources // {}' <<<"$source_json")

target=""
[ -n "$TARGET_TIME" ] && target=$'\n'"      recoveryTarget:"$'\n'"        targetTime: \"$TARGET_TIME\""

cat <<EOF
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: $RESTORE
  namespace: $NAMESPACE
spec:
  instances: 1
  imageName: $image
  storage:
    size: $size
  resources: $resources
  bootstrap:
    recovery:
      source: origin
      database: app
      owner: app
      secret:
        name: app-postgres-app$target
  externalClusters:
    - name: origin
      plugin:
        name: barman-cloud.cloudnative-pg.io
        parameters:
          barmanObjectName: $OBJECT_STORE
          serverName: $server
EOF
  • serverName - the archive the source writes to, read from its plugin parameters: one per PostgreSQL major version, app-postgres-pg18 since the upgrade to 18 (below), followed by the cluster’s id - one archive per cluster, too (Chapter 22). Without it, CloudNativePG looks under the name of the external cluster and finds nothing.
  • recoveryTarget.targetTime (-t) - where the replay stops. Without it, every archived change is replayed - in the story, the DELETE too. A moment the archive does not reach (in the future, or before the oldest base backup) is refused: the restore fails rather than stopping somewhere you did not ask for.
  • The same image, storage and resources as the source - a physical restore needs the same PostgreSQL major version, and the namespace quota (Chapter 08) has to fit a second database.
  • The application’s credentials (app-postgres-app) - the restored database keeps the app’s user and password, so the proof can use them.
  • The fixed name. develop is default-deny (Chapter 06). The network policies give app-postgres and app-postgres-restore - only these two - a path to the backup store, the API server and the operator, and let the backend reach both:

A Postgres policy that allows the restore cluster

Show allow-postgres-egress-apiserver.yaml
# Postgres (CNPG) pods talk to the Kubernetes API server: the CNPG instance manager inside each pod reads
# and updates its Cluster object. The API server is not a pod - its address and port depend on the
# cluster: 6443 on kind and k3s, 443 on most managed clouds (GKE, EKS, AKS, DOKS), a port of the
# provider's own on SKS - so the rule uses an ipBlock for any address on those two ports, plus
# ${api_server_port} from cluster-config where the module reads the real one from the cluster (SKS;
# without it the default 443 repeats the entry above). The residual risk is small: 443 is open to Postgres anyway
# (allow-postgres-egress-https, the backups), and every request to the API server still needs the
# pod's own RBAC. cluster-conformance C3 checks that this rule, not another one, lets it through.
# IPv6 too: an ipBlock covers one family, and on a dual-stack cluster the API server may be reached over IPv6.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: allow-postgres-egress-apiserver
spec:
  # app-postgres-restore: the side-by-side restore cluster (runbook, Chapter 12) needs the same
  # paths as the cluster it restores - or its recovery job hangs on a silently dropped connection.
  podSelector:
    matchExpressions:
      - key: cnpg.io/cluster
        operator: In
        values: [app-postgres, app-postgres-restore]
  policyTypes:
    - Egress
  egress:
    # Every address, written as two halves per family: Cilium (kind, Hetzner) reads exactly 0.0.0.0/0 and
    # ::/0 as "world", which leaves the nodes out - and on kind and k3s the API server runs on a node.
    # Half-ranges are plain CIDRs; with Cilium's policyCIDRMatchMode=nodes they select node addresses too
    # (tested on kind 2026-10-16: /0 blocked, the halves open). The same addresses on every other CNI.
    - to:
        - ipBlock:
            cidr: 0.0.0.0/1
        - ipBlock:
            cidr: 128.0.0.0/1
        - ipBlock:
            cidr: ::/1
        - ipBlock:
            cidr: 8000::/1
      ports:
        - protocol: TCP
          port: 6443
        - protocol: TCP
          port: 443
        - protocol: TCP
          port: ${api_server_port:=443}

Under any other name the recovery pod hangs: the connection is dropped, not refused, so it looks like a slow restore rather than a blocked one. Writing that policy during an incident is exactly the hour the story lost.

The Proof of a Restore

Decided before the restore, checked after it:

  1. The data you expect - a known row from before the damage is there; the damage is not.
  2. With the application’s own user - app, its password from app-postgres-app - not as the postgres superuser, which would succeed even if the app’s role or grants were broken.
  3. Read and write - a SELECT of the expected rows and an INSERT succeed.
  4. The time it took - from the apply to Ready, written down: your measured restore time for this size - the part of the RTO a restore takes.

Ready and pg_isready come before all four - they say the server answers, nothing about the data.

Watching the Backups

A backup that stopped is only found at restore time - unless something watches it. Since this chapter, Prometheus scrapes every app-postgres instance and four alerts follow the Chapter 11 rule - each one asks for an action:

Backup alerts

Show backup-alerts.yaml
        - alert: PostgresBackupFailed
          expr: barman_cloud_cloudnative_pg_io_last_failed_backup_timestamp > barman_cloud_cloudnative_pg_io_last_available_backup_timestamp
          for: 5m
          labels:
            severity: warning
            component: postgres
          annotations:
            summary: "{{ $labels.namespace }}: the newest Postgres base backup failed"
            description: "The last base backup of app-postgres in {{ $labels.namespace }} failed after the last good one. First check: kubectl get backups in {{ $labels.namespace }} - the failed Backup's status.error - then take a new backup once the cause is fixed."
            runbook_url: "https://safeops.work/members/chapter-12-backup-restore/runbook/"

        - alert: PostgresBackupTooOld
          # > 0: a cluster that has never completed a backup reports 0; PostgresBackupFailed covers
          # a first backup that fails.
          # The age comes first, so that $value in the summary is the age, not the timestamp.
          expr: |
            time() - barman_cloud_cloudnative_pg_io_last_available_backup_timestamp > 26 * 3600
            and barman_cloud_cloudnative_pg_io_last_available_backup_timestamp > 0
          for: 15m
          labels:
            severity: warning
            component: postgres
          annotations:
            summary: "{{ $labels.namespace }}: the newest Postgres base backup is {{ $value | humanizeDuration }} old"
            description: "No base backup of app-postgres in {{ $labels.namespace }} completed in the last 26 hours; a restore would replay more WAL, and depends on every segment since. First check: the ScheduledBackup (suspended? its last schedule time), then take a backup by hand."
            runbook_url: "https://safeops.work/members/chapter-12-backup-restore/runbook/"

        - alert: PostgresNeverBackedUp
          # A cluster that never completed a backup reports 0 - PostgresBackupTooOld leaves it out.
          # The clock is the instance's start time, so a new cluster gets the same 26 hours as the
          # daily schedule; a restart starts the clock again (the alert then comes later, not never).
          expr: |
            time() - cnpg_pg_postmaster_start_time > 26 * 3600
            and barman_cloud_cloudnative_pg_io_last_available_backup_timestamp == 0
          for: 15m
          labels:
            severity: warning
            component: postgres
          annotations:
            summary: "{{ $labels.namespace }}: Postgres has run for {{ $value | humanizeDuration }} without a single base backup"
            description: "app-postgres in {{ $labels.namespace }} has no completed base backup at all; a restore is impossible. First check: the ScheduledBackup (missing? suspended?) and kubectl get backups in {{ $labels.namespace }}, then take a backup by hand."
            runbook_url: "https://safeops.work/members/chapter-12-backup-restore/runbook/"
AlertFires whenWhy it matters
PostgresWALArchivingFailingthe newest WAL segment failed to archive, for 15 minutespoint-in-time recovery stops at the last good segment, and the unarchived WAL fills the disk
PostgresBackupFailedthe newest base backup failed after the last good oneevery restore must replay more WAL from an older start
PostgresBackupTooOldno completed base backup for 26 hoursthe daily schedule stopped - suspended or deleted
PostgresNeverBackedUpthe instance has run for 26 hours without a single completed backupthe schedule never ran - a restore is impossible

Left out on purpose: the age of the last archived segment. An idle database writes nothing, so nothing is archived - on a quiet cluster the last archive is hours old while everything works. The signal is the failure itself: the last attempt is newer than the last success.

A New Major Version: pg_upgrade

A PostgreSQL minor version (18.5 → 18.6) is a new image and a restart. A major version (17 → 18) changes the format of the data files: the new server cannot open the old directory as it is. Three ways across:

  • pg_upgrade - converts the data directory in place; with --link it re-links the files instead of copying them, so it takes minutes, not hours. The database is down while it runs.
  • Dump and restore (pg_dump, then load into a new cluster) - slow for large databases, but works across any versions and machines.
  • Logical replication into a new cluster on the new version, then a switch - almost no downtime, much more to operate.

CloudNativePG does the first: a new major version in spec.imageName makes it stop the instance, run pg_upgrade --link in a job, and start the new version on the converted directory. On kind each database took about a minute (17 → 18, 2026-10-12). What it needs, and why:

  • The same Linux distribution in the old and the new image - the job runs the old binaries next to the new ones. The platform moved 17 to the Debian trixie image first, then to 18.
  • A backup first. pg_upgrade --link changes the original files; once the new server has started on them, the old one cannot. If the job fails, setting the old image back starts the old version - nothing was changed yet. After that point, the way back is a restore.
  • A new archive for the new version. Point-in-time recovery does not cross a major version: WAL from 18 cannot be replayed on a 17 base backup. So the change that moves the image also gives the plugin a new serverName (app-postgres-pg18); 17’s backups and WAL stay under app-postgres and still restore into a 17 cluster.
  • A base backup right after, so the new archive has a starting point.
  • Statistics for every database. Since PostgreSQL 18, pg_upgrade carries most of the planner’s statistics over (on kind a table’s pg_stats rows were all still there after 17 → 18), but not all: not the extended statistics made with CREATE STATISTICS, and not the activity counters autovacuum decides by. PostgreSQL’s pg_upgrade guide gives two commands - vacuumdb --all --analyze-in-stages --missing-stats-only (fast: only what has no statistics), then vacuumdb --all --analyze-only. The --all matters: without it vacuumdb analyzes one database - the one in PGDATABASE, or else the one named after the user. In a CloudNativePG pod that user is postgres, so it would analyze postgres and leave app as it was.

The lab runs it on a small cluster of its own (B7).

Guardrails That Stop It

  • Restore next to production (script) - postgres-restore-manifest.sh always creates app-postgres-restore; it never writes over app-postgres.
  • A restore path that exists before it is needed (network policies) - the restore cluster is allowed in advance.
  • A point in time, not “the latest” (instruction) - every restore after damage names its target time.
  • Proof with data (checklist) - the expected rows with the app’s user, before anyone says “restored”.
  • Backups watched (alerts) - a failing archive or backup is reported within minutes, a schedule that stopped within about a day (26 hours) - not found during an incident.
  • One archive per major version and per cluster (cluster manifest) - the serverName changes with the major version and with every new cluster, so a restore never mixes WAL of two versions or of two databases (Chapter 22).

Safe Workflow (Step-by-Step)

  1. Stop the damage first; leave the original database running and untouched.
  2. Pick the moment - the last good second before the damage, in UTC.
  3. Restore next to it: postgres-restore-manifest.sh -n <env> -t <time>, applied with --context; time it to Ready.
  4. Prove it: the expected rows, read and written with the app’s user.
  5. Switch or copy back - either freeze writes, reconcile what was written after T, and switch the application to the restore: a change of its database host in Git, reviewed (Chapter 03). Or copy only the lost rows back: a one-off SQL statement that names its source (app-postgres-restore), its target (app-postgres) and exactly which rows, read and approved by a second person before it runs - Git does not run it.
  6. Delete the restore cluster when the incident is closed, and write down how long it took.

Instructions for Your AI Agent

The rules this chapter adds:

  1. Never run a DELETE or UPDATE against a shared database without a WHERE reviewed by a person, never a DROP without a person’s separate approval - and none of them in production. Enforced by: RBAC on Hetzner - the everyday sign-in has no exec in production; on kind - instruction only.
  2. Never restore over an existing database; restore next to it, as app-postgres-restore. Enforced by: postgres-restore-manifest.sh (the name is fixed); the network policies allow only that name.
  3. Every restore after damage names its target time; “the latest” is a decision, not a default. Enforced by: instruction only.
  4. Report a restore as done only with data proof - the expected rows, read and written with the app’s user - never because the cluster is Ready. Enforced by: instruction only.

This builds on: Observability (Chapter 11) - the backup alerts follow the same rule: each one asks for an action. This enables: Controlled Chaos (Chapter 13) - with a restore you have proven, you can break things on purpose.