Skip to content

Patroni failover behavior — what actually happens in the 30 seconds after

Patroni failover behavior in detail — the leader-lock expiry, the replica race, HAProxy convergence, the sync-promotion data-loss window, and what the application actually sees during a real failover.

The primary database server dies at 02:14:33. By 02:15:08, a new leader is accepting writes. In the thirty-five seconds between those timestamps, four distinct things happen — and the parts your application notices, the parts your monitoring records, and the parts that determine whether you lost data are not the same parts. This is the runbook-style companion to the Patroni production architecture deep dive: what the cluster actually does during a failover, what stretches the window, what data loss looks like in sync versus async configurations, and what to drill for so the first real one is not the first one you have ever seen.

The failure modes Patroni handles cleanly

Patroni is designed for a specific class of failure: the primary becomes unavailable for reasons the DCS can detect via missed lock renewal. That class is broader than it sounds and covers most real-world incidents:

  • The PostgreSQL process crashes (segfault, OOM kill, assertion failure) and Patroni cannot restart it within retry_timeout.
  • The host kernel panics, hangs, or is hard-reset.
  • The hypervisor migrates the VM and the pause exceeds ttl.
  • The host loses network connectivity to the DCS quorum (and watchdog reboots it if the main loop hung).
  • A planned switchover via patronictl switchover.
  • The primary’s disk fills and PostgreSQL refuses new connections (Patroni detects via health probe failures).
  • Patroni itself is killed (systemctl stop patroni or SIGKILL to the daemon).

In all of these, the leader lock expires in etcd, surviving replicas detect the missing lock, the one with the highest LSN promotes, and HAProxy converges. The state machine has been hardened over a decade against weird combinations of these — partial PostgreSQL hangs, watchdog races, network blips shorter than ttl. The cluster usually does the right thing.

The failure modes Patroni does NOT handle

There are failure modes that exceed Patroni’s design envelope and can produce split brain, data loss, or extended unavailability. Knowing where the edges are is the difference between trusting Patroni for the cases it handles and over-trusting it for cases it does not:

Long GC pauses or kernel I/O stalls without a watchdog. If Patroni’s main loop hangs (Python GIL contention under extreme load, an fsync() call blocked on stalled storage) but PostgreSQL keeps writing, the leader lock expires in etcd, a replica gets promoted, and the original primary returns from its pause still believing it is the leader. Without the watchdog, both nodes accept writes briefly — split brain. The watchdog (softdog or hardware) is the only defence; never disable it in production.

Network partition without quorum. If the primary loses connectivity to a majority of etcd nodes but retains connectivity to the application, it cannot renew its lock and demotes itself after ttl. So far, so good. But if your application’s only path to the primary is the same partitioned network, and your monitoring is in the same partition, you may not realise the cluster failed over to the other side until traffic from healthy clients reveals it. Test your network topology against the partitions that matter to you — placing both etcd and PostgreSQL across the same three AZs gives you a clean failure model; mixing AZs across components creates partitions that map to no real failure domain.

Two-node “HA” (which is not HA). A two-node Patroni cluster with a single etcd is not HA. If etcd dies, neither Patroni node can renew the lock and the cluster freezes. If the primary dies, the surviving replica cannot determine whether it is in a minority partition or facing a dead primary, and Patroni refuses to promote — the conservative default that prevents split brain at the cost of automated availability. If a colleague is “running Patroni” and they have two nodes plus a “we can add etcd later,” they are running a slow manual failover.

Watchdog disabled. Already mentioned, worth repeating. The watchdog is not a “nice to have.” It is the mechanism that bounds the worst-case behaviour to “node reboots” instead of “two nodes both write to the same logical database.” Run with watchdog.mode: required and accept the operational annoyance of having to deal with watchdog timeouts during heavy testing.

Corrupt WAL on the surviving replicas. If the primary has been writing corrupt WAL for hours and the corruption has propagated to replicas, the failover succeeds at the cluster level — a replica is promoted — but the database itself is damaged. No HA cluster protects you from data corruption; that is what backups are for. If pg_checksums is enabled (it is, on a properly bootstrapped cluster) you may notice the corruption before promotion. If not, you find out when an application query returns an error or, worse, returns wrong data.

Sequence diagram

The figure below is the timeline of an unplanned failover with default tuning (ttl: 30, loop_wait: 10, retry_timeout: 10, safety_margin: 5). T=0 is the moment the primary becomes unreachable.

The “no_leader” period

The no-leader window — the time between the old primary stopping and the new primary accepting writes — is the SLA-relevant number. With default tuning, expect 30-45 seconds. The breakdown:

  • 0-10s: old primary unresponsive; Patroni daemons on replicas notice missed heartbeats but the lock is still valid until ttl.
  • 10-28s: lock TTL counting down. No replica can promote because the lock is still held in etcd (compare-and-swap fails).
  • 28-30s: lock expires. Replicas race; the one with the highest LSN wins.
  • 30-35s: winner runs pg_ctl promote, PostgreSQL transitions from standby to primary, accepts the first write.
  • 35-45s: HAProxy health checks flip (3-second interval × 2 falls = 6s worst case after promotion).
  • 45-60s: application reconnects through HAProxy.

Things that stretch this window: a loop_wait longer than 10s (which is fine but adds latency to detection); pg_rewind not configured, forcing a replica_method rebuild before promotion (rare — usually replicas are already streaming and the promotion is fast); the elected replica is significantly behind on apply (maximum_lag_on_failover will skip a replica that exceeds the configured lag — usually 1MB or 16MB — and the cluster waits for a healthier candidate); etcd itself is slow or under load (raft proposal latency on a saturated DCS shows up here as failover delay).

Tighter tuning shortens the window: ttl: 20, loop_wait: 5, retry_timeout: 5, watchdog.safety_margin: 3 produces sub-25-second failover on healthy infrastructure. The cost is reduced safety margin — every component must respond inside tighter bounds. Run this configuration only after you have demonstrated, under load, that your DCS latency, network round-trips, and PostgreSQL responsiveness comfortably fit inside those windows.

Synchronous replica promotion — data loss windows

The data-loss window during failover depends entirely on whether synchronous_mode was on at the moment the primary died.

With synchronous_mode: on and synchronous_node_count: 1: every commit on the primary required at least one synchronous replica to acknowledge before returning to the client. When the primary dies, the synchronous replica has — by definition — every committed transaction. The promoted replica’s LSN is at or beyond the primary’s last committed LSN. Data loss: zero.

The asterisk: there is a narrow window where the primary has written a transaction’s WAL locally but not yet received sync ack when it dies. That transaction is not committed from the client’s point of view — the client never got a COMMIT reply — so from a correctness standpoint nothing is lost. But the transaction is durably on disk on the dead primary’s storage. When the dead primary comes back, pg_rewind discards those uncommitted-but-on-disk WAL records and the cluster converges to the post-failover timeline. The client must retry. This is correct behaviour.

With synchronous_mode: off (async replication only): commits return as soon as the primary’s local WAL is fsync’d. Replicas trail by some lag. When the primary dies, the elected replica is missing the WAL between its last received LSN and the primary’s last committed LSN. Data loss: bounded by the lag at T=0. On a healthy cluster with sub-second lag, that is a handful of transactions; on a cluster under WAL pressure with 30 seconds of lag, that is 30 seconds of writes.

The decision is not “do I want zero data loss” — everyone wants zero data loss. The decision is “do I want to trade some commit latency and a sync-replica-availability dependency for that guarantee.” For systems of record (billing, ledgers, anything with regulatory implications), sync mode is non-negotiable. For caches, session stores, or workloads where eventual consistency is fine, async mode is acceptable — and the lower commit latency is real (1-3 ms saved on every write adds up under load).

What the application sees

The application’s experience of a failover is, in order:

  1. Connection errors on the demoted primary. With HAProxy’s on-marked-down shutdown-sessions, existing connections are reset cleanly; the application driver returns connection reset or broken pipe on the next query. Without that directive, connections hang until TCP keepalive notices — minutes, depending on kernel settings.

  2. Reconnect storms. Every application instance simultaneously notices broken connections, tries to reconnect, and HAProxy sees a burst of new TCP handshakes. If your application pool is 2000 connections wide and your pool minimum reconnect time is 100ms, you get a brief CPU and connection-tracking spike on HAProxy. Usually fine; if you scale to tens of thousands of pool slots, plan for it.

  3. Read-only errors during the no-leader window. Any writes that arrive between the old primary going down and the new one being up will fail. The error from PostgreSQL is cannot execute INSERT in a read-only transaction (if the application happens to hit the read endpoint) or connection refused / connection reset (from HAProxy returning 503 on the write port).

  4. Retry budget exhaustion. Application drivers with aggressive retry policies (max_retries: 3, retry_delay: 1s) will exhaust their budget during a 30-second no-leader window and surface the error to the user. The right retry pattern for a database client during a Patroni failover is exponential backoff with a budget of 60-90 seconds and jitter — long enough to outlast the no-leader window, short enough that a longer outage gets escalated rather than silently retried forever.

  5. Successful reconnect. Once HAProxy marks the new primary up, the next reconnect attempt succeeds. The application’s pool drains its dead sockets and refills against the new endpoint. Steady state resumes.

Test your application against a real switchover. Many drivers (Hikari for Java, asyncpg for Python, pgx for Go) have sane defaults; some (older versions of Sequelize, some PHP PDO configurations) cache connections indefinitely and require explicit configuration to drop dead sockets. The drill is the only way to be sure.

Post-failover cleanup

The old primary returns. Maybe the hypervisor came back. Maybe an operator restarted it. Either way, Patroni notices and tries to reattach it as a replica of the new leader. Two paths exist for that reattachment, and the one Patroni takes determines how fast you are back to a fully redundant cluster.

pg_rewind path: the old primary and new primary’s timelines diverge at the point of failover — both have WAL beyond the divergence point, and they disagree about which records are real. pg_rewind reads both timelines, identifies the divergence, copies the missing/changed pages from the new primary, and rewrites the old primary’s pg_xact and other metadata to match. The result is a usable replica without a full data copy. This is the right path when the divergence is small (a few WAL files), takes seconds to minutes, and preserves all the disk content that hasn’t changed.

pg_rewind requires wal_log_hints: on (or data_checksums: on) in the cluster spec — Patroni’s use_pg_rewind: true enables this automatically. It also requires the old primary to be cleanly shut down before the rewind, which Patroni handles. If pg_rewind cannot reconcile the timelines (too divergent, missing files, checksum mismatches), Patroni logs the failure and falls back to the configured replica_method.

Full re-init path: Patroni runs the configured replica bootstrap method — usually pg_basebackup from the new primary, or pgbackrest restore from the backup repository. This is correct but slow: minutes to hours depending on cluster size. The pgbackrest restore path is dramatically faster than pg_basebackup for large clusters because the backup is already in object storage and downloads in parallel without saturating the new primary’s network.

The decision between pg_rewind and re-init is made by Patroni, not by you. Your job is to monitor it: patronictl list shows the node state during reattachment, and journalctl -u patroni on the rejoining host tells you which path was taken and whether it succeeded. If both fail, the node is stuck — see Cluster recovery — Postgres timeline divergence for the manual procedures.

Drilling failover

Failover behaviour read about in documentation is not the same as failover behaviour observed in your cluster. The variables that matter — your DCS latency, your network round-trip, your application’s retry policy, your driver’s reconnect behaviour, your monitoring’s notification path — only get measured by running a real failover end-to-end. A quarterly drill is the cadence that catches drift before it becomes the incident.

The drill is a one-hour event. Schedule it. Block the calendar. Run synthetic write load. Trigger a graceful switchover and measure the gap. Trigger an unplanned simulation (SIGKILL patroni plus an iptables rule that blocks port 5432) and measure that gap. Verify the failed node rejoins cleanly. Record the results. Compare quarter-to-quarter — if the gap drifts upward, something in the chain is degrading and you should investigate before it matters.

The full drill procedure, including the synthetic-load script, pre-flight checks, expected timings, sign-off criteria, and the log format, is in Patroni quarterly failover drill — procedure, timings, sign-off. Read it. Run it. Do not skip it because “things are quiet” — the drill exists precisely to catch the rot that develops during quiet quarters.

Incidents this turned into

Three anonymized stories from clusters we have run, each illustrating where the theory met reality differently than expected.

The 18-minute “30-second” failover. A bare-metal cluster with three Patroni nodes and three etcd nodes, all on the same network switch in the same rack. Switch port died at 3 AM. From the cluster’s perspective, all three nodes simultaneously lost network — etcd quorum collapsed, no node could renew or claim the lock. Patroni did the conservative thing: refused to promote without a quorum. The cluster sat unavailable until network was restored. The drill had never tested “all nodes lose network at once” because the test environment was on shared infrastructure that could not produce that failure. Lesson: place etcd and PostgreSQL across at least three independent failure domains. A single switch counts as one failure domain even if it is a “redundant pair” with a misconfigured failover.

The successful failover that caused a four-hour outage. Patroni elected a new leader in 35 seconds — textbook. Application driver was a Java service using HikariCP with connectionTestQuery: SELECT 1 and a 30-second validationTimeout. The cache of “this connection is healthy” did not invalidate after the failover because the SELECT 1 happened to be served by the new primary on the same TCP connection (the kernel had buffered the reconnect transparently). All looked fine — until the application tried to issue a write, which failed because… it was now connected to a node that had been demoted moments later when an operator did a corrective switchover. The cluster was healthy throughout; the application’s connection-validity model was wrong. Lesson: validate against pg_is_in_recovery() for write-path connections, not against SELECT 1. Drill your application, not just your database.

The sync replica that was not sync. A cluster running synchronous_mode: on, synchronous_node_count: 1 failed over after the primary VM was migrated through a 90-second pause. The promoted node was the async replica — not the sync. Why? The sync replica had been silently degraded for two days because of a network blip that Patroni had recovered from but the monitoring alert for “sync_state changed” had not been wired correctly. During those two days, every commit had been waiting for sync ack from a node that was not actually sync (Patroni had demoted it to the standby pool but client-visible synchronous_commit was still labelling it that way in a subtle way that confused our dashboard). When the failover happened, the highest-LSN node was the async replica. Data loss: 4 transactions. Lesson: monitor pg_stat_replication.sync_state directly on the primary, not Patroni’s view of it. The two can diverge during edge-case state transitions.

See also