Running relational databases inside Kubernetes is no longer taboo. StatefulSets, CSI storage drivers, and high-availability operators have made containerized PostgreSQL routine. In a standard setup, teams deploy one writable primary with several replicas, configure Patroni, and trust automatic failover: if the primary stops passing health checks, the operator promotes a replica and reroutes traffic.
On paper, this looks airtight. In production, however, cross-Availability-Zone (AZ) network degradation in a public cloud can turn a routine glitch into lost committed transactions and split-brain. A detailed engineering study by Datadog explains why naive HA setups fail at the worst possible moment—and how to design a cluster that guarantees zero data loss (RPO = 0).
The Asynchronous Failover Trap Under Network Degradation
By default, PostgreSQL uses asynchronous streaming replication. When a client issues COMMIT, the primary writes the transaction to its local Write-Ahead Log (WAL), flushes it to disk, and immediately confirms success to the client. Meanwhile, wal_sender streams those records to replicas in the background.
When the network is healthy, replication lag stays within milliseconds and a few bytes of Log Sequence Number (LSN) difference. Things change fast during chaos drills (Gamedays) or real network storms.
Datadog engineers simulated packet loss and rising latency between two AZs. The primary kept committing transactions locally and piling up WAL, while replicas fell further behind. When the link between zones finally snapped, Patroni tried to fail over—and hit its maximum_lag_on_failover safety guard (often set to a 1 MB threshold by default).
That created a deadlock:
- The primary was isolated by the network partition and unreachable for client traffic;
- Every available replica lagged beyond the allowed threshold;
- Patroni blocked promotion of any lagging replica to prevent data rollback;
- The cluster froze without a writable node, forcing on-call engineers to intervene manually in the middle of the night.
Disabling that lag guard would have been even worse: a lagging replica would become primary and drop recent commits. Once the network healed, the old primary would still think it was the leader. Accepting writes on two independent nodes creates a classic split-brain, which cannot be untangled without manual dump inspection and broken data integrity. These automatic failover risks require rethinking cluster topology from the ground up.
Separating Roles: Leader Pool vs. Read Replicas
To eliminate desynchronization, Datadog split PostgreSQL nodes into two isolated pools with distinct jobs:
- Leader Pool (HA Pool): consists of exactly three PostgreSQL instances—one active writable leader and two synchronous standby nodes. These pods are spread across three separate AZs using
podAntiAffinity. Their sole job is reliable writes and instant, safe failover; they never serve user read queries. - Read Replica Pool (Scaling Pool): any number of asynchronous replicas attached to the primary for heavy analytics, reporting, and read-only APIs. These nodes are excluded from leader elections and never participate in failover quorum.
This separation keeps heavy read traffic from slowing down replication inside the high-availability core.
Inside Patroni: DCS, Leader Leases, and Fencing
Patroni coordinates the cluster through a Distributed Configuration Store (DCS)—ZooKeeper (or etcd) in this architecture.
Leadership relies on a lease mechanism backed by ephemeral znodes and session timers. The active primary must renew its leader lock in the DCS every loop_wait seconds (typically 10 s). If the primary is partitioned from the network, its lease expires after the ttl interval (typically 30 s).
At that point, two critical safeguards kick in:
- Self-demotion / Fencing: as soon as the local Patroni daemon on the primary loses contact with ZooKeeper past the timeout, it immediately switches PostgreSQL to
read-onlymode or terminates the process (SIGTERM/SIGQUIT), stopping isolated local writes. - Timeline rewind via
pg_rewind: when the old primary rejoins the network, its transaction timeline has diverged from the newly elected leader. Patroni automatically runspg_rewind, which scans WAL page headers from the point of divergence, rolls back modified data blocks to a consistent state, and puts the node back into streaming catch-up without copying terabytes viapg_basebackup.
Synchronous Commit Levels: The Cost of RPO = 0
To ensure at least one standby in the Leader Pool always holds up-to-date data, the cluster uses synchronous streaming replication (synchronous_mode: true). This introduces a core trade-off between latency, throughput, and durability.
Engineering diagram comparing four PostgreSQL synchronous commit modes with WAL stages and a zero-data-loss indicator for remote_apply.
PostgreSQL's synchronous_commit parameter controls exactly when the primary acknowledges a transaction:
local: confirms right after flushing WAL to the primary's local disk. Fastest option, but risks losing data if the primary crashes.remote_write: waits until a replica receives the WAL over the network and writes it to OS buffers (withoutfsync). Protects against a PostgreSQL process crash on the replica, but not simultaneous power loss across hosts.on(orremote_flush): waits until the replica physically flushes the WAL to disk (fsync). This is the standard durability guarantee.remote_apply: the strictest mode. The primary confirms the commit only after the replica both flushes the WAL to disk and replays the changes into memory and table files. Data becomes immediately visible for reads on the replica with zero lag.
Datadog ran pgbench load tests (TPC-B, 100,000 transactions) to measure the overhead against the local baseline:
synchronous_commit Mode | Avg. Latency Increase | Throughput Drop (TPS) |
|---|---|---|
remote_write | +38% | -27% |
on (remote_flush) | +46% | -31% |
remote_apply | +53% | -34% |
A 53% latency jump looks alarming in synthetic benchmarks. In production, however, with inter-AZ network latency around 1–2 milliseconds, end-to-end application response times rose by only a few milliseconds. Most services barely notice it, while gaining a firm guarantee that no single-node failure can lose committed data.
Practical Example: Patroni Configuration and Operations
Here is a production-style Patroni configuration enabling strict synchronous mode in Kubernetes:
scope: postgres-ha-cluster
namespace: /service/postgres
# Distributed consensus integration (ZooKeeper / etcd)
zookeeper:
hosts: ['zk-0.zk-hs:2181', 'zk-1.zk-hs:2181', 'zk-2.zk-hs:2181']
# Strict synchronous replication and quorum failover settings
synchronous_mode: true
# Block writes if standbys fail, preventing split-brain
synchronous_mode_strict: true
synchronous_node_count: 1
# Maximum allowed lag for replica promotion (1 MB)
maximum_lag_on_failover: 1048576
postgresql:
parameters:
wal_level: replica
hot_standby: "on"
# Durability guarantee: commit only after replica replay
synchronous_commit: "remote_apply"
max_wal_senders: 10
max_replication_slots: 10
pg_hba:
- host replication replicator 0.0.0.0/0 md5
synchronous_mode_strict: true is the linchpin here. If both standby nodes go down at once, Patroni sets synchronous_standby_names to *, intentionally blocking writes on the primary. Applications see a transaction timeout error instead of silently writing data that could later vanish.
You can inspect cluster topology, check sync status, and update settings on the fly with patronictl:
# 1. Check current leader, replicas, and Sync Standby status
patronictl -c /etc/patroni/patroni.yml list
# 2. Inspect cluster configuration stored in DCS
patronictl -c /etc/patroni/patroni.yml show-config
# 3. Update configuration dynamically without restarting PostgreSQL
patronictl -c /etc/patroni/patroni.yml edit-config --set synchronous_mode=true
# 4. Verify synchronous replication wait state in PostgreSQL via psql
# SELECT pid, application_name, client_addr, sync_state, sync_priority FROM pg_stat_replication;
Production HA Checklist
When building high-availability PostgreSQL on Kubernetes, keep these rules in place:
- Spread nodes physically: enforce
topologySpreadConstraintsorpodAntiAffinityby zone (topology.kubernetes.io/zone) so the primary and synchronous standbys never share a datacenter; - Isolate the DCS: run at least three etcd or ZooKeeper nodes outside the worker nodes hosting database pods;
- Monitor
SyncRepwaits: track synchronous replication wait events inpg_stat_activity—rising waits warn you about inter-AZ network degradation long before an outage hits; - Run regular chaos drills: test node power-offs and network partitions on realistic data volumes.
Fault tolerance in distributed systems is always a deliberate trade-off. Giving up a third of write throughput for synchronous replay buys a predictable, resilient database ready for cloud infrastructure storms.

