Skip to content

Patroni — production PostgreSQL high-availability cluster architecture

Patroni PostgreSQL HA in production — etcd quorum, leader election, sync vs async replicas, HAProxy routing, watchdog, and the decisions that determine whether your cluster survives a real outage.

You have one PostgreSQL primary and a streaming replica. The replica is hot, lag is single-digit milliseconds, and you have a runbook called “promote.sh” that the on-call engineer is supposed to execute when the primary dies. Eighteen months in, the primary actually dies — at 2:14 AM on a Saturday — and the engineer who knows that runbook is on a flight to Lisbon. The cluster sits there with the replica perfectly healthy and the application down for forty minutes while another engineer reads the runbook, double-checks the LSN, and types pg_ctl promote with shaking hands. The failover didn’t fail because Postgres failed. It failed because the cluster had no memory of what it was supposed to do without a human in the loop.

Patroni exists to solve exactly that problem. It is not magic, it is not a database, and it does not replace your understanding of streaming replication — it is a state-machine wrapper around PostgreSQL that uses a distributed configuration store (etcd, Consul, or ZooKeeper) to elect a leader, manage replica configuration, gate dangerous transitions, and converge on a correct cluster state without a human reading a runbook at 2:14 AM. This article is the architecture deep-dive: the components, the decisions, and the failure modes that determine whether your production cluster is genuinely HA or just three servers with replication turned on.

What Patroni actually does

A Patroni node is a Python daemon co-located with a PostgreSQL process. The daemon owns the PostgreSQL service — it starts it, configures postgresql.conf and pg_hba.conf from the cluster spec, promotes or demotes the instance, and exposes a REST API for health checks and operator commands. The daemon’s authoritative state lives in the DCS (Distributed Configuration Store), not on the local node. The DCS holds two things that matter: the cluster spec (the configuration every node should converge on) and the leader lock (a TTL-protected key that says “this node is the primary and you all replicate from it”). Every Patroni node renews the lock or watches it on a loop_wait cycle; if the holder fails to renew within the configured ttl, the lock expires and the surviving nodes race to acquire it.

The race is not arbitrary. Patroni evaluates several gates before a node attempts promotion: the replica’s LSN must be ahead of (or equal to) all other live replicas, the node must have synchronous-replication ack history if synchronous_mode is on, and the local PostgreSQL must accept the promotion (timelines must be reconcilable). Only one node can hold the lock at a time because the DCS enforces compare-and-swap on the key; the loser of the race gracefully demotes itself and re-attaches as a replica of the winner. The watchdog, when configured, gives the deposed primary a hard deadline to abandon the role — if Patroni’s main loop hangs, the kernel reboots the node before it can write to disk with a stale belief that it is still leader. That mechanism is what prevents a split brain when the network gets weird.

The REST API on each node is the integration point for everything outside the cluster. HAProxy uses /leader and /replica to route traffic. Monitoring uses /cluster to read the full topology. Operators use patronictl (which calls the API) to issue switchovers, reload configuration, or pause/unpause the state machine. There is no “control plane” — every node sees the same DCS, and the cluster converges through the gossip of state changes through that store.

Reference architecture

The diagram below is the architecture this article walks through end-to-end. Three etcd nodes form a quorum DCS. One PostgreSQL primary and two replicas — one synchronous, one asynchronous — sit behind an HAProxy pair, with Patroni daemons co-located on each PostgreSQL node and writing leader-lock state into etcd on a 10-second renewal cadence. Applications connect through HAProxy on the write port (5000) for the primary and a read port (5001) for any healthy replica.

Component breakdown

The DCS (Distributed Configuration Store)

The DCS is the single most important architectural decision in the cluster — get this wrong and every other piece is unreliable. Patroni supports etcd v3, Consul, ZooKeeper, and Kubernetes-native (using CRDs and the K8s API). For a typical production cluster on VMs, etcd v3 is the default and the path with the most operational experience in the Patroni ecosystem.

The DCS must have an odd number of nodes — 3 or 5 — because raft consensus requires a strict majority. A three-node etcd survives one node loss (2 of 3 = majority). A five-node etcd survives two node losses (3 of 5 = majority). Do not run two etcd nodes; you have no quorum if either fails. Do not run four; you survive only one loss (3 of 4) and get worse latency than three. The choice between 3 and 5 is about how many concurrent failures you must tolerate: 3 nodes is right for a single-region cluster across three AZs; 5 nodes makes sense when you cannot place all members close to each other and want survival across two simultaneous failures.

Placement matters more than node count. The classic mistake is to co-locate the etcd nodes on the same PostgreSQL hosts in the same rack — when the rack loses power, both the database and its coordination layer die together, and the surviving nodes have no quorum to elect a new leader. Spread etcd across three AZs (or three physical racks if you are on bare metal). Pin etcd disks to fast local storage (NVMe or equivalent); etcd’s raft requires fsync on every committed entry, and a slow disk turns the DCS into your latency floor. Network: etcd’s peer port (2380) must have predictable, low-latency connectivity between members. Cross-region etcd is an antipattern — the write latency on every Patroni heartbeat will dominate your failover behaviour.

Network partition behaviour is where DCS choice matters operationally. If the Patroni primary loses connectivity to a quorum of etcd, it cannot renew its leader lock, and after ttl seconds it will demote itself (and the watchdog will reset the box if Patroni itself hangs). The minority partition is now a chain of demoted nodes that cannot accept writes. The majority partition holds the lock and continues serving — exactly the behaviour you want. The wrong behaviour, which is what an etcd-less Patroni or a misconfigured Consul gives you, is two partitions both believing they are leader. That is split brain. Patroni prevents it because the DCS itself refuses to grant the lock to more than one node.

Consul and ZooKeeper are viable alternatives. Consul has a friendlier UX for ACL-heavy environments and integrates with broader service-mesh tooling, but its raft implementation has historically been more sensitive to disk latency than etcd’s. ZooKeeper is rock-solid but operationally heavier than etcd in 2026; if you do not already run ZooKeeper for something else, do not introduce it just for Patroni. The Kubernetes-native DCS (using kubernetes mode) skips a separate DCS entirely and uses the K8s API as the store — sensible when you are already on a Kubernetes platform that uses etcd, but you are now coupling your database HA to your cluster control plane.

Primary node

The primary node runs PostgreSQL in read-write mode with wal_level=replica (or logical if you also do logical replication elsewhere). The Patroni bootstrap.dcs.postgresql.parameters block is the source of truth for these settings — never hand-edit postgresql.conf on a Patroni-managed node, because Patroni regenerates it from the cluster spec on every reload. Critical parameters that belong in the cluster spec, not in a per-node file: shared_buffers, effective_cache_size, work_mem, maintenance_work_mem, max_wal_size, min_wal_size, checkpoint_timeout, archive_mode=on, archive_command, synchronous_standby_names (Patroni manages this automatically — do not set it manually), hot_standby=on, max_replication_slots, max_wal_senders.

The archive_command is the bridge between Patroni and your backup tool. With pgBackRest, it is pgbackrest --stanza=main archive-push %p; with WAL-G, wal-g wal-push %p. The command must succeed for every WAL segment, or your point-in-time recovery floor advances slower than your incident clock. Monitor pg_stat_archiver.last_failed_wal — anything non-NULL is a finding. The Patroni cluster spec must pair with a real backup pipeline; HA is replication, backups are point-in-time recovery. They are not the same thing, and you need both.

fsync is on. Always. Anyone who tells you to turn fsync off in production is telling you to lose data on the next power event. The same applies to full_page_writes — leave it on. The performance cost is real but the durability guarantee is what makes PostgreSQL acceptable as a system of record. If you need lower commit latency, the answer is faster storage, not weaker durability guarantees.

Synchronous replicas

synchronous_commit is the lever between durability and write latency, and Patroni’s synchronous_mode is the lever between durability and availability. With synchronous_mode: on and synchronous_commit=on (or remote_apply), the primary will not acknowledge a commit until at least one synchronous standby has fsync’d the WAL (or applied it, for remote_apply). This gives you zero data loss on a primary failure — the promoted replica has every committed transaction. The cost is that every commit waits for a network round-trip, which is 1-3 ms in the same AZ and 5-15 ms across AZs.

Patroni’s synchronous_node_count controls how many standbys must be synchronous. With synchronous_node_count: 1 in a three-node cluster, Patroni picks one replica as sync and the other stays async. The choice of FIRST 1 vs ANY 1 in PostgreSQL’s synchronous_standby_names is something Patroni manages for you, but you should understand the difference: FIRST 1 (s1, s2) waits specifically for s1, falling back to s2 only if s1 is gone; ANY 1 (s1, s2) accepts ack from whichever responds first. Patroni uses FIRST semantics, which is the correct default for predictable failover behaviour.

The subtle failure mode: with synchronous_mode: on, if the sync standby dies, the primary will block writes waiting for the dead replica to ack. Patroni handles this by demoting the dead node out of synchronous_standby_names once it sees the replica is unreachable, after which the next-best replica is promoted to sync. The window between “sync replica dies” and “Patroni rewires sync to another node” is your write-availability cliff. Set synchronous_mode_strict: false if you would rather degrade to async than block writes — but only after you understand that you are explicitly trading durability for availability.

Asynchronous replicas

Async replicas trail the primary by their replication lag — which, on healthy infrastructure, is single-digit milliseconds; under WAL pressure, can be seconds or worse. They are useful for two things: read scale (offload analytical queries off the primary) and as additional failover candidates when sync nodes are unavailable. They are NOT a substitute for backups, because they replay every write — including the DROP TABLE an operator just issued.

hot_standby_feedback=on is the small setting that has a big impact: it tells the primary not to vacuum tuples that running queries on the replica still need. Without it, long-running analytic queries on the replica get cancelled when the primary’s autovacuum decides to remove the rows underneath them — you will see ERROR: canceling statement due to conflict with recovery. With it, you trade replica query stability for some bloat risk on the primary if a replica query hangs for hours. The right setting depends on your read workload; if you serve user-facing reads off the replica, turn it on.

Replication lag is the SLA you actually need to monitor. pg_stat_replication on the primary tells you the LSN gap per replica; pg_stat_wal_receiver on the replica tells you the apply position. Alert on pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) > 16MB (one WAL segment) sustained for more than a minute, and page on > 64MB sustained. Lag is the leading indicator for “your replica is going to fall off the cliff and require pg_basebackup to recover.”

HAProxy / pgBouncer front

PostgreSQL has no built-in connection routing. Patroni exposes which node is the leader, but applications still need a stable endpoint. The standard pattern is HAProxy in front, using Patroni’s REST API for health checks. The HAProxy backend for writes uses httpchk GET /leader on port 8008 — that endpoint returns HTTP 200 only on the node currently holding the leader lock. The reads backend uses httpchk GET /replica — 200 on any healthy replica, 503 elsewhere. Configure two front-end ports (typically 5000 for writes, 5001 for reads), point applications at them, and HAProxy converges automatically when Patroni promotes a new leader.

listen postgres-write
    bind *:5000
    mode tcp
    option httpchk GET /leader
    http-check expect status 200
    default-server inter 3s fall 2 rise 1 on-marked-down shutdown-sessions
    server pg-01 10.20.1.11:5432 check port 8008
    server pg-02 10.20.2.11:5432 check port 8008
    server pg-03 10.20.3.11:5432 check port 8008

listen postgres-read
    bind *:5001
    mode tcp
    option httpchk GET /replica
    http-check expect status 200
    balance roundrobin
    default-server inter 3s fall 2 rise 1
    server pg-01 10.20.1.11:5432 check port 8008
    server pg-02 10.20.2.11:5432 check port 8008
    server pg-03 10.20.3.11:5432 check port 8008

on-marked-down shutdown-sessions is the line that matters during failover: it forces HAProxy to close existing connections to a backend the moment it is marked down, so the application driver sees a clean reset and reconnects through the new leader rather than holding a stale socket to the demoted primary. Without this directive, applications can hold half-dead connections for minutes after a failover. Run HAProxy as an active/standby pair behind keepalived (or in active/active behind a network load balancer) — a single HAProxy is a single point of failure for the whole cluster.

pgBouncer sits between the application and HAProxy when you have high connection churn. PostgreSQL’s per-connection cost (memory, process startup) makes thousands of short-lived application connections expensive; pgBouncer pools them into a smaller number of long-lived backend sessions. Run pgBouncer on each application host (sidecar pattern) for lowest latency, or as a separate tier behind HAProxy if you want central pool management. Use transaction pooling mode for OLTP — session pooling forces one backend per client and gives up most of pgBouncer’s benefit; statement pooling breaks anything with multi-statement transactions. The pgcat project is a Rust rewrite with better observability and per-shard routing; it is production-viable in 2026 if you have a use case for query-level steering, but pgBouncer remains the conservative default. Patroni’s REST API also exposes /primary and /standby aliases for HAProxy if you prefer the explicit naming.

Watchdog and split-brain prevention

The watchdog is what stands between you and the worst class of database incident: two nodes both believing they are primary, both accepting writes, both producing divergent timelines. Patroni configures the Linux kernel’s softdog (or hardware watchdog, if available) and pets it on every successful main-loop iteration. If Patroni hangs — Python GC pause, kernel I/O stall, kernel panic — the watchdog fires after watchdog.safety_margin seconds and reboots the node before it can write anything else to disk. That reset is the guarantee that a demoted primary truly stops writing.

The interaction between ttl, loop_wait, retry_timeout, and the watchdog’s safety margin is the relationship that determines your failover envelope:

  • loop_wait (default 10s): how often Patroni’s main loop runs. The leader renews the DCS lock every loop.
  • ttl (default 30s): how long the leader lock lives in the DCS without a renew. After ttl, surviving nodes can race to claim it.
  • retry_timeout (default 10s): how long Patroni waits for individual DCS/postgres operations before treating them as failed.
  • watchdog.safety_margin (default 5s): the watchdog fires ttl - safety_margin seconds after the last successful main-loop pet.

Concretely with defaults: if the primary’s main loop fails to complete at T=0, it has until T=25 seconds (ttl - safety_margin) to recover before the kernel resets the box. Meanwhile, the lock expires at T=30s and surviving replicas race for it. The 5-second buffer between watchdog fire and lock expiry ensures the demoted primary is provably stopped before another node takes the lock. If you shorten ttl, you shorten failover time but also reduce that safety margin — go below ttl: 20, loop_wait: 5, retry_timeout: 5, safety_margin: 3 only after you have tested every component for latency under load. Disabling the watchdog entirely (watchdog.mode: off) trades split-brain protection for slightly faster startup; do not do this in production.

Bootstrap strategies

Bringing up a new Patroni cluster, or adding a replica to an existing one, requires deciding how the new node’s PGDATA gets initialized. Patroni supports three bootstrap methods.

The first is initdb — used only when you are creating the cluster from scratch. Patroni runs initdb on the first node, applies the configuration, and starts as primary. Replicas then bootstrap from the running primary.

The second is pg_basebackup — the default for adding a replica. Patroni runs pg_basebackup --pgdata=$PGDATA --host=<primary> --wal-method=stream to take a fresh base backup from the leader and then starts streaming replication. This works for clusters of any size but takes time proportional to the data volume; for a 500 GB cluster on 10 Gbps networking, expect 20-40 minutes of streaming before the replica catches up.

The third is replica_method: pgbackrest (or any custom external method) — use this when you have a backup pipeline that can restore faster than streaming from the primary. The standard pattern is pgbackrest --stanza=main --type=standby restore, which downloads the latest full backup plus required WAL from object storage in parallel and gets you a usable PGDATA in a fraction of the time pg_basebackup takes — particularly for large clusters where the streaming copy is bottlenecked on a single primary’s network. This also reduces load on the primary during replica rebuilds, which matters during incidents.

bootstrap:
  dcs:
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576
    synchronous_mode: true
    synchronous_node_count: 1
    postgresql:
      use_pg_rewind: true
      use_slots: true
      parameters:
        wal_level: replica
        hot_standby: 'on'
        wal_keep_size: 256MB
        max_wal_senders: 10
        max_replication_slots: 10
        max_connections: 200
        archive_mode: 'on'
        archive_command: 'pgbackrest --stanza=main archive-push %p'

  method: pgbackrest
  pgbackrest:
    command: /usr/bin/pgbackrest --stanza=main --type=standby restore
    keep_existing_recovery_conf: false
    no_params: true

use_slots: true tells Patroni to use replication slots, which guarantees the primary retains WAL needed by each replica even if the replica falls behind. Without slots, a lagging replica that exceeds wal_keep_size is broken and must be re-initialized; with slots, the primary just builds up WAL until the replica catches up — at the cost of unbounded disk growth on the primary if a replica goes missing. Either choice has a failure mode; slots plus alerting on replica lag is the right default.

Failover behavior

A primary dies. The leader lock in etcd is no longer renewed. After ttl seconds, surviving replicas detect the missing lock, evaluate their LSN positions, race for the lock, and the winner promotes itself. HAProxy’s health checks on /leader flip the new leader from 503 to 200 and the demoted node (when it returns) from 200 to 503. Existing connections to the demoted primary are reset because of on-marked-down shutdown-sessions; new connections route to the new leader. The application driver reconnects, the connection pool drains and refills against the new write endpoint, and traffic resumes. Total user-visible write-path interruption on a tuned cluster is 30-60 seconds for an unplanned failure, 5-15 seconds for a planned switchover.

That description is a summary. The dynamics — what stretches the no-leader window, when sync promotion preserves zero data loss versus when it does not, what pg_rewind does when the old primary returns, what an application’s retry budget should look like — get a full treatment in the companion piece: Patroni failover behaviour — what actually happens. Read it before you rely on Patroni for a real SLA.

Backup pairing

Patroni does not back up your database. It manages who is primary, where replicas attach, and how the cluster recovers from node loss — but if you DROP TABLE the wrong thing at 3 PM, every replica obediently replays that statement seconds later, and your only path back is point-in-time recovery from a real backup. Pair Patroni with pgBackRest (or WAL-G, or Barman) and treat the backup pipeline as a first-class operational concern.

The integration points are: the primary’s archive_command pushes WAL to object storage (S3, GCS, Azure Blob); pgBackRest runs scheduled backup calls from a dedicated backup host (not from the database hosts — Patroni manages those) to take periodic full and incremental backups; restore operations target the backup repository, not the cluster. The --stanza=main --type=standby restore mode is what makes replica rebuilds fast, and --type=time restores let you recover to any point covered by retained WAL.

The detail that catches teams out: archive_command must coordinate with Patroni’s archive_mode: on. If Patroni’s cluster spec says archive_mode: on but archive_command: /bin/true, you have WAL archiving “enabled” and producing zero retained WAL — your PITR floor is “right now” and you cannot recover from anything older than the streaming replica window. Audit this on day one of every new cluster: run a SELECT pg_switch_wal() and verify a new WAL file appears in object storage within seconds.

Monitoring

The things you alarm on, in order of “this is on fire” priority:

Pager-worthy at any time of day:

  • Cluster has no leader (patronictl list shows no * marker on any node, or the /cluster endpoint reports leader: null).
  • Synchronous replication is lost (pg_stat_replication.sync_state shows no sync row when synchronous_mode: on).
  • More than one node thinks it is primary (this should be impossible with the watchdog — page on it anyway, because if it ever fires the cluster is corrupting silently).
  • etcd lost quorum (etcdctl endpoint status shows IS LEADER: false on every member; or etcdctl member list returns errors).

Ticket-worthy during business hours:

  • Replication lag on any replica > 16MB sustained 5 minutes (rising trend).
  • pg_stat_archiver.last_failed_wal non-NULL within last hour.
  • Patroni state has transitioned more than 3 times in the last hour without an operator action (cluster is flapping).
  • Disk free on any PostgreSQL node < 20% (WAL accumulation can fill a disk fast under replica lag).
  • A replica is restarting Patroni repeatedly without rejoining.

Useful dashboards (not alerts): WAL produced per minute, checkpoint completion percentage, pg_stat_replication.write_lsn deltas per replica, etcd raft proposal latency, HAProxy backend up/down events, Patroni REST /cluster JSON snapshots over time. The Prometheus exporters for Patroni (patroni_exporter), PostgreSQL (postgres_exporter), and etcd (built into etcd itself) give you everything you need; the work is wiring the dashboard and tuning the alert thresholds so they fire on real signal.

Operational runbook

The cluster only matters if you can operate it. The procedures that come up in real life:

Planned switchover (zero-downtime upgrades, host maintenance):

patronictl -c /etc/patroni/patroni.yml switchover \
  --leader pg-01 \
  --candidate pg-02 \
  --force

Patroni demotes the current leader, promotes the candidate, and reattaches the old leader as a replica. Application impact is the connection-reset window — sub-15 seconds on a tuned cluster. Use this for rolling minor-version upgrades (pg_upgrade is not needed for 16.4 -> 16.5; just apt install postgresql-16=16.5... on each replica, restart Patroni, switch over, then upgrade the demoted primary).

Unplanned failover (primary dies):

Nothing to do. Patroni handles it. The on-call’s job is to confirm via patronictl list that a new leader is up and lag-clean, then triage why the old primary died after the dust settles. Resist the urge to patronictl reinit a node that is recovering on its own — pg_rewind is faster than a full re-init if the timelines diverged less than the size of the cluster.

Restoring a failed primary as a new replica:

When the dead primary returns, Patroni attempts pg_rewind against the new leader if use_pg_rewind: true is set. This works when the divergence is small (a few WAL segments). If pg_rewind fails (timelines too divergent, missing files), Patroni falls back to the configured replica_method — usually pgbackrest restore — which gets the node back as a replica in minutes-to-tens-of-minutes instead of hours. Watch patronictl list until the rejoined node shows Running and lag is zero. If it sits in start failed for more than a few minutes, check journalctl -u patroni on that host.

Cluster rebuild (last-resort recovery):

If all nodes are damaged or the cluster is unrecoverable, the procedure is: stop all Patroni daemons, restore the most recent backup to one host via pgbackrest restore, bootstrap a new Patroni cluster pointing at that PGDATA with bootstrap.initdb removed and the restored data dir intact, then let the other nodes bootstrap as replicas via pg_basebackup or pgbackrest. Test this procedure in a non-production environment before you need it. Practice it under simulated incidents — see Patroni quarterly failover drill for the cadence we recommend.

When you should not run your own Patroni

Patroni is well-designed software, but running it well takes roughly a year of operational learning per team. The reading is straightforward; the hard part is the operational instincts — when to switch over versus wait, when pg_rewind is safe versus when you need a clean re-init, what your sync-promotion data-loss window actually is under your write pattern, when an etcd hiccup is going to roll into a Patroni state-machine confusion. You learn that by running the cluster through real failures, ideally including ones that did not turn into incidents because the cluster handled them right.

If your team is shipping product features and the database is supposed to be invisible, running Patroni yourself is opportunity cost. The discipline of monthly patching, quarterly failover drills, replication-lag triage, and pg_rewind/re-init decisions is a permanent on-call burden. Stack Harbor’s Clustered Environments solution covers Patroni-managed PostgreSQL HA as a standard offering, with the operational practices already in place — etcd placement reviewed, watchdog enabled, quarterly drills on the calendar, backups paired with the cluster, monitoring tuned, and senior engineers on Sev-1 escalation. Pricing scopes to drivers like cluster size, replica count, and recovery objectives — discovery first, fixed quote after. If you would rather keep your existing cluster and have us run it day-to-day, that fits under Managed Operations.

Be honest about whether you want to be a database operations team. Most product engineering organizations should not.

See also