Patroni is an open-source high-availability framework for PostgreSQL that runs alongside each database node, manages streaming replication and performs automatic failover by coordinating leadership through a distributed configuration store such as etcd, Consul, ZooKeeper or the Kubernetes API. In databases, it belongs to the replication toolset because it turns a group of independently replicated PostgreSQL servers into a self-healing cluster with a single writable primary.
Patroni does not replicate data itself. It relies on PostgreSQL’s native physical streaming replication and adds what PostgreSQL lacks out of the box: leader election, health checking, safe promotion of a replica and consistent cluster-wide configuration.
How Patroni elects and maintains a leader
Each PostgreSQL node runs a Patroni agent, a Python daemon that starts, stops and configures the local database. The agents never vote among themselves directly; instead, they compete for a leader key stored in the distributed configuration store (DCS), which provides the consensus layer through Raft in etcd and Consul or Zab in ZooKeeper.
The node holding the leader key runs PostgreSQL as the primary and must renew the key on every loop cycle, by default every 10 seconds, before its time-to-live of about 30 seconds expires. If the primary fails or loses contact with the DCS, the key expires, and the healthy replicas race to acquire it. Before promoting itself, a candidate checks that it is sufficiently up to date and not lagging beyond a configured threshold.
The key timing parameters control how fast and how safely failover happens.
| Parameter | Default | Effect |
|---|---|---|
| ttl | 30 seconds | Leader key lifetime; sets failure detection time |
| loop_wait | 10 seconds | Interval between agent health cycles |
| retry_timeout | 10 seconds | Time allowed for DCS and PostgreSQL retries |
| maximum_lag_on_failover | 1 MB | Largest replication lag a candidate may have |
| primary_start_timeout | 300 seconds | Wait before failing over a slow-starting primary |
Architecture and components
A production Patroni deployment combines several layers, and the reliability of the whole depends on each of them. The DCS cluster must itself be highly available, typically with three or five members placed in separate failure domains, because Patroni cannot elect a leader without a DCS quorum.
Clients usually do not connect to PostgreSQL nodes directly. Patroni exposes a REST API on each node, commonly on port 8008, that returns HTTP 200 only from the current primary or from healthy replicas, and load balancers or connection routers use those endpoints to send traffic to the correct node.
| Layer | Typical tools | Responsibility |
|---|---|---|
| Database nodes | PostgreSQL with Patroni agent | Store data and replicate via WAL streaming |
| Consensus store | etcd, Consul, ZooKeeper, Kubernetes API | Hold leader key and cluster configuration |
| Traffic routing | HAProxy, PgBouncer, virtual IP, DNS | Direct clients to primary or replicas |
| Administration | patronictl command-line tool | Switchover, restart, reinitialize, edit config |
| Backup and restore | pgBackRest, WAL-G, pg_basebackup | Create replicas and recover from failure |
Cluster-wide PostgreSQL settings are stored in the DCS and applied by every agent, which prevents configuration drift between nodes. Changes are made with patronictl edit-config, and Patroni reports whether a parameter requires a pending restart.
Failover, switchover and split-brain protection
Patroni distinguishes an unplanned failover, triggered when the leader key expires, from a planned switchover, requested by an operator for maintenance. A switchover demotes the primary cleanly, waits for the chosen replica to catch up and then promotes it, so no committed transactions are lost.
Split-brain, the situation in which two nodes accept writes simultaneously, is the main risk in any failover system. Patroni counters it by making a primary demote itself whenever it cannot renew the leader key, even if PostgreSQL is healthy. An optional watchdog device goes further and reboots the node if the Patroni agent itself hangs, guaranteeing that a stale primary stops serving writes.
Data loss during failover depends on the replication mode configured in Patroni.
| Mode | Data loss on failover | Write latency | Typical use |
|---|---|---|---|
| Asynchronous | Possible, bounded by maximum lag | Lowest | Most general workloads |
| Synchronous mode | None for acknowledged commits | Higher, one network round trip | Financial and order data |
| Strict synchronous | None; writes stop without a sync replica | Higher | Zero-loss requirements |
| Quorum commit | None if quorum of replicas confirms | Moderate | Multi-zone clusters |
Patroni compared with other PostgreSQL failover tools
Several tools solve the same problem, and the main difference lies in where consensus comes from. Patroni delegates it to an external store, which is proven and robust but adds an extra system to operate.
| Tool | Consensus source | Strength | Limitation |
|---|---|---|---|
| Patroni | External DCS | Mature, flexible, Kubernetes-ready | Requires running a DCS |
| repmgr | Node witness and voting | Simple to install | Weaker split-brain protection |
| pg_auto_failover | Dedicated monitor node | Easy setup for small clusters | Monitor is a critical component |
| Pacemaker with Corosync | Cluster stack quorum | General-purpose, fencing support | Complex configuration |
Patroni is also the engine behind several Kubernetes operators for PostgreSQL, where it uses Kubernetes objects instead of a separate etcd cluster, which makes it a common choice for cloud-native deployments.
Common mistakes when running Patroni
- Running a single-member DCS, which makes the consensus store the new single point of failure.
- Placing all DCS members in one availability zone, so a zone outage removes quorum and freezes the cluster.
- Editing
postgresql.confby hand instead of the DCS configuration, which Patroni silently overwrites. - Setting ttl too low on unstable networks, causing unnecessary failovers on short latency spikes.
- Connecting applications to a fixed host instead of a health-checked endpoint, so they keep writing to a demoted node.
A plain-language summary
Picture a team of identical database servers where only one is allowed to accept changes at a time. Patroni acts as a supervisor on each server, and the supervisors share a small notice board that holds the name of the current leader. The leader must keep refreshing its name on the board.
If the leader stops refreshing, because it crashed or lost its network, the other supervisors notice, pick the most up-to-date server and make it the new leader. Applications are pointed to the new leader automatically, so the service keeps running with little interruption.
An example from practice
A logistics company runs its shipment-tracking database on three PostgreSQL nodes spread across three availability zones, with Patroni managing them and a three-member etcd cluster alongside. HAProxy checks the Patroni REST API every few seconds and routes writes only to the node that answers as primary. One replica is configured as a synchronous standby so that confirmed shipments are never lost.
During a zone outage, the primary lost network access. Patroni on that node failed to renew the leader key and demoted PostgreSQL, while the synchronous replica acquired the key and was promoted. Writes resumed after about 35 seconds, no acknowledged transactions were lost, and when the failed zone returned, Patroni used pg_rewind to rejoin the old primary as a replica without a full rebuild.