CloudNativePG: Backups, Restore Drills and Pre-upgrade Backups¶
The CloudNativePG (CNPG) operator runs the PostgreSQL clusters on hetzner-mgmt (components/cloudnative-pg/base, chart 0.29.1, operator 1.30). This page covers how those clusters are backed up, how each backup is proven restorable every week, how a component gates an upgrade behind a fresh, verified backup, and how the operator's own upgrade is gated (Renovate architecture §11).
The webshop cluster runs the same parts for the shops' databases (cluster/webshop/cloudnative-pg/), with its own bucket webshop-backups, its own gate CLUSTERS and drills, and requests and limits for one node. Its differences and the steps for a shop's database are in the webshop environment README.
Needs the backup store
Everything here writes to the store described on the backups page (Hetzner Object Storage, fsn1, with object lock), through the backup-store Secret wired by task #1228. Without that Secret, or if the store refuses barman-cloud's uploads, the database pods still start, but WAL archiving and backups fail, CNPGWALArchivingFailing fires, and WAL builds up on the database volume.
The bucket's object lock makes S3 refuse an upload that carries neither Content-MD5 nor an SDK checksum header. barman-cloud sends no Content-MD5, so its uploads rely on boto3's default checksum header. Never set AWS_REQUEST_CHECKSUM_CALCULATION=when_required in the ObjectStore: the plugin docs suggest it for some S3-compatible stores, but here it would turn off the only integrity header barman-cloud sends.
Overview¶
| Part | Where | What it does |
|---|---|---|
| Barman Cloud Plugin | components/cloudnative-pg/barman-cloud (chart plugin-barman-cloud 0.9.0, plugin v0.16.0) |
Archives WAL and takes base backups to S3. It replaces the in-tree barmanObjectStore, which has been deprecated since CNPG 1.26. It runs in cnpg-system and needs cert-manager. Its Flux Kustomization cnpg-barman-cloud dependsOn backup-store, so nothing that archives WAL starts before the store's secret exists and its smoke Job has written to it. It depends on cloudnative-pg-system (namespace and HelmRepository), not on the operator: the plugin watches only its own ObjectStore (plugin v0.15.1, internal/cnpgi/operator/manager.go), and the operator finds it through its Service whenever it appears. |
ObjectStore backup-store |
components/cloudnative-pg/object-store, included in each Cluster's namespace and in cnpg-drill |
Points at s3://skatzi-backups/${cluster_name}/cnpg with the backup-store Secret, and keeps 30 days (retentionPolicy: "30d"). The bucket's 14-day object lock is shorter, so Barman can prune; its deletes become delete markers that the bucket lifecycle clears after 31 days. |
plugins on each Cluster |
the Cluster's own manifest | Sets the WAL archiver and serverName. Each Cluster writes under .../cnpg/<serverName>/. |
ScheduledBackup <cluster>-daily |
next to the Cluster | One base backup a day between 02:00 and 03:00 UTC, plus one as soon as it is created (immediate: true). |
| Restore drill | components/cloudnative-pg/drill (shared parts), cluster/hetzner-mgmt/cloudnative-pg/drill/cron-job.yaml (one CronJob per Cluster) |
Every Sunday it restores the latest backup into the scratch namespace cnpg-drill, checks the data and records the result. |
| Pre-upgrade backup | components/cloudnative-pg/preupgrade |
A Job template that takes an on-demand Backup and then runs the same restore check. A component's <component>-preupgrade Flux Kustomization uses it, and so does each image gate <cluster>-image-preupgrade. |
| Operator upgrade gate | components/cloudnative-pg/operator-preupgrade (script, RBAC), cluster/<cluster>/cloudnative-pg/preupgrade/job.yaml (one per cluster, hetzner-mgmt and webshop: the Clusters and the target chart) |
Before a new operator chart, backs up and restores every backed-up Cluster. The cloudnative-pg Kustomization dependsOn cloudnative-pg-preupgrade. See Operator upgrade gate. |
| Alerts | components/cloudnative-pg/drill-alerts/prometheus-rule.yaml |
CNPGRestoreDrillFailed, CNPGWALArchivingFailing, CNPGBackupStale, sent to Mattermost through Alertmanager. They have their own Flux Kustomization cnpg-drill-alerts, which dependsOn prometheus-stack for the PrometheusRule CRD. On webshop the cloudnative-pg operator Kustomization also dependsOn it, for the PodMonitor CRD; that is safe there because prometheus-stack depends only on hetzner-csi and external-secrets-config. On hetzner-mgmt the operator must not, and cnpg-drill must not: the operator, Keycloak and Mattermost gates depend on cnpg-drill, and prometheus-stack depends on keycloak, so that edge closes a cycle where none of them ever become Ready again. |
Clusters covered¶
| Cluster | Namespace | serverName |
Backup (UTC) | Drill (Sunday, UTC) | Drill query |
|---|---|---|---|---|---|
terraform-state-db |
terraform-state |
terraform-state |
02:00 | 04:00 | rows of every <schema>.states table (one schema per Terraform environment) |
mattermost-db |
mattermost |
mattermost |
02:10 | 05:00, by mattermost-restore-drill, which also starts Mattermost on the copy |
SELECT count(*) FROM users |
keycloak-db |
keycloak |
keycloak |
02:20 | 09:00 | SELECT count(*) FROM realm |
tasks-db |
tasks-dev |
taskbase-dev |
set in Skatzi/taskbase |
06:00 | SELECT count(*) FROM tasks |
tasks-prod-db |
tasks-prod |
taskbase-prod |
set in Skatzi/taskbase |
07:00 | SELECT count(*) FROM tasks |
emiliero-db |
emiliero-prod |
emiliero |
02:50 (set in Skatzi/emiliero) |
08:00 | SELECT count(*) FROM posts |
nightgain-db |
nightgain |
nightgain |
02:40 | none | — |
- Taskbase owns its
Clusterand namespace inSkatzi/taskbase(deploy/dev,deploy/prod), so itsplugins,ObjectStore,ScheduledBackupand namespace label belong there too. They are not patched in from this repository, because a separate Flux Kustomization would have to create theObjectStorebefore Taskbase's own Kustomization creates the namespace. They are onmainthere, withserverNametaskbase-devandtaskbase-prod, so the drills and the operator gate cover both Clusters. - nightgain is commented out of
cluster/hetzner-mgmt/kustomization.yaml. Its component has backups configured, but it has no drill until it is deployed. When it is, add adrill-nightgainCronJob with a query against one of its tables. - Not covered yet:
botyard-prod-db(Dupondforge/botyard-control) has no backups at all: noplugins, noScheduledBackup. Its repository owns its Cluster, so they belong there. Until it has them, an operator upgrade restarts it unprotected (Operator upgrade gate). - No backups by design:
helloweekly-dev-dbinhelloweekly-dev, whose Cluster is defined inEmmalia/Helloweeklydeploy/dev, has no backups because dev's data is disposable (#3670). It is in no restore drill and not in the operator gate'sCLUSTERS, socnpg-operator-preupgradereportingWARNING: helloweekly-dev/helloweekly-dev-db has no backups; the operator upgrade restarts it unprotectedis expected.
Adding backups to a Cluster¶
- Label the namespace
backup.skatzi.com/store: enabled, so it gets thebackup-storeSecret. If more than one Flux Kustomization applies the sameNamespace(for example asecretsand abasepath), label it in every one of them. Otherwise they keep removing each other's label. - Add the
ObjectStoreto the namespace. From a component, add../../cloudnative-pg/object-storeto itskustomization.yaml, withnamespace:set. Elsewhere, copy the manifest and replace${cluster_name}with the cluster name. The Flux Kustomization needspostBuild.substituteFromthecluster-configConfigMap anddependsOn: cnpg-barman-cloud. -
Add the plugin to the
Cluster, with aserverNamethat is unique per cluster:spec: plugins: - name: barman-cloud.cloudnative-pg.io isWALArchiver: true parameters: barmanObjectName: backup-store serverName: <unique-name>Adding the plugin restarts the instance pods, to inject the sidecar. With one instance, that means a short outage. 4. Add a
ScheduledBackup(seecomponents/mattermost/base/scheduled-backup.yaml). Its schedule has six fields, with seconds first. 5. Add adrill-<serverName>CronJob tocluster/<cluster>/cloudnative-pg/drill/cron-job.yaml, with a query that returns a row count of a table that is never empty. 6. Add the Cluster, with the same query, toCLUSTERSincluster/<cluster>/cloudnative-pg/preupgrade/job.yaml. The operator gate fails for a Cluster that archives to the store but is not listed there.
The endpoint is not set in the ObjectStore. The sidecar gets AWS_ENDPOINT_URL from the backup-store Secret through instanceSidecarConfiguration.env, and boto3 reads it from the environment. That env entry is optional, so a missing Secret makes archiving fail rather than the database pod. The plugin passes the same env to restore Jobs (internal/cnpgi/operator/lifecycle_envs.go in plugin v0.15.1).
Restore drill¶
drill.sh (ConfigMap cnpg-drill) runs as ServiceAccount cnpg-drill. It:
- reads the source
Cluster(serverName, database, storage size and running image). A read-only ClusterRole gives it access toclustersandbackups, and to no Secrets. - deletes any throwaway Cluster left over from an earlier run of the same mode, and waits until its volumes are gone.
- creates
Cluster<mode>-<serverName>incnpg-drill(drill-<serverName>for the weekly drill,preupgrade-<serverName>for the pre-upgrade Job, so the two can run at the same time) with the same image and size, bootstrapped byrecoveryfrom thebackup-storeObjectStore. This restores the latest base backup and replays all archived WAL. The throwaway Cluster has no WAL archiver, so it never writes into the store. - waits up to 40 minutes for it to become
Ready, then runs the query throughpsqlin the instance pod. The result must be a number of at least 1 (MIN_ROWS). - records success in ConfigMap
drill-<serverName>incnpg-drill:lastSuccess,source,image,queryandrows. - deletes the throwaway Cluster, whether the drill passed or failed.
A failed drill is never retried within the same run (backoffLimit: 0, deadline one hour). This is the success that the evidence of a stateful upgrade cites:
kubectl --context admin@mgmt-cluster -n cnpg-drill get configmap drill-terraform-state -o jsonpath='{.data}'
kubectl --context admin@mgmt-cluster -n cnpg-drill get cronjob # LAST SCHEDULE / LAST SUCCESSFUL
To run a drill now:
kubectl --context admin@mgmt-cluster -n cnpg-drill create job --from=cronjob/drill-terraform-state drill-terraform-state-manual
kubectl --context admin@mgmt-cluster -n cnpg-drill logs -f job/drill-terraform-state-manual
Alerts¶
| Alert | Fires when |
|---|---|
CNPGRestoreDrillFailed (critical) |
for 2 hours, the last scheduled run of a drill CronJob has not succeeded, a drill has never succeeded, or none has succeeded in 8 days (kube-state-metrics kube_cronjob_status_last_*) |
CNPGWALArchivingFailing (critical) |
for 30 minutes, the last failed WAL archive is newer than the last successful one (cnpg_pg_stat_archiver_*) |
CNPGBackupStale (warning) |
for 1 hour, the newest available base backup is older than 2 days (barman_cloud_cloudnative_pg_io_last_available_backup_timestamp) |
All three carry incident: "true" and component: cloudnative-pg, so Taskbase opens an incident for them (ADR 0018). Their runbooks: CNPGRestoreDrillFailed, CNPGWALArchivingFailing, CNPGBackupStale.
Pre-upgrade backup¶
components/cloudnative-pg/preupgrade is the CNPG part of a component's backup gate (§11 item 1). It suits a CNPG-backed component whose gate needs only the database and does not stop the app. Mattermost and Keycloak do not use it: their gates stop the app around the Backup, start it again as soon as the Backup has completed (also on failure), and start the app on the restored copy, so each has its own Job (Mattermost backups, Keycloak backups) on the same cnpg-drill namespace and ObjectStore. A component instantiates it with its own Flux Kustomization, and its main Kustomization dependsOn that one:
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
name: example-preupgrade
namespace: flux-system
spec:
interval: 10m0s
path: ./components/cloudnative-pg/preupgrade
prune: true
wait: true # Ready only once the Job has completed
timeout: 2h
sourceRef:
kind: GitRepository
name: ${git_source_repository}
postBuild:
substitute:
source_namespace: example
source_cluster: example-db
target_version: "1.2.0" # the version about to be applied; bump it with the upgrade
drill_query: "SELECT count(*) FROM accounts"
dependsOn:
- name: cnpg-drill
The Job preupgrade-<cluster> in cnpg-drill:
- passes without a backup when the Cluster does not exist yet. On a new cluster the gate runs before its Cluster, because the Cluster's Kustomization waits for it; failing there would hold both for good. Any other error reading the Cluster fails the Job.
- creates
Backup<cluster>-preupgrade-<timestamp>(annotated with the target version) and waits for it to complete. Afailedphase fails the Job. - restores and checks it exactly as the drill does, into its own throwaway Cluster
preupgrade-<serverName>, and records ConfigMappreupgrade-<serverName>.
target_version is in the Job's environment, and the Job has kustomize.toolkit.fluxcd.io/force: Enabled. A new target version therefore recreates the Job, and Flux applies the gated component only after the backup of the old version has been taken and restored. Stopping writes before the backup (scaling the app to 0, maintenance mode) is the gate's own step. The CNPG backup is consistent without it, but writes made after it would not be in the restored copy.
The demo shop's gate (webshop)¶
shop-demo-preupgrade (cluster/webshop/shop-demo/kustomization.yaml) gates the demo shop's database shop-demo-db with this template: source_namespace: shop-demo, source_cluster: shop-demo-db, drill-demo's query SELECT count(*) FROM river_migration, and target_version the shop image's image.tag in deploy/demo/helmrelease.yaml of eloro/webshop-platform. The shop-demo Kustomization dependsOn it, and it waits for cnpg-drill and for the operator (cloudnative-pg), which completes the on-demand Backup. Its Job is cnpg-drill/preupgrade-shop-demo-db, and it records ConfigMap preupgrade-demo.
The shop's image and the gate live in two repositories, so a demo image pull request in eloro/webshop-platform that is stateful (a release in its range carries a risky migration, or the chart annotation webshop.skatzi.com/backup-gate: required; design 06 §6.6 there) is paired with one here:
- Open a pull request here that sets
target_versionto the image pull request's newimage.tag(for examplev1.115.0), and name the image pull request in it. Leave the image pull request unmerged. - Once it is merged, wait for the gate to pass on the old image:
kubectl --context webshop -n flux-system get kustomization shop-demo-preupgrade kubectl --context webshop -n cnpg-drill get configmap preupgrade-demo -o jsonpath='{.data.targetVersion} {.data.lastSuccess}{"\n"}'targetVersionmust be the new tag, with alastSuccessafter the merge. A failed Job (kubectl --context webshop -n cnpg-drill logs job/preupgrade-shop-demo-db) keepsshop-demofrom reconciling at all, so fix it or revert the pull request before anything else changes indeploy/demo. - Then merge the image pull request. Merged the other way round, the shop reconciles the new image before the backup, and the gate backs up the already-migrated database.
The operator persona lands each demo image pull request and decides which kind it is (Land a demo release bump). An expand-only image pull request (standard) leaves target_version as it is: the gate stays Ready and does not run again. Leaving it behind the deployed tag is harmless, but the next stateful pull request still moves it to its own new tag.
Moving target_version here does not touch the operator gate's TARGET_VERSION, but both restore into preupgrade-demo, so never merge the two moves in the same push or while the other Job runs.
On a new cluster the gate cannot be applied before shop-demo has created the namespace for the gate's Role, and shop-demo waits for the gate. (A missing shop-demo-db alone no longer fails the Job: it passes without a backup.) To bootstrap, open a pull request that removes shop-demo-preupgrade from the dependsOn of shop-demo, and revert it once the database runs and has a base backup; then delete the failed Job (kubectl --context webshop -n cnpg-drill delete job preupgrade-shop-demo-db) so Flux recreates it.
Taskbase's image gates (hetzner-mgmt)¶
taskbase-dev-preupgrade and taskbase-prod-preupgrade (cluster/hetzner-mgmt/taskbase-<env>/kustomization.yaml) gate the PostgreSQL image of tasks-db and tasks-prod-db. Their files are in Skatzi/taskbase, deploy/<env>/preupgrade/: an instantiated copy of this template (#3217), outside deploy/<env>/kustomization.yaml, with the drill query SELECT count(*) FROM tasks and TARGET_VERSION the tag of the Cluster's imageName (for example 18.1-system-trixie). Renovate moves both in one pull request there, and its deploy/test_preupgrade.py fails while they differ.
| Gate | Job in cnpg-drill |
ConfigMap | Gated Kustomization |
|---|---|---|---|
taskbase-dev-preupgrade |
preupgrade-tasks-db |
preupgrade-taskbase-dev |
taskbase-dev |
taskbase-prod-preupgrade |
preupgrade-tasks-prod-db |
preupgrade-taskbase-prod |
taskbase-prod |
Each gate reads the same GitRepository, taskbase, as the Kustomization it gates. kustomize-controller applies a Kustomization only when every dependency with the same source has applied the same revision, so a Taskbase commit that changes imageName and TARGET_VERSION reaches taskbase-<env> only after the gate has applied that commit and its recreated Job has completed. The gate depends on cnpg-drill (the scratch namespace, drill.sh and the ObjectStore) and on cloudnative-pg, whose operator completes the on-demand Backup. The Backup is online: Taskbase keeps running while the gate runs, but taskbase-<env> applies nothing new from Taskbase until the Job ends (up to 2 hours, activeDeadlineSeconds; the Kustomization's timeout is 2h5m). The gates carry platform.skatzi.com/source-repository: taskbase, so Taskbase raises a failed gate in its own project.
To read a pass, check that targetVersion is the new image tag and lastSuccess is after the merge. The operator gate writes the same ConfigMap with its chart version as targetVersion, so an older entry may name a chart version instead:
flux --context admin@mgmt-cluster get kustomizations taskbase-prod-preupgrade
kubectl --context admin@mgmt-cluster -n cnpg-drill get configmap preupgrade-taskbase-prod \
-o jsonpath='{.data.targetVersion} {.data.lastSuccess} {.data.rows}{"\n"}'
kubectl --context admin@mgmt-cluster -n cnpg-drill logs job/preupgrade-tasks-prod-db
A failed Job keeps taskbase-<env> from reconciling at all, Taskbase's application releases included. Fix the cause, or revert the image pull request in Skatzi/taskbase, then delete the failed Job (kubectl --context admin@mgmt-cluster -n cnpg-drill delete job preupgrade-tasks-prod-db) so Flux recreates it. An image change of tasks-prod-db is drain-class (Renovate ADR §11): the restart onto the new image takes Taskbase down, not the gate.
On a new cluster the gate cannot be applied before taskbase-<env> has created the namespace for the gate's Role, and taskbase-<env> waits for the gate. (A missing Cluster alone does not fail the Job: it passes without a backup.) Bootstrap it as the demo shop's gate above: remove taskbase-<env>-preupgrade from the dependsOn of taskbase-<env> in a pull request, and revert it once the database runs and has a base backup.
Emiliero's image gate (hetzner-mgmt)¶
emiliero-preupgrade (cluster/hetzner-mgmt/emiliero/kustomization.yaml) gates the PostgreSQL image of emiliero-db, built like Taskbase's. Its files are in Skatzi/emiliero, deploy/prod/preupgrade/ (#3221), outside deploy/prod/kustomization.yaml, with the drill query SELECT count(*) FROM posts and TARGET_VERSION the tag of the Cluster's imageName. Renovate moves both in one pull request there, and its deploy/test_preupgrade.py fails while they differ.
| Gate | Job in cnpg-drill |
ConfigMap | Gated Kustomization |
|---|---|---|---|
emiliero-preupgrade |
preupgrade-emiliero-db |
preupgrade-emiliero |
emiliero |
It reads the same GitRepository, emiliero, as emiliero, depends on cnpg-drill and cloudnative-pg, has timeout: 2h5m for the Job's 2-hour activeDeadlineSeconds, and carries platform.skatzi.com/source-repository: emiliero, all as Taskbase's gates do. While the Job runs, emiliero applies nothing new from Emiliero, its application releases included.
emiliero-db also holds Hello weekly's database (helloweekly-prod). The gate's online backup is of the whole Cluster and leaves both apps up; the restart onto a new image takes both down. The query checks Emiliero's data only, as drill-emiliero does.
flux --context admin@mgmt-cluster get kustomizations emiliero-preupgrade emiliero
kubectl --context admin@mgmt-cluster -n cnpg-drill get configmap preupgrade-emiliero \
-o jsonpath='{.data.targetVersion} {.data.lastSuccess} {.data.rows}{"\n"}'
kubectl --context admin@mgmt-cluster -n cnpg-drill logs job/preupgrade-emiliero-db
A pass has targetVersion the new image tag and lastSuccess after the merge (the operator gate writes the same ConfigMap with its chart version). A failed Job, and a new cluster, are handled as for Taskbase's gates above, with preupgrade-emiliero-db and emiliero.
PostgreSQL image¶
A Cluster's PostgreSQL version is its spec.imageName. When a manifest leaves it out, the CNPG webhook fills in the operator's default image when the Cluster is created, and nothing changes it after that: an operator upgrade changes the default for new Clusters only. So a Cluster without imageName in Git stays on the image of its creation day. shop-demo-db (webshop, created later) got 18.6-system-trixie from operator 1.30.1, while the older Clusters on hetzner-mgmt were created on 18.1. To read what each Cluster runs:
kubectl --context admin@mgmt-cluster get clusters.postgresql.cnpg.io -A \
-o custom-columns='NS:.metadata.namespace,NAME:.metadata.name,IMAGE:.spec.imageName'
Renovate sees imageName only through the regex manager in this repository's renovate.json (#3212). Renovate's kubernetes manager reads image: keys only. The manager proposes minors of ghcr.io/cloudnative-pg/postgresql within the same major and suffix (18.1-system-trixie → 18.7-system-trixie), and no majors: a PostgreSQL major is planned against the app's support matrix (Keycloak supports PostgreSQL 13 to 17, so keycloak-db stays on 15). A Cluster appears only once its manifest pins imageName. Skatzi/taskbase (#3217) and Skatzi/emiliero (#3221) carry the same manager in their own renovate.json, until Skatzi/renovate-config does (see Renovate: coverage).
A minor image change restarts the Cluster's single instance on the new image, and it is stateful (Renovate ADR §11). The other gates are keyed on something else (the operator gate on the chart version, keycloak-preupgrade and mattermost-preupgrade on the app version), so a Cluster whose image Renovate moves needs an image gate of its own; Taskbase's and Emiliero's Clusters have theirs in their own repositories (Taskbase's image gates, Emiliero's image gate). Until it has one, its image upgrade waits:
| Cluster | Image (2026-11-15) | imageName in Git |
Gate and upgrade |
|---|---|---|---|
terraform-state-db, mattermost-db |
18.7-system-trixie |
pinned | image gates (#3220); upgraded from 18.1 behind them (#3222) |
keycloak-db |
15.19-system-trixie |
pinned | image gate (#3220); 15.20 by the Renovate pull request |
tasks-db, tasks-prod-db |
18.7-system-trixie |
pinned (Skatzi/taskbase, #3217) |
taskbase-<env>-preupgrade (#3218); upgraded from 18.1 behind them (#3219, drain-class for tasks-prod-db) |
emiliero-db |
18.1-system-trixie |
pinned (Skatzi/emiliero, #3221) |
emiliero-preupgrade (#3225); upgrade to 18.7 by the Renovate pull request in Skatzi/emiliero, after the gate's first pass (#3226) |
botyard-prod-db |
18.1-system-trixie |
Dupondforge/botyard-control |
no backups at all (Clusters covered) |
18.1 has PostgreSQL bug #19370: a correlated sub-select inside an array subscript kills the backend with signal 11, and with restart_after_crash off the whole instance stops (the Taskbase outage of 2026-11-14, #3210). It is fixed in 18.2 (release notes).
Image gates¶
An image gate is the pre-upgrade backup keyed on the PostgreSQL image: a Flux Kustomization <cluster>-image-preupgrade on components/cloudnative-pg/preupgrade, next to the Cluster's own Kustomization in cluster/hetzner-mgmt/<component>/kustomization.yaml, which dependsOn it:
| Gate | Cluster | Gated Kustomization | Job (in cnpg-drill) |
Restores into, records |
|---|---|---|---|---|
terraform-state-db-image-preupgrade |
terraform-state/terraform-state-db |
terraform-state-db |
preupgrade-terraform-state-db |
preupgrade-terraform-state |
mattermost-db-image-preupgrade |
mattermost/mattermost-db |
mattermost |
preupgrade-mattermost-db |
preupgrade-mattermost |
keycloak-db-image-preupgrade |
keycloak/keycloak-db |
keycloak-database |
preupgrade-keycloak-db |
preupgrade-keycloak |
target_version is the tag of the Cluster's imageName (for example 18.1-system-trixie), and the line above it is # renovate: datasource=docker depName=ghcr.io/cloudnative-pg/postgresql. Renovate reads the tag through the shared preset's # renovate: comment manager, and imageName through the regex manager in renovate.json: both are the same package, so one pull request moves both. components/cloudnative-pg/preupgrade/test_image_gates.py fails a pull request in which they differ, in which the Cluster's Kustomization does not dependsOn its gate, or in which a Cluster pins imageName without a gate. The drill_query is the operator gate's for the same Cluster.
When the pull request is merged, the new target_version recreates the Job, which backs up the Cluster on the old image and restores it (the copy runs the Cluster's status.image, still the old one). Only then does the gated Kustomization apply the new imageName, and CNPG restarts the instance on it. The upgrade itself is a short outage of the single instance. Read the pass before you call the upgrade landed:
kubectl --context admin@mgmt-cluster -n flux-system get kustomization terraform-state-db-image-preupgrade
kubectl --context admin@mgmt-cluster -n cnpg-drill get configmap preupgrade-terraform-state -o jsonpath='{.data.targetVersion} {.data.lastSuccess} {.data.image}{"\n"}'
kubectl --context admin@mgmt-cluster get cluster -n terraform-state terraform-state-db -o jsonpath='{.status.image} {.status.phase}{"\n"}'
targetVersion must be the new tag, image the old one, and lastSuccess after the merge. A failed Job (kubectl --context admin@mgmt-cluster -n cnpg-drill logs job/preupgrade-terraform-state-db) keeps the gated Kustomization from applying anything, so fix it or revert the pull request first. A minor within the same major keeps the data directory's format, so the way back is a revert of imageName (and target_version), which restarts the instance on the old minor; the gate's backup is for a release that damages data.
Why separate from the app gates. Mattermost's and Keycloak's own gates stop the app, back up and start the app on the restored copy, because the app's migrations run one way. A PostgreSQL minor runs no app migration, so the image gate backs up with the app running, as the operator gate does. Keycloak's gate could not hold the image anyway: keycloak-preupgrade dependsOn keycloak-database, the Kustomization that applies imageName, so gating keycloak-database on it would be a cycle. An image pull request and an app pull request of the same database must not be merged in one push: both gates would back up the same Cluster at once.
Adding one. Pin imageName to the live status.image first (flux --context admin@mgmt-cluster diff kustomization <name> --path <path> must show no change), then add the gate with that tag, its dependsOn (the namespace's Kustomization, cnpg-drill, cloudnative-pg), the dependsOn on the Cluster's Kustomization, and the Cluster to EXPECTED in the test. Its first run takes a backup and restores it, so it is Ready only some minutes after the merge, and the Cluster's Kustomization waits for it that once.
Operator replicas¶
The API server calls the operator's admission webhooks (mcluster.cnpg.io and the others, behind cnpg-webhook-service) on every create or update of a Cluster, Backup, ScheduledBackup, Pooler or Database, including Flux's server-side dry run, and they fail closed (failurePolicy: Fail). With one replica, a stalled node fails every Kustomization that applies a Cluster (#2254, #2634).
On hetzner-mgmt the operator therefore runs two replicas (replicaCount: 2, a patch in cluster/hetzner-mgmt/cloudnative-pg/kustomization.yaml). The component spreads them over nodes (topologySpreadConstraints on kubernetes.io/hostname, DoNotSchedule, tainted nodes not counted) and sets a PodDisruptionBudget with maxUnavailable: 1. Every replica serves the webhook, and only the reconcilers wait for the leader lease (--leader-elect): in CNPG 1.30.1, internal/cmd/manager/controller/controller.go loads the webhook certificate from Secret cnpg-webhook-cert and registers the webhooks before the manager starts, and controller-runtime runs the webhook server on every replica. A restart of the operator does not restart the instance pods; only a new operator image does.
webshop is one node, so it stays at the chart's one replica; the spread constraint and the budget do nothing there, and maxUnavailable: 1 still lets the node drain.
To check that both replicas serve the webhook on different nodes:
kubectl --context admin@mgmt-cluster -n cnpg-system get endpointslices -l kubernetes.io/service-name=cnpg-webhook-service \
-o jsonpath='{range .items[*].endpoints[*]}{.nodeName} {.conditions.ready}{"\n"}{end}'
Barman Cloud plugin replica¶
The operator calls the plugin over gRPC (Service barman-cloud, port 9090) on every reconcile of a Cluster that uses it. The plugin runs one replica, unlike the operator, because more than one did not work with chart 0.8.1 and plugin v0.15.1 (#2661):
- The gRPC server runs on the lease holder only.
internal/cnpgi/operator/manager.gostarts the manager with--leader-electand adds the gRPC server (CNPGIinstart.go) as a plain runnable. It does not implementNeedLeaderElection, so controller-runtime (v0.25.1,pkg/manager/runnable_group.go) puts it in the leader-election group. A second replica would not listen on 9090 until it took the lease822e3f5c.cnpg.io. - The chart marks that standby Ready anyway. Its readiness probe checks port 8081, the health endpoint every replica opens; upstream's own
kubernetes/deployment.yamlchecks 9090. TheServicewould send about half of the operator's connections to a replica that refuses them. If 9090 were checked instead, the standby would never be Ready: the Deployment would never be fully available, Flux's wait for the HelmRelease would time out, and aPodDisruptionBudgetwould block every drain. - The chart hard-codes
strategy: Recreate("RollingUpdate strategy is not supported by the operator yet",templates/deployment.yaml); itsupdateStrategyvalue is not used.
So on hetzner-mgmt the plugin prefers a worker other than worker-1 instead (preferred nodeAffinity, a patch in cluster/hetzner-mgmt/cloudnative-pg/kustomization.yaml). worker-1 stalls the most: 246 container restarts against 67 on worker-2 and 47 on worker-3 (2026-11-07), and the plugin restarted 11 times in 16 days there. Because the rule is preferred, the plugin still schedules on worker-1 when the other workers are full. A worker-2 or worker-3 stall still takes the plugin down.
Plugin v0.16.0 (chart 0.9.0) fixes the first point: CNPGI now implements NeedLeaderElection
(internal/cnpgi/operator/start.go), so every replica serves 9090 and only the ObjectStore
controller needs the lease (upstream #1105, Running Multiple Replicas).
The readiness probe on 8081 is then right. Recreate stays, so more replicas protect against a
node or pod loss but not against the restart of an upgrade. The plugin still runs one replica here
until a change sets replicaCount: 2 (task #3644).
A plugin upgrade restarts every Cluster that uses it¶
The plugin injects its sidecar with the image in its own SIDECAR_IMAGE (the chart's
sidecarImage, by default the plugin's version), unless a Cluster sets the sidecarImage plugin
parameter (internal/cnpgi/operator/lifecycle.go, plugin v0.16.0). In CNPG 1.30.1 the operator
builds each instance pod's target spec through the plugins' lifecycle hook and compares it with the
pod's cnpg.io/podSpec annotation (checkPodSpecIsOutdated in
internal/controller/cluster_upgrade.go). So a new plugin version gives every Cluster with
plugins: barman-cloud.cloudnative-pg.io a rollout, original and target PodSpec differ. Each
Cluster here has one instance and primaryUpdateMethod: restart, so that is a short outage of each
database: on hetzner-mgmt emiliero-db, keycloak-db, mattermost-db, tasks-db,
tasks-prod-db (Taskbase) and terraform-state-db, and shop-demo-db and shop-eloro-db on
webshop (2026-11-26). Clusters without the plugin, such as botyard-prod-db, do not restart. The
restarts come when each Cluster next reconciles after the plugin is back, up to 17 minutes later
(next section).
Because tasks-prod-db restarts, a plugin upgrade is drain-class (owner, #3643): its pull request
carries the label drain-before-merge, and an operator merge run holds agent work around the merge
(Renovate ADR: Drain).
The merge run's watch ends when every Cluster that uses the plugin runs the new sidecar and is
healthy. On each cluster, each pod of a Cluster with the plugin shows the new sidecar tag (one without
it shows none), and each Cluster Cluster in healthy state:
kubectl --context <context> get pods -A -l cnpg.io/podRole=instance \
-o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name} {.spec.initContainers[?(@.name=="plugin-barman-cloud")].image}{"\n"}{end}'
kubectl --context <context> get clusters.postgresql.cnpg.io -A \
-o jsonpath='{range .items[*]}{.metadata.namespace}/{.metadata.name} {.status.phase}{"\n"}{end}'
Clusters wait up to 17 minutes after the plugin returns¶
Most of the delay after a plugin outage is the operator's backoff, not the plugin. In CNPG 1.30.1, a failed connection while the Cluster's plugins load (Error loading plugins, retrying, while getting plugin connection) returns an error from Reconcile (internal/controller/cluster_controller.go). That puts the Cluster on controller-runtime's per-object exponential backoff, which doubles from 5 ms up to 1000 s. Plugin errors raised later in the reconcile requeue after a fixed 15 s instead. No operator flag changes the backoff.
On 2026-11-07 (#2655) the operator's attempts for emiliero-db failed from 01:10:18 to 01:15:40, about 30 failures. The plugin served again from 01:15:47, and the next attempt came at 01:32:24, 1004 s later. Meanwhile the Cluster reports the phase Cluster cannot proceed to reconciliation due to an error while interacting with plugins. emiliero and keycloak-database health-check their Cluster, so their chains wait as long.
Once the plugin's endpoint is ready, any change to the Cluster object makes the operator retry at once. Its controller watches Cluster with no predicate (For(&apiv1.Cluster{})), and a watch event skips the backoff delay. This is a recovery write, so log it and remove the annotation afterwards. It has not yet been run during an incident. Both clusters run the plugin, so replace <context> with the context of the Cluster's cluster (rules of engagement, rule 8):
kubectl --context <context> -n cnpg-system get endpointslices -l kubernetes.io/service-name=barman-cloud \
-o jsonpath='{range .items[*].endpoints[*]}{.nodeName} {.conditions.ready}{"\n"}{end}'
kubectl --context <context> -n <ns> annotate cluster <name> skatzi.com/requeue="$(date -u +%FT%TZ)" --overwrite
kubectl --context <context> -n <ns> get cluster <name> -o jsonpath='{.status.phase}{"\n"}' # Cluster in healthy state
kubectl --context <context> -n <ns> annotate cluster <name> skatzi.com/requeue-
Operator upgrade gate¶
An operator upgrade restarts the instance pod of every CNPG Cluster: the operator config sets no ENABLE_INSTANCE_MANAGER_INPLACE_UPDATES, and every Cluster runs one instance, so each has a short outage. The cloudnative-pg-preupgrade Flux Kustomization is the operator's backup gate (Renovate ADR §11 item 1). Its health check is the Job cnpg-operator-preupgrade in cnpg-drill, and the cloudnative-pg Kustomization (the operator HelmRelease) dependsOn it. The Job runs components/cloudnative-pg/operator-preupgrade/preupgrade.sh, which:
- passes without doing anything when the CNPG API is not there yet, on a new cluster before the operator is installed;
- lists every
Clusteroutsidecnpg-drill. It fails if one archives to the backup store but is not inCLUSTERS, and only reports (WARNING: ... restarts unprotected) one without backups; - runs
drill.shwithMODE=preupgradefor each line ofCLUSTERS(<namespace> <cluster> <drill query>), one after another: an on-demandBackup, a restore intopreupgrade-<serverName>and the drill query. The first failure fails the gate, and the operator stays on its old chart. Each pass is recorded in ConfigMappreupgrade-<serverName>with itstargetVersion.
In CLUSTERS |
Owner |
|---|---|
terraform-state-db, mattermost-db, keycloak-db |
this repository |
tasks-db, tasks-prod-db |
Skatzi/taskbase |
emiliero-db |
Skatzi/emiliero |
The gate takes its own backup of Mattermost and Keycloak with the apps running. A CNPG backup is consistent without stopping them, and the operator upgrade does not change their data.
botyard-prod-db restarts unprotected. It has no backups, so the gate has nothing to back up or restore, and it only reports that Cluster. An operator upgrade restarts it like the others, but without a backup taken just before. Merging a CNPG chart upgrade accepts that until its owner (Dupondforge/botyard-control) adds backups and the Cluster is added to CLUSTERS.
Moving the target version. TARGET_VERSION in every cluster's gate Job, cluster/<cluster>/cloudnative-pg/preupgrade/job.yaml (hetzner-mgmt and webshop), is the chart version the operator HelmRelease is about to apply. A CNPG chart PR (Renovate's included) changes it in every gate Job to the new version in components/cloudnative-pg/base/helmrelease.yaml, in the same commit. components/cloudnative-pg/operator-preupgrade/test_preupgrade.py fails the PR while any of them differs. The new value changes the Job's pod template, so Flux recreates it (kustomize.toolkit.fluxcd.io/force: Enabled). The operator moves only after every listed Cluster has been backed up on the old operator and restored. The Job may take up to 4 hours (activeDeadlineSeconds, and the Kustomization's timeout).
To read the last pass and the gate's log:
kubectl --context admin@mgmt-cluster -n cnpg-drill get configmap preupgrade-terraform-state -o jsonpath='{.data}'
kubectl --context admin@mgmt-cluster -n cnpg-drill logs job/cnpg-operator-preupgrade
Why the gate does not deadlock. The gate needs cnpg-drill (the scratch namespace, drill.sh and the ObjectStore), which needs cnpg-barman-cloud. Those therefore must not wait for the operator. The namespace cnpg-system and the HelmRepository are in their own ungated Kustomization, cloudnative-pg-system (components/cloudnative-pg/system), and cloudnative-pg holds only the version-carrying HelmRelease. The order is cloudnative-pg-system → cnpg-barman-cloud → cnpg-drill → cloudnative-pg-preupgrade → cloudnative-pg → every Cluster. On a new cluster this converges: nothing before the operator applies a CNPG kind, and the gate passes at step 1.
When the operator is gone. Once the CNPG API exists, the gate needs a running operator: without one, its on-demand Backups never complete, the Job fails at its deadline, and cloudnative-pg (and every Cluster after it) waits for good. The CRDs outlive the operator (the chart keeps them), so this happens if the operator is uninstalled but the API stays. To recover, open a PR that removes cloudnative-pg-preupgrade from the dependsOn of cloudnative-pg in cluster/hetzner-mgmt/cloudnative-pg/kustomization.yaml, and wait for the operator HelmRelease to be Ready. Then delete the failed Job (kubectl --context admin@mgmt-cluster -n cnpg-drill delete job cnpg-operator-preupgrade), so Flux recreates it and it runs against the running operator, and revert that PR once the gate passes.
The namespace cnpg-system and the HelmRepository carry kustomize.toolkit.fluxcd.io/prune: disabled. They used to belong to the cloudnative-pg Kustomization, which would otherwise prune them while it still runs its old spec, and deleting the namespace uninstalls the operator. Removing them from Git therefore does not delete them; delete them by hand if that is ever the intent.
Gates share their scratch names. The operator gate and the image gates (this repository's, Taskbase's and Emiliero's) restore into the same preupgrade-<serverName> Cluster and record into the same ConfigMap. Two of them running at once delete each other's restore copies, so do not move the operator's TARGET_VERSION and an image gate's target_version in the same push, nor merge one while the other's Job runs. The Keycloak and Mattermost app gates back up the same Clusters too, so do not move one of them together with that Cluster's image gate or the operator's TARGET_VERSION either. A Taskbase or Emiliero image pull request is in its own repository, so the two cannot share a push: merge it only while cnpg-operator-preupgrade is not running, and the operator's chart pull request only while preupgrade-tasks-db, preupgrade-tasks-prod-db and preupgrade-emiliero-db are not.
Restoring by hand¶
Production data is restored into a new Cluster. CNPG never restores over a running Cluster. Use serverName to choose which backup history to read.
-
Pick a point in time, or leave
recoveryTargetout to replay to the latest archived WAL. To see the available backups: -
Create the restored Cluster next to the original, in a namespace that has the
backup-storeObjectStore:apiVersion: postgresql.cnpg.io/v1 kind: Cluster metadata: name: mattermost-db-restore namespace: mattermost spec: instances: 1 imageName: <the image of the original, from its status.image> storage: size: 10Gi bootstrap: recovery: source: origin # recoveryTarget: # targetTime: "2026-10-19 08:00:00+00" externalClusters: - name: origin plugin: name: barman-cloud.cloudnative-pg.io parameters: barmanObjectName: backup-store serverName: mattermost -
Check the data:
kubectl --context admin@mgmt-cluster -n mattermost exec mattermost-db-restore-1 -c postgres -- psql -d mattermost. - Switch the app to the restored Cluster's services (
mattermost-db-restore-rw), or dump and load the tables you need into the original. - To make the restored Cluster permanent, rename it in Git under its new name, and give it
pluginswith a newserverName(for examplemattermost-r1). The plugin refuses to archive into aserverNamethat already holds WAL, so the old history stays readable. Then delete the old Cluster.
The weekly drill does steps 1–3 for you in cnpg-drill. Its log shows the manifest it used.