When PostgreSQL Failover Becomes Unsafe: How Datadog Rebuilt High Availability on Kubernetes and PatroniLongread · digest for November 25
Isometric architectural model of a high-availability PostgreSQL cluster in Kubernetes managed by Patroni, showing a writer node and synchronous replicas.
Longread6 sections≈ 19 min

When PostgreSQL Failover Becomes Unsafe: How Datadog Rebuilt High Availability on Kubernetes and Patroni

Picture a routine game-day drill in a staging environment. Datadog engineers run these exercises regularly. They intentionally break a piece of infrastructure to spot weak points before a real incident hits on a Friday night. That day, the scenario looked familiar: simulating an availability zone outage. They injected high network latency into one zone that happened to host the primary nodes of several PostgreSQL clusters on Kubernetes.

In theory, automation should have taken over right away. The clusters run on Patroni and ZooKeeper, standby nodes are ready, and leader failover is configured. Instead of a clean failover, the worst happened: the clusters simply froze.

Network latency spiked, and primary nodes lost stable connections to their replicas. Meanwhile, the primaries kept accepting writes as if nothing had happened. Replication lag shot up, writes started stalling, and apps began serving stale data to users. When Patroni tried to fail over to a standby node, it checked every candidate's lag and flatly refused to promote any of them.

The cluster was trapped. The old leader was choking in a degraded zone, and no replica was safe to promote. The only way out without losing data was to wait for the network to recover so replicas could catch up on the transaction log.

Why an Asynchronous Cluster Stalls During Network Degradation

To see why automation hit the brakes so hard, let's look inside PostgreSQL streaming replication. The primary node writes every database change to the Write-Ahead Log (WAL) and streams those records to replicas. Replicas apply the log locally to stay in sync with the leader.

By default, PostgreSQL uses asynchronous replication. It's built for speed: a client sends COMMIT, the primary writes the record locally, and immediately replies with success. The leader doesn't wait for the WAL packet to reach replicas and get written there. For everyday traffic, this works great: write latency stays low and throughput stays high.

The trouble starts when the network degrades. At Datadog, the primary kept confirming transactions even though traffic to replicas was barely crawling through the slow availability zone. As a result, the leader raced ahead while replicas were left with a huge backlog of unapplied WAL records.

Before promoting a standby to become the new leader, Patroni runs a mandatory safety check using maximum_lag_on_failover. This threshold is set in WAL bytes and caps how far behind a candidate can be. If a replica lags past that limit, Patroni won't promote it. Otherwise, any transactions committed on the old leader that never reached the replica would vanish.

During the drill, all standby nodes crossed that threshold. Patroni did the right thing: it protected data integrity instead of faking a green status on a dashboard. The real flaw sat in the original setup. Under network degradation, asynchronous replication put write availability ahead of data durability, leaving the cluster with no safe path to recover.

Base Architecture: Two Pools, Patroni, and ZooKeeper

At Datadog, PostgreSQL runs on Kubernetes using a classic single-writer model. To keep heavy analytical or user read queries from slowing down writes, each cluster is split into two logical pools.

The first contour is the leader pool. It holds one active writer node and two standby nodes. Application traffic never hits those two standbys. Their only job is to keep a fresh copy of the database and stay ready to take over as leader at any moment.

The second contour is the read replica pool. Several nodes run here solely for read traffic. You can scale them independently when SELECT load grows, and they isolate heavy queries from the writer node. These nodes are deliberately excluded from leader elections using the nofailover: true tag.

High-availability PostgreSQL architecture on Kubernetes with Patroni and ZooKeeper: leader pool and read replica pool (Source: Datadog Engineering Blog)

Patroni and Apache ZooKeeper coordinate the whole setup. ZooKeeper acts as the Distributed Configuration Store (DCS). It holds the current leader lock key, shared dynamic cluster settings, and the replication status of each member, including the latest LSN (Log Sequence Number, the position in the WAL).

Starting a new node works in a clean, predictable way. When a database pod comes up in Kubernetes, Patroni first checks ZooKeeper for an active leader. If the leader key is free, the node tries to create an ephemeral znode lock. ZooKeeper guarantees that only one member can create this key, which prevents two leaders from appearing at once. If a leader already exists, the new node configures itself as a replica and starts streaming replication.

During a network partition, this caution prevents split-brain, where two nodes both think they are primary and accept conflicting writes. A replica that loses contact with the leader or ZooKeeper pauses instead of blindly grabbing control. If the leader itself drops off, its ephemeral key in ZooKeeper expires after ttl. The lock clears, an eligible standby claims leadership, and it becomes the new primary.

PostgreSQL failover sequence under Patroni and ZooKeeper during a network partition (Source: Datadog Engineering Blog)

When the old leader finally comes back online, it tries to renew its key, gets rejected by ZooKeeper, demotes itself to standby, and reconnects to the new leader as a replica. Under normal conditions, this ran like clockwork until the drill exposed its weak spot: if replicas fall too far behind right before a disconnect, nobody can safely take over leadership.

Hybrid Replication and Key Patroni and PostgreSQL Settings

Switching every replica in the cluster to synchronous mode would be a bad fix. Forcing the writer to wait for confirmations from a dozen busy read replicas would kill write performance. Instead, Datadog engineers built a hybrid setup.

They moved the standby nodes inside the leader pool to strict synchronous replication managed by Patroni. Now, before returning a commit confirmation to the app, the leader waits for an acknowledgment from the designated synchronous standby. Meanwhile, the read replica pool stays on standard asynchronous replication. Those nodes don't participate in failover anyway, so they shouldn't slow down writes.

This creates a healthy balance. The cluster always has at least one failover candidate tracking the leader step for step, while read scaling stays free of extra coordination overhead.

Enabling this mode required tuning four parameters: three in Patroni and one inside PostgreSQL.

ParameterPurposeDefaultManaged byRequiredDatadog value
synchronous_modeEnables Patroni synchronous replication management (true / on)false (off)PatroniRequiredtrue
synchronous_node_countNumber of synchronous standbys in synchronous_standby_names1PatroniOptional1
synchronous_mode_strictBlocks writes when all replicas are lost instead of falling back to asyncfalsePatroniOptionaltrue
synchronous_commitLevel of WAL durability guarantee on transaction commitonPostgreSQLOptionalremote_apply

In the official Patroni documentation (the current 4.x branch), synchronous_mode uses off, on, and quorum, though boolean true and false remain compatible in YAML configs. Patroni's docs also state a strict rule: to keep writes available when one server goes down under synchronous replication, the pool needs at least three nodes: one leader and two standbys. Datadog's leader pool already had that three-node layout.

Here is a working bootstrap.dcs dynamic configuration snippet for this setup, including DCS loss protection and pg_rewind readiness:

bootstrap:
  dcs:
    # Leader lock timers:
    # follow the rule loop_wait + 2 * retry_timeout <= ttl
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    # Lag limit in bytes (1 MB) above which failover is blocked
    maximum_lag_on_failover: 1048576
    # Protect against false leader demotion during ZooKeeper outages
    failsafe_mode: true
    # Enable strict synchronous replication to 1 standby
    # (Patroni 4.x also accepts on or quorum instead of true)
    synchronous_mode: true
    synchronous_mode_strict: true
    synchronous_node_count: 1
    postgresql:
      # Allow rewinding a diverged old leader without a full basebackup
      use_pg_rewind: true
      parameters:
        # Wait until the synchronous standby applies WAL locally
        synchronous_commit: remote_apply
        # Required for pg_rewind when data checksums are disabled
        wal_log_hints: "on"

Notice the pairing of synchronous_mode_strict: true and synchronous_commit: remote_apply. The first setting stops Patroni from quietly dropping the cluster back to async mode if all standbys vanish. The second sets the strictest confirmation level in PostgreSQL.

In fact, synchronous_commit has five levels, each trading write speed for durability in a different way.

ValueWhat the leader waits for before replying to the clientPractical effect and risk
remote_applyReplica received WAL, flushed it to disk, and applied changesMaximum consistency and instant failover readiness, but highest latency
on (remote_flush)Replica received WAL and flushed it to non-volatile diskStrong disk durability, but replica queries don't see new rows yet
remote_writeWAL reached the replica's filesystem and OS cache (no fsync)Faster than on, but recent records can be lost if the replica OS crashes
localLocal WAL flush on the leader's disk only, no waiting for replicasNo cross-machine durability guarantee if the primary node is lost
offDoesn't even wait for local WAL flush (window up to 3 * wal_writer_delay)Lowest latency, but recent transactions may vanish on crash (DB stays intact)

PostgreSQL's documentation notes another detail: if synchronous_standby_names is empty, remote_apply, on, and remote_write effectively collapse to local behavior. That's why Patroni's synchronous_mode_strict and PostgreSQL's synchronous_commit only deliver full protection when used together.

The Cost of Reliability: pgbench Benchmarks and Gradual Production Rollout

In databases, nothing comes for free. You either pay with lost writes or higher latency. With synchronous replication, the cost is clear upfront: every COMMIT must wait for a network round-trip and disk activity on another node. How much that hurts depends on two levers: the number of synchronous standbys (synchronous_node_count) and the chosen synchronous_commit level.

Instead of guessing, Datadog ran load tests using standard pgbench with TPC-B transactions (a mix of short reads and writes) on Patroni 3.2.1. They varied database size (scale factor), concurrent clients, thread counts, and total transactions, measuring average transaction latency in milliseconds and throughput in TPS (excluding connection setup time). They didn't include quorum mode in this benchmark series; they tested a single synchronous standby.

pgbench Metric Changes (TPC-B, Patroni 3.2.1) vs. Asynchronous Mode

On synthetic benchmarks, the pattern was clear and harsh. Stronger durability guarantees bring slower writes and lower transactions per second. remote_apply, where the leader waits for the replica to apply changes rather than just flush the log, proved the most expensive. At the same time, it gives the cleanest consistency for instant failover, so engineers decided to test it on real services next.

Here came an interesting twist familiar to anyone who runs load tests. In synthetic pgbench, transactions fire in a tight, continuous stream with zero pauses for business logic, making synchronous commit overhead look scary. Yet when Datadog enabled remote_apply on live production clusters—with heavy writes, high read traffic, and mixed workloads—they saw no noticeable drop in application-level write latency or TPS.

Of course, nobody flipped a single switch for all of production on Monday morning. The rollout moved step by step across data centers and workload tiers, with bake-in periods and close chart monitoring after each stage. For example, a high-throughput resource-processing pipeline handled remote_apply smoothly. Even though the database itself took slightly longer to commit writes, the pipeline kept up without falling behind or building a backlog downstream.

As an extra safety net in case a write-heavy service ever starts struggling, engineers rely on dynamic config changes via patronictl. Running patronictl edit-config lets you lower synchronous_commit or temporarily disable synchronous mode (synchronous_mode: false) on the fly with zero restarts or downtime.

Five Failure Scenarios: From Losing a Replica to a ZooKeeper Outage

Writing YAML and running benchmarks is only half the job. The real test starts when you pull cables and kill processes in a test cluster. Datadog ran five tough failure scenarios to verify that the new setup wouldn't break in production or cause split-brain.

Scenario 1: The current synchronous standby goes down. Patroni on the leader continuously reads pg_stat_replication (catching broken, stalled, or lagging streams) and checks live members in ZooKeeper. As soon as the synchronous replica disappears, Patroni recalculates healthy candidates, picks the second standby in the leader pool, and updates synchronous_standby_names in PostgreSQL automatically. Writes continue synchronously with no pause and no manual action.

Scenario 2: All synchronous standbys go down. Here, behavior depends directly on synchronous_mode_strict. When strict mode is off (false), Patroni clears synchronous_standby_names to an empty string ''. The leader falls back to normal async mode so apps can keep writing. Flip the flag to true, and Patroni does the exact opposite: it sets synchronous_standby_names = '*'. PostgreSQL accepts and commits transactions locally, but freezes client responses. Clients wait until at least one eligible replica returns and confirms the WAL. Once a healthy standby reconnects, Patroni promotes it to synchronous and the queue clears.

Scenario 3: All replicas are unreachable, including the read pool. pg_stat_replication shows zero active connections. With synchronous_mode_strict: true, PostgreSQL blocks confirmations for all write transactions. To applications, this looks like a temporary write outage. If a client gives up and cancels a stuck transaction, PostgreSQL warns that changes may not have reached a replica.

Blocking writes sounds scary at first, but Datadog chose it on purpose: an explicit write error is better than silent data loss. When the database returns an error or timeout, upstream services see it right away and can retry or buffer events in a queue. In async mode, the client would get a cheerful "OK" right before the data vanished with a dying leader, and nobody would notice in time.

Cross-section diagram of PostgreSQL synchronous replication with a leader and standby managed by Patroni

Scenario 4: The leader crashes mid-synchronous commit. This is the trickiest case of the five. Suppose the leader writes WAL to its local disk and waits for the synchronous standby's reply. At that exact millisecond, things break: the PostgreSQL process crashes, the network drops, or the client cancels. That record never reached the replica.

Patroni detects the dead leader and promotes the up-to-date synchronous standby onto a new timeline. For example, test-db-2 becomes the new primary on timeline 2, and async read replicas (nofailover: true) reconnect to it. The catch is that the old leader still has that unreplicated transaction on disk. The two nodes now have diverged timelines, so the old leader can't simply rejoin as a replica.

This is where pg_rewind steps in. When the old leader starts back up, Patroni runs pg_rewind. It finds the exact point where the timelines diverged and rolls back the old node's data directory to match the new primary, discarding local changes that never made it to the cluster. You don't have to re-sync gigabytes of data from scratch.

Note that pg_rewind is a core PostgreSQL tool, not Patroni magic, and requires prerequisites from the PostgreSQL docs: either wal_log_hints = on in the config, or a cluster initialized with data checksums, plus full_page_writes enabled. One nice detail from PostgreSQL's source code: when pg_rewind runs, it forces synchronous_commit = off for its own session so it doesn't hang on broken synchronous replication.

Scenario 5: ZooKeeper itself disappears. Without the DCS, Patroni can't verify leadership or hold new elections. Cluster behavior here depends on failsafe_mode.

When failsafe_mode is false, the leader keeps accepting writes until its leader lock ttl runs out. Once time expires and it can't renew the key in ZooKeeper, Patroni plays it safe: it clears synchronous_standby_names and immediately demotes the leader to read-only recovery mode. All writes fail right away.

With failsafe_mode: true, the cluster acts much smarter. Patroni stores the list of all members in a persistent /failsafe key inside the DCS. If the connection to ZooKeeper drops—and it's truly a DCS outage rather than a lost lock from a leader change—the primary polls every cluster node directly via the Patroni REST API. As long as every known member replies with accepted, the leader keeps accepting writes with its synchronous standby intact. If even one node fails to respond over the REST API, the leader immediately demotes itself to read-only to avoid split-brain. One practical downside remains: while ZooKeeper is down, patronictl can't fetch cluster state, so operational visibility drops until DCS recovers.

Manual Switchover, Why They Skipped DRBD, and Monitoring Signals

Automation handles emergencies, but teams also need manual failovers for Kubernetes node upgrades or hardware maintenance. When Patroni runs with synchronous_mode, patronictl puts guardrails in place to prevent operator mistakes.

If you run patronictl failover or a graceful patronictl switchover targeting a regular asynchronous replica, both commands fail with an error. You can only bypass this with a force flag, which skips durability guarantees and risks losing recent transactions. Target a healthy synchronous standby instead, and the switch runs cleanly: failover shifts leadership in an emergency, while switchover hands off the baton smoothly without breaking consistency.

Here is the core set of patronictl commands for daily checks, live config edits, and manual transitions:

# Check cluster members and roles (Leader / Sync Standby / Replica)
patronictl -c /etc/patroni.yml list

# Change synchronous_commit or disable synchronous_mode with zero downtime
patronictl -c /etc/patroni.yml edit-config

# Planned handoff to a synchronous standby (fails on an async node)
patronictl -c /etc/patroni.yml switchover --candidate test-db-2

# Emergency manual failover to a synchronous standby
patronictl -c /etc/patroni.yml failover --candidate test-db-2

The first command immediately shows which node is Sync Standby and whether any dangerous lag is building up. With edit-config, you can relax synchronous_commit or revert to async mode (synchronous_mode: false) in seconds if a replica's disks suddenly slow down and bottleneck writes.

During the design phase, Datadog engineers also considered a completely different route: kernel-level block replication using DRBD (Distributed Replicated Block Device). DRBD mirrors an entire disk volume—including PostgreSQL's data directory and WAL files—from one server to another in near real time. In pure latency, that approach can beat database-level streaming replication.

In the end, they passed on DRBD. Adopting it meant major changes to their Kubernetes platform, new storage infrastructure, separate monitoring, and new on-call runbooks. PostgreSQL's built-in synchronous replication paired with mature Patroni proved clearer, more flexible, and much easier to maintain.

After rolling out to production, Datadog kept watch on two key monitoring signals. Without them, a synchronous cluster quickly becomes a black box.

The first signal tracks SyncRep and WalSenderWaitForReply wait events in pg_stat_activity. They show how long the primary sits idle waiting for a synchronous standby to confirm. Brief, occasional waits are normal. If their frequency or duration climbs, either cross-zone networking is acting up or the standby's disk can't keep up. Datadog tracks this via the postgresql.activity.waits metric filtered by wait_event:SyncRep.

The second signal verifies that a synchronous standby actually exists. Engineers use the patroni_sync_standby metric exposed by Patroni in OpenMetrics format (since Datadog has no native integration for it, they collect it via OpenMetrics). If that metric stays empty past an allowed window, a critical HA alert fires: the cluster has lost its safety net and can no longer fail over safely.

During an incident, you can check both states directly inside the database with three short SQL queries on the leader:

-- Check the current synchronous standby list:
-- '*' means strict mode with no available standby, '' means async fallback
SHOW synchronous_standby_names;

-- Inspect active replicas, their role (sync / async / potential), and lag
SELECT
  application_name,
  client_addr,
  state,
  sync_state,
  pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes
FROM pg_stat_replication;

-- Find sessions currently waiting for sync standby confirmation
SELECT wait_event_type, wait_event, count(*)
FROM pg_stat_activity
WHERE wait_event IN ('SyncRep', 'WalSenderWaitForReply')
GROUP BY wait_event_type, wait_event;

If the first query returns '*' and the second returns zero rows, strict mode is actively pausing writes while waiting for a live replica. The third query shows how many commits are queued up, helping you decide whether to wait for the node to recover or temporarily set synchronous_mode: false.

Checklist Before Enabling Strict Synchronous Replication in Patroni

  • Keep at least 3 nodes in the leader pool (1 leader and 2 standbys) so losing one host doesn't halt writes.
  • Tag read replicas with nofailover: true and keep them asynchronous so they don't slow down commits.
  • Enable wal_log_hints = on (or data checksums during initdb) and full_page_writes = on in PostgreSQL for pg_rewind.
  • Set failsafe_mode: true in the DCS config and ensure timers satisfy loop_wait + 2 * retry_timeout <= ttl.
  • Set up alerts for rising SyncRep / WalSenderWaitForReply waits and for an empty patroni_sync_standby metric.
Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 8