Patroni

On this page 7

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.

ParameterDefaultEffect
ttl30 secondsLeader key lifetime; sets failure detection time
loop_wait10 secondsInterval between agent health cycles
retry_timeout10 secondsTime allowed for DCS and PostgreSQL retries
maximum_lag_on_failover1 MBLargest replication lag a candidate may have
primary_start_timeout300 secondsWait before failing over a slow-starting primary
Core Patroni timing parameters

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.

LayerTypical toolsResponsibility
Database nodesPostgreSQL with Patroni agentStore data and replicate via WAL streaming
Consensus storeetcd, Consul, ZooKeeper, Kubernetes APIHold leader key and cluster configuration
Traffic routingHAProxy, PgBouncer, virtual IP, DNSDirect clients to primary or replicas
Administrationpatronictl command-line toolSwitchover, restart, reinitialize, edit config
Backup and restorepgBackRest, WAL-G, pg_basebackupCreate replicas and recover from failure
Layers of a typical Patroni cluster

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.

ModeData loss on failoverWrite latencyTypical use
AsynchronousPossible, bounded by maximum lagLowestMost general workloads
Synchronous modeNone for acknowledged commitsHigher, one network round tripFinancial and order data
Strict synchronousNone; writes stop without a sync replicaHigherZero-loss requirements
Quorum commitNone if quorum of replicas confirmsModerateMulti-zone clusters
Replication modes and their guarantees

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.

ToolConsensus sourceStrengthLimitation
PatroniExternal DCSMature, flexible, Kubernetes-readyRequires running a DCS
repmgrNode witness and votingSimple to installWeaker split-brain protection
pg_auto_failoverDedicated monitor nodeEasy setup for small clustersMonitor is a critical component
Pacemaker with CorosyncCluster stack quorumGeneral-purpose, fencing supportComplex configuration
Comparison of PostgreSQL high-availability managers

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.conf by 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.