Home›Learn›PostgreSQL 4: high availability with Patroni
PostgreSQL · Chapter 4 · High availability

PostgreSQL high availability with Patroni

The primary just died. Who promotes a replica, and how do you make sure the old one never comes back as a second primary?

PostgreSQL ships with replication, but not with failover. Something outside the database has to notice the primary is gone, pick the best replica, promote it, and point the app at it. Patroni is the most common way to do that.

Why this chapter matters

Why we need high availability at all

Every server fails eventually: a disk, a kernel panic, a zone outage, or just the patch you have to install on Tuesday. With one database, each of those is an outage for every customer at once. High availability turns them into a few seconds that most users never notice.

What we are protecting

Revenue and trust. Checkout, login, payments: when the database is down, the whole product is down, and nothing in the app can work around it.

What we achieve

Two numbers. RTO: how fast writes work again, seconds instead of the 15 to 30 minutes a manual failover takes. RPO: how much confirmed data a failure can lose, ideally zero.

Maintenance without downtime

The quiet win. With a spare node, patches, upgrades and hardware swaps become rolling switchovers during the day, not maintenance windows at night.

What it is not

A backup. A bad DELETE reaches every replica in milliseconds. You still need backups and point-in-time recovery.

What the targets mean in minutes

99.9%
8.8 h a year
99.99%
53 min a year
99.999%
5 min a year
One manual failover
15 to 30 min
Availability targetDowntime allowed per yearPer monthWhat it takes
99.9% ("three nines")8.8 hours43.8 minutesOne server and good backups can almost do it, if nothing big breaks.
99.99% ("four nines")52.6 minutes4.4 minutesAutomatic failover. One manual 3 a.m. failover uses most of the year.
99.999% ("five nines")5.3 minutes26 secondsAutomatic failover in seconds, and maintenance with no downtime at all.

The arithmetic is why teams automate: a single manual failover at 3 a.m. can spend a whole year of a 99.99% budget.

How companies usually set it up

  1. Three nodes across three availability zones in one region, with automatic failover. This is the standard production setup; losing a zone loses one node.
  2. A replica in a second region for disaster recovery, usually asynchronous, promoted by a person or a runbook when a whole region is gone.
  3. A proxy or pooler in front, so the app has one address and never needs to know which server is primary.
  4. Backups and continuous WAL archiving to object storage, with restores tested on a schedule.
  5. Or a managed service (RDS, Aurora, Cloud SQL) that does the same three jobs for you, with less control.

Running it on thousands of servers

Nobody configures a thousand clusters by hand. At that scale, high availability is a product the database team runs, with the same few parts everywhere:

Desired state in code

Each cluster is a file in Git: size, version, replicas, settings. Terraform, Ansible or a Kubernetes operator turns the file into servers, and a pull request is how anything changes.

One failover tool, everywhere

The same Patroni (or orchestrator, or Group Replication) setup on every cluster, so a failover at 3 a.m. behaves exactly like the one you tested.

Service discovery, not hard-coded hosts

Consul, etcd or a proxy layer tells every app where the primary is right now. Failover updates one record, not a thousand config files.

Fleet automation with guardrails

Rolling patches and upgrades one node, then one cluster, at a time. Rate limits so a bad network day cannot trigger a hundred failovers at once.

Proof, not hope

Scheduled switchovers and game days that kill a primary on purpose, restore tests from backup, and dashboards that show every cluster's role, lag and last failover.

Runbooks a machine can follow

The common incidents are scripted and safe to run; the rare ones page a person with the evidence already gathered. That is the idea behind the DBA agent on this site.

Step through it: how a team patches a cluster with no downtime.

What it looks like at real companies

Now let us look at how one PostgreSQL cluster does it, starting with how it was done before tools like Patroni existed.

The idea behind it

Before Patroni: failover by hand

PostgreSQL 9.0 (2010) added streaming replication: a standby receives the WAL as it is written and replays it. 9.1 added synchronous replication. But the database never decides on its own to promote a standby. That was always a person, or a script.

  1. Notice the primary is gone. Monitoring pages you. Is it really down, or is the network between you and it down?
  2. Pick a standby. Compare pg_last_wal_replay_lsn() on each one and choose the one furthest ahead.
  3. Promote it. pg_ctl promote, or SELECT pg_promote(); since PostgreSQL 12. Before 12 this was a trigger file named in recovery.conf.
  4. Move the app. Change DNS, a virtual IP or the pooler config, and wait for caches to expire.
  5. Fence the old primary. Make sure it cannot come back and accept writes. If it does, you have two primaries and two diverging histories: split brain.
  6. Rebuild it as a standby. A full pg_basebackup, or pg_rewind (since 9.5) to rewind it to the point where the histories split.

Expect 15 to 30 minutes at 3 a.m., done well. Done badly, it is split brain and lost orders. Tools like repmgr and Pgpool-II scripted parts of it. Patroni, released by Zalando in 2015, took a different approach: let a consensus store decide who the leader is, so two nodes can never both believe it.

Step through it:

Explained clearly

What Patroni does

Listen, 3 min 24 s
1

The problem

A replica is only useful if something promotes it fast and safely. A script that promotes on a timeout can promote while the old primary is still alive behind a network split, and then both take writes.

2

What it is

Patroni is a small Python agent that runs next to every PostgreSQL server and controls it: it starts, stops, promotes and demotes PostgreSQL itself. The agents agree on who is the leader through a distributed configuration store (DCS), usually a three-node etcd cluster. The leader holds a key in etcd with a time to live. Only the holder of that key may run as primary.

3

Follow one failover

  1. The leader renews its key every loop_wait (10 s). The key lives for ttl (30 s).
  2. The primary's server dies. Nobody renews the key.
  3. Up to 30 s later the key expires. Each replica checks that it is healthy and no more than maximum_lag_on_failover (1 MB of WAL) behind.
  4. The best replica takes the key in etcd. etcd lets only one of them win.
  5. The winner's Patroni promotes its PostgreSQL. The others follow the new primary.
  6. HAProxy asks each node's Patroni API /primary, sees the new answer, and sends new connections there.

For your app: typically 30 to 45 seconds without writes, up to about 50, with no person involved.

4

What to watch

  • Fencing comes from the key. A primary that cannot reach etcd demotes itself, so a cut-off primary stops taking writes. That assumes Patroni itself is running: turn on the watchdog (watchdog: mode: required, Linux /dev/watchdog) so a hung Patroni resets its host. If etcd itself goes down, every primary demotes, unless you turn on failsafe_mode.
  • Asynchronous means a failover can lose the last commits. synchronous_mode: on makes Patroni promote only a synchronous standby. If no standby can be synchronous, the primary keeps writing unprotected; synchronous_mode_strict: on blocks writes instead.
  • Timers follow a rule: loop_wait + 2 × retry_timeout ≤ ttl. Shorter timers mean faster failover and more false alarms.

Step through it:

Running on Kubernetes? See PostgreSQL on Kubernetes with CloudNativePG, which does failover without Patroni. Running hundreds of clusters? See how a team runs 1,000 databases.

The setup

Three PostgreSQL nodes, three etcd nodes, one proxy

Your appone addressHAProxy:5000 writes · :5001 readspg1 · primaryPatroni holds the leader keypg2 · replicastreaming, sync standbypg3 · replicastreamingchanges flowto every copyetcd × 3leader key, TTL 30 s

Put etcd on three separate machines or zones, so losing one keeps a majority. Two PostgreSQL nodes work, three give you a spare after a failover. HAProxy checks Patroni's REST API on port 8008, not PostgreSQL itself.

Step by step

Set it up

  1. Run etcd on three hosts and check it: etcdctl endpoint health --cluster.
  2. Install PostgreSQL and Patroni on each database host (pip install "patroni[etcd3]" or your distribution's package). Do not run initdb yourself: Patroni bootstraps the first node and clones the others.
  3. Write /etc/patroni.yml on each node. Only name and the addresses change between nodes.
scope: orders                     # cluster name, the same on every node
name: pg1                         # unique per node
restapi:
  listen: 0.0.0.0:8008
  connect_address: 10.0.0.11:8008
etcd3:
  hosts: 10.0.0.21:2379,10.0.0.22:2379,10.0.0.23:2379
bootstrap:
  dcs:                            # stored in etcd, shared by all nodes
    ttl: 30
    loop_wait: 10
    retry_timeout: 10
    maximum_lag_on_failover: 1048576
    synchronous_mode: on
    postgresql:
      use_pg_rewind: true
      parameters:
        wal_level: replica
        wal_log_hints: "on"       # pg_rewind needs this or data checksums
        max_wal_senders: 10
        max_replication_slots: 10
postgresql:
  listen: 0.0.0.0:5432
  connect_address: 10.0.0.11:5432
  data_dir: /var/lib/postgresql/18/main
  bin_dir: /usr/lib/postgresql/18/bin
  authentication:
    superuser:   { username: postgres,   password: change-me }
    replication: { username: replicator, password: change-me }
  1. Start Patroni on pg1 first (systemctl start patroni), then pg2 and pg3. The first one to start initializes the cluster and takes the key; the others clone it with pg_basebackup.
  2. Check the cluster: patronictl -c /etc/patroni.yml list shows one Leader, the Sync Standby and the lag of each replica.
  3. Point HAProxy at the REST API:
listen orders_write
  bind *:5000
  option httpchk GET /primary
  http-check expect status 200
  default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
  server pg1 10.0.0.11:5432 check port 8008
  server pg2 10.0.0.12:5432 check port 8008
  server pg3 10.0.0.13:5432 check port 8008

listen orders_read
  bind *:5001
  option httpchk GET /replica
  http-check expect status 200
  default-server inter 3s fall 3 rise 2
  server pg1 10.0.0.11:5432 check port 8008
  server pg2 10.0.0.12:5432 check port 8008
  server pg3 10.0.0.13:5432 check port 8008

The app connects to HAProxy on 5000 for writes and 5001 for reads. /primary answers 200 only on the leader, so HAProxy never sends a write to a replica.

When it breaks

A failover, second by second

  1. 0 spg1 loses power. Its last WAL already reached pg2, the synchronous standby.
  2. 3 to 9 sHAProxy's checks to pg1 fail three times. It drops pg1 and closes its sessions.
  3. up to 30 sThe leader key in etcd expires, because pg1 stopped renewing it.
  4. +1 looppg2 and pg3 notice. pg2 is the sync standby, so only pg2 may take the key. It does.
  5. +1 to 2 sPatroni on pg2 promotes PostgreSQL. pg3 now follows pg2.
  6. +3 to 6 sHAProxy sees /primary answer 200 on pg2. Writes resume.
  7. laterpg1 comes back. Patroni sees it is no longer leader, runs pg_rewind, and starts it as a replica of pg2.

A planned switchover is much faster, because the leader hands over on purpose: patronictl switchover --leader pg1 --candidate pg2. Use it for upgrades and maintenance.

What goes wrong

What breaks, and what Patroni does

FailureWhat happensWhat you do
Primary host diesFailover in typically 30 to 45 s, up to about 50.Nothing. Check patronictl list afterwards.
Network cut between the primary and etcdThe primary cannot renew its key and demotes itself. A replica on the majority side takes over.Nothing. That is the fencing working.
etcd loses its majorityNobody can hold the key. The primary demotes to read-only, unless failsafe_mode is on and all members can still reach each other.Fix etcd first. Keep etcd on separate hosts from the databases.
Every replica is too far behindNo replica is within maximum_lag_on_failover, so nobody is promoted.Decide by hand: patronictl failover --candidate pg3 promotes it and accepts the data loss.
You need to work on a node without a failoverPatroni would react to a stopped PostgreSQL.patronictl pause, do the work, patronictl resume.
A replica is broken or very far behindIt keeps streaming, or stays stuck.patronictl reinit orders pg3 re-clones it.

Step through it:

Monitoring

What to watch

patronictl -c /etc/patroni.yml list            # leader, sync standby, lag, timeline
curl -s http://10.0.0.11:8008/patroni          # this node's state as JSON
etcdctl endpoint health --cluster              # is the DCS healthy
SELECT application_name, state, sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS bytes_behind
FROM pg_stat_replication;

Alert on: no leader, more than one leader (should be impossible; check your timers), a replica behind by more than maximum_lag_on_failover, and etcd members down. Page playbooks: no leader, or the primary went read-only, failovers that should not happen.

Next · chapter 5Running it as a DBREWhat I watch, the logs, the settings, the commands← Chapter 3: What happens on every write
Part 1 of 4 · Learn · 56 pagesAll pages

How do databases actually work? From one row on disk to transactions: the words you need, PostgreSQL, MySQL and MongoDB from the files up, then Redis, Cassandra and vector search, side by side, and the query and concurrency traps.

Start 1: the basicsStart 2: ten conceptsStart 3: how a query travelsStart 4: napkin mathThe courseShort videosPostgreSQL 1: why PostgreSQLPostgreSQL 2: how it stores your dataPostgreSQL 3: what happens on every writePostgreSQL 4: high availability with PatroniPostgreSQL 5: running it as a DBREPostgreSQL 6: when it breaksPostgreSQL on Kubernetes: CloudNativePGMySQL 1: why MySQLMySQL 2: how it stores your dataMySQL 3: what happens on every writeMySQL 4: high availability with InnoDB ClusterMySQL 5: running it as a DBREMySQL 6: when it breaksMySQL failover with OrchestratorMySQL on Kubernetes: the Percona operatorsMongoDB 1: why MongoDBMongoDB 2: how it stores your dataMongoDB 3: what happens on every writeMongoDB 4: high availability with replica setsMongoDB 5: running it as a DBREMongoDB 6: when it breaksMongoDB on Kubernetes: the Percona operatorB-tree and LSM treeRedis 1: why RedisRedis 2: how it stores your dataRedis 3: high availabilityRedis 4: running it as a DBRERedis 5: when it breaksCassandra 1: why CassandraCassandra 2: how it stores your dataCassandra 3: high availabilityCassandra 4: running it as a DBRECassandra 5: when it breaksVector databases 1: why vector searchVector databases 2: how it stores your dataVector databases 3: high availabilityVector databases 4: running it as a DBREVector databases 5: when it breaksDatabase familiesEngines side by sideQueries that look fine and are notLost updates and write skewMany servers 1: keep a copy runningMany servers 2: who is the leaderMany servers 3: CAP as settingsMany servers 4: unique IDsMany servers 5: split the dataMany servers 6: across servicesMany servers 7: a thousand databasesStaff path, zero to architect