Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

How do Patroni-managed PostgreSQL clusters elect a leader, and why do they depend on etcd, Consul or ZooKeeper instead of the nodes voting among themselves?

Every node runs a Patroni agent, and the leader is whichever agent holds the leader key in the distributed configuration store, a key with a TTL that the leader renews on every loop. If it cannot renew, because it crashed or is cut off, the key expires and a healthy replica within maximum_lag_on_failover (and synchronous, if synchronous_mode is on) takes the key with an atomic write and promotes itself. Patroni relies on etcd, Consul or ZooKeeper because they already solve consensus with Raft or a similar protocol; two database nodes alone cannot form a majority, and a leader that loses the store demotes itself, with a watchdog as a backstop.

Why this question is asked

Patroni is the most common way to run highly available PostgreSQL outside managed services, and it is used under several Kubernetes operators too. When it works, failover takes about half a minute and nobody thinks about it. When it is misconfigured, it can fail over too often, not at all, or, worst of all, leave two primaries. Interviewers ask about its internals because understanding the leader key explains all three behaviours. In this answer, we will recap the problem of choosing a leader, follow the leader key loop, walk through a failover, see why the store is external and look at self-fencing and the settings that decide which replica may win.

1A Quick Recap: Why Choosing a Leader Is Hard

In a primary and standby setup, exactly one node may accept writes. When the primary seems to vanish, the others must decide whether it is really gone and which of them takes over. The difficulty is that a node cannot tell a crashed peer from a peer it simply cannot reach. If two nodes each conclude that they should lead, we get split brain, two primaries diverging.

Distributed systems solve this with consensus: a group of nodes agrees on a value only when a majority, a quorum, agrees. With three voters, two must agree, so two separate sides of a network split can never both have a majority. Patroni does not implement consensus itself. It borrows it.

2The Leader Key and the Heartbeat Loop

Patroni keeps the cluster's state in a distributed configuration store, the DCS: etcd, Consul, ZooKeeper, or Kubernetes objects. The central piece is the leader key, stored under a path like /service/shop/leader, whose value is the name of the current leader and which has a TTL, a time to live after which the store deletes it.

Every node runs a Patroni agent that wakes up every loop_wait seconds (10 by default). On the leader, the agent checks that PostgreSQL is healthy and renews the leader key, resetting its TTL (30 seconds by default). On replicas, the agent checks that the key exists, makes sure its PostgreSQL follows that leader, and publishes its own state, including how much WAL it has received, under its member key.

Java
# patroni.yml (parts)
scope: shop
name: pg1
etcd3:
hosts: etcd1:2379,etcd2:2379,etcd3:2379
bootstrap:
dcs:
ttl: 30 # leader key expires 30 s after the last renewal
loop_wait: 10 # each agent runs its check every 10 s
retry_timeout: 10 # how long to retry the DCS before giving up
maximum_lag_on_failover: 1048576 # bytes; replicas further behind may not take over
synchronous_mode: true # only a synchronous replica may be promoted

3Walking Through a Failover

Suppose pg1 is the leader and its server crashes. Nobody renews the key, and up to 30 seconds later the DCS deletes it. On their next loop, the replicas pg2 and pg3 see that there is no leader.

Each replica now asks whether it is a good candidate. It checks that its own lag is within maximum_lag_on_failover, and it contacts the other members through Patroni's REST API to compare WAL positions; if another healthy member is ahead, it steps back. A replica that passes these checks tries to create the leader key with an atomic create-if-absent operation, a compare-and-set. The DCS guarantees only one such write succeeds. The winner promotes its PostgreSQL to primary; the loser sees the new key and reconfigures itself to follow the winner.

Step throughPatroni failover through the DCS
pg2 agentDCS (etcd)pg3 agent
leader key TTL expires, key deleted
read leader key
no leader
REST: what is your WAL position?
behind pg2
create leader key if absent = pg2
success
create leader key if absent = pg3
fails: key exists
promote PostgreSQL
follow pg2

11 messages in order. Play them, or step through them one at a time.

The atomic create in the store, not a vote among database nodes, decides the winner.

4Why the Store Is External

Why not let the database nodes vote among themselves? With two nodes, which is a common setup, there is no majority to be had: when they lose contact, each side has one vote out of two, and neither can safely decide. Even with three database nodes, writing a correct consensus protocol is famously hard, and getting it slightly wrong produces exactly the split brain we fear.

etcd and Consul use Raft, and ZooKeeper uses its own similar protocol, ZAB. They are widely used and carefully tested, and they give Patroni one agreed answer to the question who holds the key, even during partitions. A three-member etcd cluster tolerates the loss of one member; five tolerate two. The members should sit in different zones, ideally including a zone with no database node, so that losing a database zone never also loses the store's majority.

5Self-Fencing and the Watchdog

Now consider a partition instead of a crash: pg1 is alive but cut off from the DCS. It cannot renew the key. Patroni on pg1 retries for retry_timeout, and if it still cannot reach the store, it demotes its own PostgreSQL to read-only before the key's TTL can expire. That is self-fencing: the old leader stops accepting writes on its own, so when pg2 takes the key 30 seconds later, there is never a moment with two writers. This is why ttl must be larger than loop_wait plus retry_timeout.

Self-fencing depends on the Patroni process itself working. If Patroni hangs, it cannot demote anything. The watchdog covers that case: Patroni opens a watchdog device, such as /dev/watchdog on Linux, and must keep resetting it; if it stops, the operating system reboots the node before the leader key could expire. There is also a failsafe_mode in recent versions that lets the leader keep running when the DCS itself is down but all members can still see each other; check your version.

6Who Is Allowed to Win

Two settings decide eligibility. maximum_lag_on_failover, 1 MB by default, stops a replica that is far behind from becoming primary and silently losing a large amount of data; the cluster prefers to stay down until a better candidate is available. synchronous_mode makes Patroni manage synchronous_standby_names itself and allows only a synchronous replica to take the key, which guarantees that no acknowledged commit is lost. Tags such as nofailover exclude nodes entirely, for example a reporting replica.

7Follow-up questions

What happens if the whole etcd cluster goes down?

Without failsafe_mode, the leader cannot renew its key, so it demotes itself and the cluster becomes read-only, even though PostgreSQL is fine. That is the price of never risking split brain. failsafe_mode in newer Patroni versions lets the leader stay primary if it can reach all other members directly; we should know which behaviour our version has before an etcd outage teaches us.

Why must ttl exceed loop_wait plus retry_timeout?

The leader must have time to notice it cannot renew and demote itself before the key expires and another node takes over. If ttl were shorter, a partitioned leader could still be accepting writes when the new leader is promoted.

How do applications find the new leader?

Patroni exposes REST endpoints such as /primary that return 200 only on the leader. HAProxy health checks against them route connections to the current leader; alternatively, a callback or a Kubernetes service selector updates where clients connect.

8Conclusion

In this answer, we saw that Patroni turns leader election into ownership of a key with a TTL in etcd, Consul or ZooKeeper. The leader renews it every loop; when it expires, the most up-to-date eligible replica wins it with an atomic create and promotes itself. The store is external because it provides real consensus that two database nodes cannot, a leader that loses the store demotes itself with a watchdog as backup, and maximum_lag_on_failover and synchronous_mode decide who may win.

What to say in the interviewAbout 90 seconds aloud

Open with

Each PostgreSQL node runs a Patroni agent, and the cluster state lives in a distributed configuration store like etcd, Consul or ZooKeeper. The leader is simply whoever holds the leader key, which has a TTL, 30 seconds by default.

Then, if they want more

Every loop, every 10 seconds, the leader's agent checks PostgreSQL is healthy and renews the key. Replicas check the key exists, follow that leader and publish their WAL position. If the leader crashes or gets cut off, the key expires.

Replicas then check they are eligible, within maximum_lag_on_failover and synchronous if synchronous_mode is on, compare positions with each other over the REST API, and the best one does an atomic create-if-absent of the key. Only one write can succeed, so there is exactly one winner, which promotes itself; the others follow it.

The reason for an external store is consensus: with two database nodes there is no majority, and writing your own consensus is error-prone, while etcd and Consul use Raft and give one agreed answer even during partitions. I would run three or five store members across zones.

For partitions, a leader that cannot reach the store within retry_timeout demotes itself before the TTL expires, which is self-fencing, so ttl must exceed loop_wait plus retry_timeout. And a hardware watchdog reboots the node if Patroni itself hangs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do Patroni-managed PostgreSQL clusters elect a leader, and why do they depend on...": https://scrivio-interview-library.netlify.app/databases/replication-and-ha/87cd79e357/