Architecture

Running PostgreSQL highly available on Kubernetes: CloudNativePG in the enterprise

·Architecture·15 min read

Getting a database to start on Kubernetes takes a few minutes. Keeping it available through the loss of a node, a data centre or an entire region is a different matter. Database instances are not interchangeable: one of them accepts writes, the others follow it, and when something fails, somebody has to decide which instance takes over. Kubernetes does not make that decision on its own.

An operator fills the gap. It is a controller that brings operational knowledge about the database into the cluster as a control loop. For PostgreSQL, CloudNativePG has become the established choice; it is an Incubating project of the Cloud Native Computing Foundation. This article walks through what running it involves from an enterprise point of view, organised the way platform teams tend to think about it: what has to be in place beforehand (day 0), getting the first cluster and its data in (day 1), and everything that follows (day 2).

Note

Everything here refers to CloudNativePG 1.30.2, released on 17 November 2026, and is taken from the original documentation of that version. It supports Kubernetes 1.34 to 1.36 and PostgreSQL 15 to 18.

The diagram shows the target architecture that the rest of the article refers to.

Highly available PostgreSQL on Kubernetes with CloudNativePG Highly available PostgreSQL on Kubernetes One CloudNativePG cluster across three zones, a WAL archive, and a replica cluster in a second region KUBERNETES CLUSTER · REGION A · THREE AVAILABILITY ZONES CloudNativePG operator watches the Cluster resource, creates Pods, PVCs and Services Services orders-db-rw → the primary orders-db-ro → the replicas Applications connect to the Service name, optionally through a Pooler ZONE A orders-db-1 replica · hot standby may be promoted PVC · PGDATA its own volume, nothing shared PVC · WAL separate volume for the log ZONE B orders-db-2 primary · reads and writes holds the cluster's Lease PVC · PGDATA its own volume, nothing shared PVC · WAL separate volume for the log ZONE C orders-db-3 replica · hot standby may be promoted PVC · PGDATA its own volume, nothing shared PVC · WAL separate volume for the log Streaming replication inside the cluster · automated failover Synchronous with ANY 1: a commit is confirmed only once a replica in another zone has it. If the primary fails, the operator promotes a replica. OBJECT STORE · OUTSIDE BOTH CLUSTERS WAL archive continuous, at least every 5 minutes (RPO ≤ 5 min) Base backups scheduled, taken from a standby SECOND KUBERNETES CLUSTER · REGION B Replica cluster a designated primary and its replicas, read-only, following region A through the WAL archive, streaming or both Its own operator has no authority beyond this cluster Promotion is a decision, not an automatism a change to the manifests, made by people

How CloudNativePG is put together

The desired state of a database lives in a resource of kind Cluster. From it, the operator creates the instances: one primary, which accepts reads and writes, and any number of replicas, which follow it through PostgreSQL's own streaming replication and can serve read traffic.

Three design choices set CloudNativePG apart from a hand-rolled StatefulSet.

  • The operator manages Pods and volumes directly. It does not use a StatefulSet. Every instance gets its own PersistentVolumeClaim, and no instance shares storage with another (shared nothing). Replication is left to PostgreSQL, and the documentation explicitly advises against replicating at the storage layer.
  • State lives in Kubernetes. CloudNativePG does not ship a consensus store of its own. Which instance is the primary is recorded in the API server and, since version 1.30, additionally guarded by one Lease object per cluster.
  • Applications talk to Services. The Service <name>-rw always points at the current primary, <name>-ro at the replicas and <name>-r at all instances. After a failover, nothing changes for the application apart from a dropped connection.

Day 0: what the platform has to provide

The operator alone does not make a database highly available. The platform underneath has to meet a number of requirements, and they are best settled before the first installation.

Three availability zones. The documentation recommends a Kubernetes cluster that spans at least three zones. The reason is the control plane: only with three sites does it survive the loss of one, and without a control plane the operator cannot fail anything over either.

Dedicated worker nodes for PostgreSQL. Databases should not share nodes with arbitrary workloads. The documentation recommends the label and taint node-role.kubernetes.io/postgres, and a node count that is a multiple of three, ideally one node per zone.

Spreading as a hard rule. By default, the operator tries to place the instances on different nodes but does not enforce it. In production, the anti-affinity should be mandatory (podAntiAffinityType: required) and refer to the zone (topologyKey: topology.kubernetes.io/zone).

Guaranteed resources. For PostgreSQL, the documentation recommends the "Guaranteed" QoS class, which means setting requests and limits for CPU and memory to the same values. As a starting point for shared_buffers, it suggests 25 percent of the memory.

Storage that has been tested. CloudNativePG works with any StorageClass. For write-heavy and very large databases, local storage is the better fit, because network storage varies in throughput and latency. A separate volume for the write-ahead log (walStorage) keeps the two I/O profiles apart; once added, it cannot be removed. The StorageClass should allow volume expansion, and a benchmark belongs before any production use. The kubectl plugin helps with kubectl cnpg fio and kubectl cnpg pgbench.

An object store outside the cluster. It holds the WAL archive and the backups, and every recovery scenario depends on it.

Important

Only the current minor version of the operator is supported, and of that only the latest patch release. A new minor version appears roughly every two to three months, and the support window is about half a year. Version 1.30 is expected to reach end of life in March 2027. Adopting CloudNativePG therefore means committing to regular operator upgrades, and they should be planned as a routine part of operations from the start.

Day 1: installing the operator and the first cluster

The installation has three parts: the operator, the backup plugin and the database itself.

The operator is installed from a single manifest. A Helm chart and the Operator Lifecycle Manager are available as alternatives.

# Install the operator into the cnpg-system namespace
kubectl apply --server-side -f \
  https://raw.githubusercontent.com/cloudnative-pg/cloudnative-pg/release-1.30/releases/cnpg-1.30.2.yaml

# Wait until the operator is ready
kubectl rollout status deployment -n cnpg-system cnpg-controller-manager

For backups and the WAL archive, the Barman Cloud Plugin is the intended route. It is installed in the same namespace as the operator and needs certificates to secure its communication with the operator, which cert-manager issues most conveniently. The object store is described by a resource of kind ObjectStore:

apiVersion: barmancloud.cnpg.io/v1
kind: ObjectStore
metadata:
  name: orders-backup
spec:
  configuration:
    destinationPath: s3://backups-orders/
    s3Credentials:
      accessKeyId:
        name: backup-credentials
        key: ACCESS_KEY_ID
      secretAccessKey:
        name: backup-credentials
        key: ACCESS_SECRET_KEY
    wal:
      compression: gzip

The database itself is a resource of kind Cluster. The following example puts the day-0 requirements into practice:

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
  name: orders-db
spec:
  instances: 3
  imageName: ghcr.io/cloudnative-pg/postgresql:18.7-system-trixie

  storage:
    storageClass: fast-local
    size: 200Gi
  walStorage:
    size: 50Gi

  resources:
    requests:
      memory: 8Gi
      cpu: "2"
    limits:
      memory: 8Gi
      cpu: "2"

  postgresql:
    parameters:
      shared_buffers: 2GB
    synchronous:
      method: any
      number: 1
      dataDurability: required
      failoverQuorum: true

  affinity:
    podAntiAffinityType: required
    topologyKey: topology.kubernetes.io/zone
    nodeSelector:
      node-role.kubernetes.io/postgres: ""
    tolerations:
      - key: node-role.kubernetes.io/postgres
        operator: Exists
        effect: NoSchedule

  plugins:
    - name: barman-cloud.cloudnative-pg.io
      isWALArchiver: true
      parameters:
        barmanObjectName: orders-backup

The image is pinned to a specific version on purpose. The documentation advises against the latest tag and also supports pinning by digest. Teams that run many databases maintain their images centrally in an ImageCatalog or ClusterImageCatalog; a change there rolls the new image out to every cluster that uses the catalog.

Day 1: moving existing data in

Few databases start from scratch. For moving an existing PostgreSQL database in, whether from a virtual machine or from a managed service, there are two supported routes.

Offline, by import. The new cluster is created with bootstrap.initdb.import and pulls the data from the source using pg_dump and pg_restore. The microservice type takes a single database, the monolith type several databases along with their roles. The source may run an older major version, so migration and version upgrade can be done in one go. Writes to the source have to stop for the duration of the import, which means the downtime grows with the size of the database.

# Excerpt from the Cluster resource
bootstrap:
  initdb:
    import:
      type: microservice
      databases:
        - orders
      source:
        externalCluster: legacy-orders

Online, by logical replication. For large databases with a short maintenance window, logical replication is the right tool. CloudNativePG models it declaratively with the Publication and Subscription resources. The procedure has four steps:

  1. The schema is brought over with a schema-only import (schemaOnly: true), because logical replication does not carry schema changes.
  2. A Publication on the source and a Subscription in the new cluster start the data transfer, while the source stays in production.
  3. Shortly before cutover, the sequences are synchronised (kubectl cnpg subscription sync-sequences), since logical replication does not carry those either.
  4. The applications are stopped, pointed at the new cluster and started again.

A third route, a physical copy taken with pg_basebackup from an instance outside Kubernetes, requires the same major version and the same hardware architecture. The documentation does not endorse it for migrations and recommends the logical import instead.

Day 2: upgrades without surprises

Four kinds of change come up in day-to-day operation, and CloudNativePG handles all of them with the same pattern, the rolling update: the operator updates the replicas first, one at a time, and the primary last.

Changes to the database. A new image, changed resources or a parameter that requires a restart all trigger a rolling update. Two settings control what happens to the primary. primaryUpdateMethod determines whether it is restarted (restart, the default) or whether a replica takes over first (switchover). primaryUpdateStrategy determines whether that happens automatically (unsupervised, the default) or whether the operator pauses after the replicas until someone approves the final step (supervised). In regulated environments, supervised fits well with a maintenance window and a four-eyes sign-off.

Operator upgrades. This is the one that most often catches teams off guard. Upgrading the operator also updates the instance manager inside every database Pod, and so by default it triggers a rolling update of every cluster, each ending in a switchover. Two operator settings take the edge off: CLUSTERS_ROLLOUT_DELAY and INSTANCES_ROLLOUT_DELAY spread the rollout over time, and ENABLE_INSTANCE_MANAGER_INPLACE_UPDATES updates the instance manager without restarting PostgreSQL. Operator minor versions should be applied in sequence and not skipped.

Node maintenance. The operator creates PodDisruptionBudgets for every cluster. When the primary's node is drained, the operator performs a switchover first, and only one replica is ever shut down at a time. A Kubernetes upgrade therefore goes through without anyone touching the database.

New PostgreSQL versions. A new minor version is an ordinary rolling update with a new image. For a new major version, CloudNativePG offers three routes:

  • In place with pg_upgrade, available since version 1.26. The major version is changed in the image; the operator shuts down all instances, runs the upgrade in a job and rebuilds the replicas. The whole cluster is unavailable while this runs. A fresh base backup is needed afterwards, because point-in-time recovery does not work across major versions.
  • Logical import into a new cluster: offline, blue-green.
  • Logical replication into a new cluster: online, also blue-green.

Day 2: failover inside a cluster

Automated failover within a Kubernetes cluster is the heart of high availability, and it happens in two steps. First, the operator marks the primary as due for replacement and forces it to shut down, so that no replica is still receiving data from it. Then it picks the replica that is furthest ahead as the new primary and promotes it. The Service <name>-rw now points at the new instance. If the former primary comes back, it rejoins as a replica.

Three questions determine how well this matches the requirements.

How quickly is the failure detected? If PostgreSQL or the Pod crashes, the readiness probe fails and the operator reacts once failoverDelay has elapsed, which by default means immediately. If an entire node goes down, detection depends on Kubernetes: the node is considered unreachable after roughly 40 to 55 seconds, and only then does the failover begin. That time has to go into any calculation of the recovery time objective (RTO).

Can data be lost? By default, PostgreSQL replicates asynchronously, and the most recent transactions may be missing after a failure. Synchronous replication prevents that: with method: any and number: 1, the primary confirms a commit only once at least one replica has received it. The dataDurability setting decides what happens when no replica is reachable. With required, the primary pauses writes until a replica confirms again. That guarantees zero data loss (RPO = 0) at the expense of availability. With preferred, the primary carries on alone if it has to, which preserves availability and accepts data loss in that situation. This is a business decision, and it should be made together with the people who own the application.

Can there be two primaries? Three mechanisms stand in the way. The Lease ensures that only one instance holds the primary role. Since version 1.27, every primary also checks whether it can still reach the API server or any other instance, and an isolated primary shuts itself down. And with failoverQuorum: true, the operator promotes a replica only when it is certain to contain every synchronously confirmed transaction.

Tip

A failover should be rehearsed before it is needed. kubectl cnpg promote triggers a planned switchover, and deleting the primary Pod in a test environment shows how the applications cope with a dropped connection. In practice, high availability fails more often because applications do not reconnect than because of the database.

Day 2: backup and recovery

Replication is not a backup. A table dropped by mistake is gone from every replica seconds later. CloudNativePG therefore combines two building blocks.

The first is the WAL archive. The primary ships its write-ahead log to the object store continuously, and at least every five minutes even under light load. Out of the box, that caps data loss in a disaster at five minutes, even across regions.

The second is base backups, which are full physical copies. They are taken while the database is running and, by default, from a replica, so the primary carries no extra load. A resource of kind ScheduledBackup puts them on a schedule:

apiVersion: postgresql.cnpg.io/v1
kind: ScheduledBackup
metadata:
  name: orders-db-weekly
spec:
  # Six fields, the first one is seconds: Sundays at 02:00
  schedule: "0 0 2 * * 0"
  backupOwnerReference: self
  cluster:
    name: orders-db
  method: plugin
  pluginConfiguration:
    name: barman-cloud.cloudnative-pg.io

According to the documentation, a weekly base backup is enough in most cases, because the WAL archive covers the time in between. For very large databases, volume snapshots are the preferred alternative to the object store, as they can be incremental depending on the storage system.

A recovery never overwrites an existing cluster. It always creates a new cluster from a backup, optionally up to a specific moment (point-in-time recovery). That protects the existing data and makes it possible to check a restore alongside production.

# Excerpt from the resource of the new cluster
bootstrap:
  recovery:
    source: orders-db
    recoveryTarget:
      targetTime: "2026-11-26 08:55:00+01"
externalClusters:
  - name: orders-db
    plugin:
      name: barman-cloud.cloudnative-pg.io
      parameters:
        barmanObjectName: orders-backup
        serverName: orders-db

Warning

The object store integration built into the operator (spec.backup.barmanObjectStore) has been deprecated since version 1.26. Version 1.31 is the last one to include it, and it is removed in version 1.32, which is announced for March 2027. Existing installations have to be moved to the Barman Cloud Plugin by then. Existing backups remain usable with the plugin.

Day 2: disaster recovery across clusters

Automated failover stops at the boundary of the Kubernetes cluster. For the loss of an entire region, or for operating out of two data centres, CloudNativePG provides the replica cluster: a self-contained cluster in a second Kubernetes cluster that continuously follows the first. It receives changes from the WAL archive, through streaming replication or both, and it can serve read traffic.

Both clusters describe the same topology and differ only in which of them they name as the primary:

# Excerpt from the cluster in region B
replica:
  self: orders-db-region-b
  primary: orders-db-region-a
  source: orders-db-region-a

There are two ways to swap the roles.

A planned switchover loses no data and takes two steps. First, the current primary is demoted by naming the other cluster as primary in its resource. The operator shuts it down cleanly and writes a token into its status. Then the other cluster is told that it is the primary and handed that token. It waits until it has reached exactly the state the token describes and takes over. The former primary then follows it without having to be rebuilt.

A failover in a disaster is a promotion without the token. It is what remains when the first region can no longer be reached. The replica cluster becomes primary immediately. Transactions that had not yet reached it are lost, and the former primary has to be rebuilt when it returns.

The documentation leaves no room for doubt here: CloudNativePG performs no automated failover across clusters, because an operator has no authority beyond its own Kubernetes cluster. The decision is made by a person or by a higher-level system. This is by design. Without a third site, two sites cannot tell whether the other one is down or merely unreachable. In a GitOps setup, the switch is a commit. The runbook that goes with it, including repointing the applications and DNS, needs to be written down and practised regularly.

Day 2: monitoring

Every instance exposes its metrics in Prometheus format on port 9187, the operator on port 8080. For scraping, the documentation recommends a PodMonitor that the team creates itself; the former enablePodMonitor setting is deprecated.

apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: orders-db
spec:
  selector:
    matchLabels:
      cnpg.io/cluster: orders-db
  podMetricsEndpoints:
    - port: metrics

For high availability, a handful of metrics matter most:

  • cnpg_pg_replication_lag shows how far a replica is behind.
  • cnpg_pg_replication_streaming_replicas shows how many replicas are following the primary.
  • cnpg_collector_sync_replicas compares the expected with the observed number of synchronous replicas.
  • cnpg_pg_stat_archiver_last_failed_time and cnpg_collector_pg_wal_archive_status show whether the WAL archive is working. A stalled archive puts recovery at risk and fills up the WAL volume.
  • cnpg_collector_fencing_on and cnpg_collector_manual_switchover_required flag states in which the operator is waiting for someone to step in.

The project provides a Grafana dashboard and a sample set of alerting rules, including rules for a replication lag of more than 300 seconds and for failed archiving. The documentation is explicit that these are examples. The thresholds have to be derived from the organisation's own RPO and RTO targets.

CloudNativePG writes its logs as JSON to standard output, so any common log pipeline can pick them up. For audit requirements, PGAudit is supported; the operator sets up the extension as soon as the corresponding parameters are configured.

Security and access

Several defaults already match what an enterprise expects. Connections are encrypted with TLS, and the operator requires TLS 1.3 by default. It issues the certificates itself and renews them without interruption; alternatively, certificates from the organisation's own PKI can be plugged in, for example through cert-manager. Superuser access over the network is switched off by default, and the application receives its credentials through a Secret named <name>-app. The containers run without root privileges and with a read-only file system.

Two topics remain the platform team's responsibility. CloudNativePG leaves encryption at rest to the storage system, and NetworkPolicies have to be defined by the platform.

For applications with many short-lived connections, the Pooler resource puts PgBouncer in front of the database. The pooler runs as a Deployment of its own with several instances and follows the primary automatically on failover.

The bottom line

CloudNativePG turns running a PostgreSQL database into a declaration: one resource describes instances, storage, replication and backup, and the operator continuously reconciles the cluster against it. Within a Kubernetes cluster that spans three zones, it handles failover automatically and, with synchronous replication, without losing data.

Three decisions remain with the organisation. The first is the topology: three zones for automated failover, and a second cluster for disaster recovery. The second is the trade-off between data safety and availability in synchronous replication. The third is the procedure for switching between regions, which deliberately stays a human decision.

An organisation that has settled these three points, plans for the operator's support window, and rehearses failover and recovery on a regular basis runs PostgreSQL on Kubernetes at a level that comes close to managed database services, while keeping control over versions, configuration and data.

Comments

Write a comment

Loading the form …


Back to the index