PostgreSQL high availability with Patroni, etcd and HAProxy

Patroni, etcd and HAProxy can keep a PostgreSQL primary available when a server fails, but only if the quorum, routing and failover behavior are designed and tested before go-live.

On this page

PostgreSQL high availability with Patroni, etcd and HAProxy: when your team needs it

Choose Patroni, etcd and HAProxy when a PostgreSQL primary must keep accepting writes after a server fails, and your team wants the promotion, fencing and client routing automated rather than run by hand at 2 a.m. PostgreSQL does not detect a primary failure or promote a standby by itself. The PostgreSQL failover documentation is explicit that external software must watch the primary, decide when to promote and tell clients where to connect. This stack splits that job across three components: Patroni runs on each database node and manages the PostgreSQL instance, etcd stores the shared leader lock and cluster state so only one node can hold the leader role, and HAProxy routes application connections to whichever node currently holds the leader role.

Each component has a narrow job, and each one is a dependency you will operate. Patroni decides promotion and demotion and rewrites the replication setup on the nodes. etcd is the consensus store that makes that decision safe, so it needs an odd number of members and its own monitoring, backups and disk planning. HAProxy is the routing layer, usually fed by Patroni's REST API health checks, so clients do not need to know which node is primary. Teams that already run a consensus store, or that prefer a virtual IP managed by the platform, can replace parts of this design, but they must still prove that a single leader is enforced everywhere.

Compare this stack with alternatives before committing. repmgr and pg_auto_failover also automate failover, with different trade-offs in witness design, monitor placement and how they handle fencing. A managed database service removes the operational work, but it moves the infrastructure outside your control. Confirm with your own architects which constraints apply: whether you can run three independent failure domains, whether your team has operated a distributed key-value store, and whether your recovery targets need an automated switchover or a documented manual runbook. If those answers point toward a small team with no consensus store experience, a simpler tool may fit better.

Configuration choices and when each fits

This table compares the main design choices for a Patroni cluster: where etcd runs, how clients reach the leader, how the leader replicates and how the TTL and loop timing are set. Read each row against your own failure domains and the team that will operate the cluster, since the right choice depends on which failures you most need to survive.

DecisionOptionTrade-offWhen it fits
etcd placementDedicated etcd nodesFailure of a database host does not remove a DCS member, but adds hosts to patch and monitorTeams that want etcd failures isolated from PostgreSQL maintenance
etcd placementCo-located with PostgreSQLFewer servers and lower cost, but a host failure can take a database member and a DCS member togetherSmall estates where the three hosts already span separate failure domains and disk I/O is isolated
Client routingHAProxy with Patroni health checksAdds a layer to run and make highly available, and clients only need one addressMixed client stacks or teams that want routing decided by a health endpoint rather than by DNS changes
Client routingVirtual IP moved by the leaderSimpler data path with no proxy hop, but depends on network support for moving addresses between hostsNetworks where you control layer 2 or can use an equivalent mechanism and your operators know how to troubleshoot it
Leader replicationSynchronous standbyCommits wait for a standby, so write latency rises with network distance and a stalled standby can block writesWorkloads where losing acknowledged transactions on failover is not acceptable and the link is low latency
Leader replicationAsynchronous standbyCommits return without waiting, so writes stay fast, but recent transactions can be lost on failoverWorkloads that accept a bounded loss window or use cross-site links where waiting would be too slow
Patroni loop timingShort TTL and loop waitFaster detection of a failed leader, but more sensitivity to brief network or disk stalls that cause false failoversEnvironments with stable networks and a tested fencing or watchdog approach
Patroni loop timingLonger TTL and loop waitFewer false failovers during transient stalls, but a longer period before a dead leader is replacedEnvironments with variable latency or shared storage pressure, where the outage window is accepted in writing

Building the three-node cluster in order

This sequence takes three empty servers to a Patroni-managed PostgreSQL cluster in which an etcd quorum holds the leader lock, HAProxy sends client traffic only to the current primary, and each step has a check that confirms it worked before the next one starts.

  1. Prepare nodes and network paths

    The platform team provisions three database nodes, plus the etcd and HAProxy placement you have chosen, and confirms that every node can resolve the others by name and reach the PostgreSQL, Patroni REST API, etcd client and peer ports. Time sync, the same PostgreSQL major version on every node, and firewall rules are set here. Check: from each node, a name lookup and a TCP connection to every other node's ports succeed, and the PostgreSQL version reported by each node matches. Confirm port numbers and placement against your own network design, because they depend on your environment.

  2. Form the etcd quorum first

    Install etcd on three members and start them with an initial cluster definition that lists all three peers, so Patroni has a distributed store to hold the leader key before any database starts. Keep etcd on separate hosts or failure domains from the database where your design allows, since losing etcd quorum stops automatic failover. Check: the etcd member list shows three started members, and endpoint health reports every member healthy with one elected leader. Do not continue until this passes.

  3. Bootstrap the leader with Patroni

    Install Patroni and PostgreSQL on the first node, then write its configuration with the scope name, the etcd endpoints, the REST API address, the PostgreSQL data directory, and the replication and superuser credentials, which should come from your secrets store. Start Patroni on this node only. It initializes the database and writes the leader key to etcd. Check: the Patroni REST API on that node returns a leader role, and the leader key appears in etcd under the cluster scope.

  4. Create replicas from the leader

    Start Patroni on the second and third nodes with the same scope and etcd endpoints. Each node takes a base backup from the leader and begins streaming replication as a hot standby. Replication roles and pg_hba.conf entries must allow these nodes to connect, which you confirm in your own configuration. Check: patronictl list shows one Leader and two Replica members in the streaming state, with low replication lag on each replica.

  5. Configure HAProxy health checks against the Patroni REST API

    Create two HAProxy frontends, one for writes that routes only to the leader and one for reads that routes to replicas, or leave reads out if your application does not use them yet. Health checks call the Patroni REST API endpoints that report role, so HAProxy marks the old primary down after a failover and promotes the new one without manual edits. Check: the HAProxy stats page shows exactly one backend server up for the write pool, and it matches the Leader in patronictl list.

  6. Verify routing and a controlled switchover

    From an application-like client, connect through the HAProxy write address and run a query that reports whether the session is on a primary, such as checking pg_is_in_recovery(). Then run a planned switchover with patronictl, confirm the new leader, and repeat the client check to see that traffic moved without changes on the client. Check: the client reconnects to the new leader within the window your application can tolerate, and patronictl list shows the old primary rejoining as a replica.

  7. Confirm replication and recovery before go-live

    Verify that writes on the leader appear on both replicas, that synchronous or asynchronous mode matches your recovery requirements, and that backups and WAL archiving work independently of Patroni. Record the replication, etcd and HAProxy health results as the baseline for later failure tests. Check: a test row written through the proxy is visible on each replica, and the baseline configuration is stored in version control. The failure tests that prove failover works belong in a separate runbook before go-live.

Failure tests to run before go-live

A Patroni cluster is only proven once it has been broken on purpose. The tests below cover process, service, network, coordination and planned-change failures, and each one should be run against the same recovery targets the business agreed before go-live. Record the new leader, the client reconnection time and the data loss observed in every run.

Kill the leader PostgreSQL process

Send a hard kill to the postgres process on the current leader, not a clean stop, so the test resembles a crash. Confirm that Patroni detects the failure, promotes a healthy replica and that HAProxy routes new connections to the new leader. Record how long applications took to reconnect and whether any committed transactions are missing, which depends on your synchronous settings.

Stop the Patroni service

Stop the Patroni service on the leader while leaving PostgreSQL running if your runbook expects that case. Check whether PostgreSQL shuts down with the agent, whether the leader key in etcd expires as configured, and whether a replica is promoted without two nodes accepting writes. Confirm that the old leader rejoins as a replica once Patroni is restarted.

Isolate the leader from etcd

Block the leader's traffic to the etcd members with a firewall rule while the database itself remains reachable to clients. This tests whether the leader demotes itself when it cannot renew its lock, which is the condition that prevents split-brain. Watch for any write acceptance on the isolated node after its lock expires, and confirm the cluster elects one leader once the network is restored.

Stop one etcd member

Stop a single etcd member and confirm the remaining two keep quorum and the cluster keeps accepting leader changes. Then stop a second member in a separate test to show what loss of quorum looks like, and confirm that Patroni does not promote a replica without a working coordination store. Record how the cluster behaves during each step and how long it takes to restore full membership.

Run a planned switchover

Use patronictl switchover to move leadership to a chosen replica during a quiet window, then compare the observed client interruption with the planned maintenance target. Confirm the old leader becomes a streaming replica, that lag returns to normal and that HAProxy health checks mark the nodes correctly. Repeat the switchover back to the original leader to verify both directions work.

Fail a replica during writes

Stop a replica while a write workload runs against the leader, then check that the leader keeps accepting writes according to its synchronous commit settings. Restart the replica and confirm it catches up from the leader or archive without manual rebuild. Note any write stalls, and confirm that replication slot retention does not fill the leader's disk while the replica is down.

Adapting the design to your infrastructure

On servers you run in your own data centers, the team controls the full stack, which makes the three-node layout straightforward to place. Each PostgreSQL node runs Patroni, and each etcd member should sit on a separate physical host or failure domain so that losing one host does not cost the quorum. HAProxy or a virtual IP can run on dedicated hosts, and the team decides whether routing is a floating address or a health-checked proxy tier.

  • Failure domain placement: Spread the three database nodes and three etcd members across racks or power feeds, and confirm that a single rack loss leaves two etcd members reachable.
  • Hypervisor behavior: If nodes are virtual machines, confirm how the hypervisor handles host failure, live migration and clock drift, because a paused VM can resume after Patroni has already promoted another node.
  • Storage durability: Confirm that the write cache on controllers and hypervisors honors flush requests, since a lost acknowledged write defeats synchronous replication.
  • Floating address handling: If you use a VIP, confirm that gratuitous ARP or routing updates move cleanly on your switches and that the old holder releases the address during failover.
  • Fencing: Decide whether a watchdog device or power control is available on each node, because a node that loses its network can keep accepting writes if nothing stops it.

Confirm these items with your virtualization or hardware team, and test them with a planned host failure before go-live.

Securing etcd, Patroni and replication traffic

A three-node Patroni cluster has several independent trust paths: etcd peer and client traffic, the Patroni REST API, PostgreSQL replication connections, and the admin interfaces operators use to switch roles. Each one needs its own authentication decision, and a gap in any of them can let a client or a stray host change who is primary.

etcd client and peer TLS

Encrypt and mutually authenticate both client traffic from Patroni to etcd and peer traffic between the three etcd members, using certificates issued from an internal CA you control. Patroni holds the leader key in etcd, so write access to that keyspace decides who can become primary. Check that plaintext listeners are disabled and that each Patroni node presents an identity etcd is configured to accept. Confirm the certificate renewal process before the first expiry date, not after.

HA docs

Patroni REST API authentication

The Patroni REST API accepts operations such as switchover, restart and reinitialize, so it needs its own protection. Configure separate credentials for read-only health checks and for control operations, and restrict which source addresses can reach the control endpoints. HAProxy health checks depend on the API, so the read-only path must stay reachable while the control path stays narrow. Confirm the exact options against the Patroni version you deploy.

Replication role and pg_hba.conf entries

Create a dedicated replication role with the REPLICATION attribute and no superuser or data-access privileges. Scope its pg_hba.conf entries to the replication pseudo-database and to the addresses of the three nodes, with TLS required. Application subnets and HAProxy should not be able to match replication lines. Review these entries after every node is added, since a broad address range is the most common way replication access grows unnoticed.

Authentication methods

SCRAM password authentication

Set password_encryption to scram-sha-256 and use scram-sha-256 in pg_hba.conf for both application and replication roles. PostgreSQL 18 deprecates MD5 password authentication in favor of SCRAM, so existing MD5 roles should be found and rotated before an upgrade. Verify that Patroni bootstrap configuration and any pooler in front of the cluster also negotiate SCRAM. Test each role's login from every client path once the cluster is running.

Superuser and replication credential handling

Patroni needs the superuser and replication passwords in its configuration to bootstrap and manage replicas, so those values must not sit in plain text in shared configuration files. Store them in a secrets manager or a root-readable file with restricted ownership, and rotate them through a documented procedure that updates Patroni, PostgreSQL and any dependent service together. Ask who holds the superuser password outside the platform team and whether that access is logged.

Patronictl and HAProxy admin access

Anyone who can run patronictl switchover or reach the HAProxy stats and admin socket can move traffic or take nodes out of rotation. Limit operating system accounts that can read the Patroni configuration, restrict the HAProxy stats listener to an administrative network with its own credentials, and record which operators performed each switchover. Use the same change process for manual failover as for planned maintenance, and rehearse it in a non-production cluster first.

How clients, HAProxy, Patroni and etcd fit together

The diagram starts with client applications connecting to HAProxy, which routes each connection to whichever node Patroni reports as leader through its health endpoint. Three nodes each run Patroni and PostgreSQL alongside an etcd member. The leader holds the leader lock in etcd, and the two replicas receive WAL by streaming replication from the leader. Check that every node sees the same etcd cluster, that only one node holds the lock, and that HAProxy marks only the leader as up.

Client traffic reaches the leader through HAProxy, while etcd holds the leader lock.

Questions teams ask before building Patroni clusters

What drives the cost and effort of building and testing a Patroni cluster?

The cost is mostly labor, and the main drivers are the number of environments, how many nodes and sites are involved, and how much of the surrounding estate must be changed. Cost components include discovery of the current network and identity setup, the etcd quorum and HAProxy or virtual IP routing design, Patroni bootstrap and replica creation, backup and point-in-time recovery integration, and the failure test campaign that proves failover behaves as designed. Ask any quote to list each component separately, state which environments are covered (for example, test, staging and production), and say who provides hardware, hypervisors and load balancers. Testing is often the least visible line item and the one that most affects confidence at go-live.

How long does a Patroni cluster build take, and what sets that duration?

Duration depends on how quickly access and infrastructure are ready, how many environments must be built in sequence, and how many failure scenarios the test plan includes. Work usually runs in phases: design and sizing, build in a non-production environment, failure testing, then production cutover. Delays most often come from waiting on firewall changes, DNS entries, certificate issuance and approval of the test plan rather than from the Patroni configuration itself. Ask for a written timeline that shows which tasks depend on client input and which milestones require sign-off before the next phase begins.

What must our team provide before the build starts?

The client team typically provides the following before work begins:

  • Three or more Linux hosts or virtual machines for PostgreSQL and Patroni, plus placement for the etcd members, with the failure domains you need
  • Network paths for PostgreSQL (typically port 5432), Patroni REST API, etcd client and peer traffic, and HAProxy listeners, agreed in writing
  • DNS names for the cluster endpoint and each node, and a decision on whether a virtual IP is used
  • TLS certificates or an internal CA process, and a plan for certificate renewal
  • Administrative access, change windows and a named contact for approvals

Confirm each item with your network, security and identity teams early, because these approvals usually set the pace of the project.

Can an internal team build a Patroni cluster without outside help?

Yes, a capable internal team can build a Patroni cluster, provided it has PostgreSQL administration skills, experience running a distributed key-value store such as etcd, and time to test failures properly. The harder part is usually not the first working cluster but proving that failover, fencing, client reconnection and backup restores behave correctly under faults. Ask whether your team has run failover drills before, who will own the runbooks, and who will be on call when something unusual happens. A partner can cover some or all of the build, testing and knowledge transfer, with the split defined in the written scope.

What recurring work follows a Patroni cluster go-live?

Recurring work includes minor PostgreSQL updates, Patroni and etcd version maintenance, certificate renewal, backup verification restores, monitoring review and periodic failover drills. Minor PostgreSQL releases do not change the storage format, so they mainly require replacing executables and restarting, but they still need a planned change window and a tested rollback path. Major version upgrades are a separate project, and they should be scheduled against the community support dates for each release. Ask for a schedule of these tasks and clarify whether they are performed by your team, by a retainer, or both.

How is a fixed-scope Patroni engagement agreed?

Most engagements are fixed-scope, meaning the scope, deliverables and timelines are agreed in writing before work starts. A usable written scope names the environments in scope, the node count and topology, the routing design, the backup integration, the failure tests to be run, the documentation delivered, and the acceptance criteria for go-live. It also states the client inputs and the change control process if requirements move. DeployOpen does not publish a price list, so a quote follows from that written scope. Ask for the assumptions behind the quote so you can see how a change in scope would affect cost and timing.

What should we check in a quote for a Patroni cluster?

Check that the quote lists each deliverable and the environments it covers, the number of failure scenarios tested, whether backups and point-in-time recovery are included, and what documentation and operator training are delivered. Confirm which items depend on your inputs, such as network changes or certificate issuance, and how delays caused by those inputs are handled. Ask whether ongoing support is separate, and what it covers. Finally, confirm acceptance criteria so both teams agree in advance what a passing cluster looks like.

How DeployOpen scopes and delivers Patroni clusters

DeployOpen plans, builds, tests and documents a three-node Patroni cluster with its etcd quorum and HAProxy routing inside infrastructure you control. Each engagement starts from a written scope, so failover behavior, routing and the go-live failure tests are agreed before the build begins.

How we scope

  • Confirm the PostgreSQL major version, Patroni release and etcd layout against your servers, network and support policy before the build starts.
  • Agree in writing how clients reach the leader, whether through HAProxy health checks, a virtual IP or both.
  • Define the failure tests, acceptance criteria and documentation that the fixed-scope agreement will cover.

How we build

  • Install PostgreSQL, Patroni and etcd on your hosts, then bootstrap the cluster and create the two replicas.
  • Configure etcd for quorum across three members and verify that a single member loss leaves the cluster writable.
  • Set up HAProxy or VIP routing and test that client connections follow the leader after each planned switchover.

How we hand over

  • Run the agreed failure tests, including killed PostgreSQL processes, stopped etcd members and network cuts, and record measured results.
  • Deliver runbooks for switchover and failover with patronictl, covering the steps an operator follows under pressure.
  • Document the configuration, topology and recovery decisions so your own team can review and maintain the cluster.

How we support

  • Ongoing support, upgrades and continuous testing are available as retainers after handover.
  • Plan minor and major PostgreSQL upgrades on the cluster as a separate written scope, with rollback steps agreed in advance.
  • Retest routing and failover after changes to hosts, network paths, etcd membership or Patroni configuration.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.