What does Kubernetes need to know before it can run a database that fails over by itself?
CloudNativePG is an operator: a controller that keeps a PostgreSQL cluster in the state you declared, and handles failover, switchover, updates and backups.
Kubernetes is good at restarting stateless pods. A database is not stateless. If you run Postgres as a plain StatefulSet, Kubernetes will restart a dead pod, but it knows nothing about replication: which pod is the primary, which replica is furthest ahead, which old primary must not come back as a primary. CloudNativePG (CNPG) is an operator that teaches Kubernetes those rules.
Writes to one PostgreSQL primary, and the data behind it, while pods, nodes and zones come and go.
Automated failover and switchover, rolling updates that do the primary last, backups to object storage, and one YAML file that describes the whole cluster.
Most Postgres operators run an external failover tool such as Patroni. CNPG's FAQ says it relies on the Kubernetes API server as "the only source of truth" and does not rely on StatefulSets. See the Patroni chapter for the other design.
Not a backup by itself, and not cross-cluster failover. The docs say CNPG cannot do automated failover across Kubernetes clusters. Each operator manages its own cluster.
Pinned versions on this page: CloudNativePG 1.30.2 and PostgreSQL 18. Check the supported releases page of the CNPG docs for the Kubernetes versions it supports.
The first try is a StatefulSet with one primary pod and two replicas, plus a Service that selects the primary by label. It runs. Then the primary pod dies on a node that is gone for good.
SELECT pg_last_wal_replay_lsn(); on each.SELECT pg_promote();.primary_conninfo on the other replica and reload.pg_rewind or re-clone it, then add it back.Patroni solves this inside the pods, with a distributed store (etcd or the Kubernetes API) holding the leader key. It works well and is covered in the Patroni chapter. CNPG moves the same decisions into one Kubernetes controller.
Step through it:
You want one object that says "three PostgreSQL instances, this storage, these backups", and a controller that keeps it true when pods, nodes and disks fail.
You install the operator once per Kubernetes cluster. Then you create a Cluster resource (apiVersion: postgresql.cnpg.io/v1). The operator creates a PVC and a pod per instance, and manages the pods and volumes directly instead of through a StatefulSet. Inside each pod, an instance manager runs as PID 1, starts Postgres and serves the health probes.
CLUSTER-rw.-rw to it.| Service | Points to | Use it for |
|---|---|---|
CLUSTER-rw | The primary | All writes, and reads that must be current. |
CLUSTER-ro | Hot standby replicas only | Read-only traffic that can be a little behind. |
CLUSTER-r | Any instance | Read-only traffic when the primary may serve it too. |
Step through it:
Pinned: CloudNativePG 1.30.2, PostgreSQL 18, three instances. You need a Kubernetes cluster with at least three nodes in different zones and a StorageClass.
kubectl apply --server-side -f \ https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.30/releases/cnpg-1.30.2.yaml kubectl rollout status deployment -n cnpg-system cnpg-controller-manager
Helm installs name the deployment cnpg-cloudnative-pg instead.
orders.yaml:apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: orders
namespace: db
spec:
instances: 3
imageName: ghcr.io/cloudnative-pg/postgresql:18 # pin an exact tag in production
storage:
size: 20Gi
postgresql:
synchronous:
method: any
number: 1
failoverQuorum: true
primaryUpdateStrategy: unsupervised
primaryUpdateMethod: switchover
affinity:
enablePodAntiAffinity: true
topologyKey: topology.kubernetes.io/zone failoverQuorum: true makes the operator check, before it promotes, that the replica it picks cannot be missing a synchronous commit. If the check fails, no replica is promoted. primaryUpdateMethod: switchover makes rolling updates move the primary to the best replica. The default is restart, which restarts the primary pod in place when it can.
kubectl create namespace db kubectl apply -f orders.yaml kubectl krew install cnpg # the cnpg plugin, once kubectl cnpg status orders -n db kubectl get cluster -n db
apiVersion: barmancloud.cnpg.io/v1
kind: ObjectStore
metadata:
name: s3-store
namespace: db
spec:
configuration:
destinationPath: s3://my-backups/orders/
s3Credentials:
accessKeyId: {name: s3-creds, key: ACCESS_KEY_ID}
secretAccessKey: {name: s3-creds, key: ACCESS_SECRET_KEY}
wal:
compression: gzip
---
# add to the Cluster spec
plugins:
- name: barman-cloud.cloudnative-pg.io
isWALArchiver: true
parameters:
barmanObjectName: s3-storeapiVersion: postgresql.cnpg.io/v1
kind: Backup
metadata:
name: orders-first
namespace: db
spec:
cluster:
name: orders
method: plugin
pluginConfiguration:
name: barman-cloud.cloudnative-pg.io To restore, create a new Cluster with bootstrap.recovery.source set to an externalClusters entry that uses the same plugin, barmanObjectName and the original serverName. Restoring to a new cluster name is how you test a backup without touching production.
Connect with the app secret and the -rw service: orders-rw.db.svc. CNPG creates an application user and secret for you; read the secret names from kubectl get secret -n db.
Three instances, failoverDelay at its default of 0 seconds. The primary pod's disk fails.
Step through it:
Planned work uses a switchover, not a failure. kubectl cnpg promote orders orders-2 -n db moves the primary to a chosen instance. Rolling updates do replicas first, one pod at a time, and the primary last. With primaryUpdateStrategy: supervised the update pauses after the replicas so you finish it with promote or restart.
Kubernetes timing matters too. The docs mention the node monitor grace period (40 seconds on Kubernetes 1.29 to 1.31, 50 seconds on 1.32 and later) and a default 300 second pod eviction toleration, and say the operator does not wait for eviction to promote. The primary lease defaults are 15 seconds lease duration, 10 renew deadline and 2 retry period. So a failure with a sudden node loss can take longer than a clean pod delete. Measure it on your own cluster before you give it an RTO.
These use the kubectl cnpg plugin and plain kubectl. CLUSTER is the Cluster name.
kubectl cnpg status CLUSTER -n NS # summary, replication, backup, instance health; add -v for more kubectl cnpg promote CLUSTER INSTANCE -n NS # planned switchover to that instance (pod name or number) kubectl cnpg restart CLUSTER -n NS # rolling restart; primary last kubectl cnpg restart CLUSTER INSTANCE -n NS # restart one instance (a replica pod is deleted and recreated) kubectl cnpg reload CLUSTER -n NS # run a reconcile loop to pick up dependent config kubectl cnpg backup CLUSTER -n NS # create a Backup resource (on demand) kubectl cnpg psql CLUSTER -n NS -- -c "select 1" # psql on the primary; add --replica for a replica kubectl cnpg report cluster CLUSTER -n NS -f out.zip # bundle resources, events and (with --logs) logs for support kubectl cnpg maintenance set CLUSTER -n NS --reusePVC # node drain window; use unset to end it
kubectl cnpg fencing on CLUSTER INSTANCE_NUMBER -n NS # stop postgres in that pod, keep the pod; not ready kubectl cnpg fencing on CLUSTER "*" -n NS # fence the whole cluster kubectl cnpg fencing off CLUSTER "*" -n NS kubectl cnpg hibernate on CLUSTER -n NS # stop the cluster and keep the data kubectl cnpg hibernate off CLUSTER -n NS
Fencing a primary stops Postgres and does not fail over, so apps see an outage. Fence a primary only when you must. Hibernation sets the cnpg.io/hibernation=on annotation. Neither one is the same as pausing the operator, and the agent does not offer a pause for CNPG.
There is no manual rejoin step for a normal case: a failed instance is recreated and rejoins as a replica. If a pod is stuck in a crash loop, fence it, fix the cause, then unfence it. Deleting a fenced pod recreates it with the postmaster not started, which helps with CrashLoopBackOff.
kubectl get pods -n NS -l cnpg.io/cluster=CLUSTER kubectl describe cluster CLUSTER -n NS kubectl logs -n NS POD -c postgres
| Symptom | Likely cause | First check | Fix |
|---|---|---|---|
| Failover does not happen after the primary dies | failoverQuorum blocked it, no healthy replica, or the lease has not expired yet. | kubectl cnpg status, describe cluster, operator logs in cnpg-system. | Wait for the lease, restore a replica, or as a last resort kubectl cnpg promote, which can lose data. The docs call it a last resort. |
| Cluster stuck during update | Supervised strategy waiting for you, or a replica not ready. | Cluster status phase, pod readiness. | Finish with promote or restart. For image changes you need a switchover. |
| Replica far behind | Slow disk, long query, network, or WAL not retained. | status -v replication section. | Fix the bottleneck. A replica that cannot catch up is re-cloned from the primary. |
| Backups fail or WAL archive lags | Bad credentials, bucket permissions, plugin not installed or not running. | Backup resource status, status backup section, plugin pod logs. | Fix the secret or policy. An archive that is behind grows WAL on the primary's disk. |
| Primary disk fills | WAL kept for a broken archive or a stuck replication slot. | Disk use on the PVC. | Fix archiving, then grow the PVC if your StorageClass allows it. |
| App sees errors during failover | Connections to the old primary drop. | App logs, pool settings. | Retry with backoff and use the -rw name. A pooler such as PgBouncer (CNPG has a Pooler resource) can hold connections, but the app still retries. |
| Operator down | Deployment crash, bad upgrade, RBAC. | kubectl get deploy -n cnpg-system | Databases keep running. Restore the operator before you need a failover. |
| Nodes lost in one zone | Instances were not spread across zones. | Pod placement. | Use anti-affinity across zones, and three or more instances. |
CNPG exposes a Prometheus metrics endpoint on each instance. The docs name one metric you can rely on for fencing, cnpg_collector_fencing_on, which is 1 while a pod is fenced. For the rest, scrape the instance pods and the operator, and start from the dashboards and alert rules that the project publishes.
| Signal | Where | Alert when |
|---|---|---|
| Cluster phase and ready instances | kubectl cnpg status, kube-state-metrics on the Cluster resource | Not all instances ready for more than a few minutes. |
| Failover and switchover events | Kubernetes events on the Cluster | Any failover. |
| Replication lag, WAL receiver state | Postgres metrics on each instance | Lag above your RPO. |
| WAL archive status, last backup time | Plugin and Backup resources | No successful backup in your window, archive failing. |
cnpg_collector_fencing_on | Instance metrics | Any instance fenced longer than planned. |
| PVC use | kubelet and storage metrics | Above 80 percent. |
| Operator health | cnpg-system deployment | Not running. |
See also Patroni, Something is slow or broken and, for fleets, running 1,000 databases.
Every change is shown to you first and runs only after you type an approval. Reads run straight away.
python3 -m dbagent.ha k8s status --kind cnpg --name CLUSTER -n NAMESPACE python3 -m dbagent.ha k8s switchover --kind cnpg --name CLUSTER --to POD python3 -m dbagent.ha k8s restart --kind cnpg --name CLUSTER
switchover is a planned move of the primary. restart is the rolling restart. There is no pause for CNPG: hibernation and fencing are different things, and the docs describe no operator pause, so the agent does not offer one.
How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.