Preventing split-brain in PostgreSQL clusters

A split-brain leaves two servers accepting writes to the same data. This page explains how it happens in PostgreSQL clusters and which leader locks, watchdogs, fencing and partition tests keep it from happening.

On this page

Why PostgreSQL split-brain prevention matters before go-live

Split-brain means two nodes accept writes as primary at the same time. A team running one primary and several standbys expects a server failure to promote a standby and keep the application writing. Without protection, the old primary may still be alive, reachable by some clients, and accepting writes that the new primary never receives. Those writes diverge, and reconciling them is slow and often impossible. Prevention rests on two controls: promotion happens only when a single node holds exclusive ownership of the leader role, and the old primary is fenced so it cannot accept writes once it loses that role.

PostgreSQL does not detect a failed primary and promote a standby on its own. The PostgreSQL failover documentation states that external software must detect the failure and notify the standby, so the safety of the cluster depends on that software and on how it is configured. In scope for this topic are Patroni with a distributed configuration store (DCS) that holds the leader lock, repmgr with repmgrd and its fencing hooks, and general fencing that cuts off the old primary at the host, storage or network layer. Before go-live, confirm which of these components owns promotion in your design, who is paged when it acts, and whether any step relies on an operator remembering to stop a server.

Treat split-brain protection as a property you test, not one you assume. Ask your team or partner to name the exact condition that allows promotion, the timeout that releases a lock or fences a host, and the path a client takes to reach the primary after failover. Plan a partition test that isolates the primary from the DCS or witness while clients still reach it, and confirm that the old primary stops accepting writes. Record the results before production traffic arrives. The later sections describe how each tool is built and how to run these tests.

How leader locks and fencing decide who may write

The diagram starts with the primary holding the leader key in the distributed configuration store (DCS), which sits on the other side of a trust boundary from the database hosts. A network partition cuts the primary off from the DCS, so its lock expires and a standby can acquire it. Before the standby is promoted, a watchdog or fencing step must stop the old primary from accepting writes. Check that the expiry timing, the watchdog action and the fencing step all complete in the right order.

Leader lock expiry and fencing before a standby is promoted.

Which protection layer fits Patroni, repmgr and pg_auto_failover

Patroni keeps cluster state, including which node holds the leader key, in a distributed configuration store (DCS) such as etcd, Consul or ZooKeeper. A node may run as primary only while it holds that key. The key expires if it is not renewed, so a node that loses contact with the store must demote itself, and a standby can acquire the key only after expiry. This blocks a second primary only when the store keeps quorum and the old primary can actually demote. It does not cover a PostgreSQL process that keeps running and accepting writes while Patroni is unable to act, and it does not stop clients that connect directly to an old primary.

  • Lock ownership: Only the holder of the leader key can be promoted, so two nodes cannot both win the same election through Patroni.
  • Store quorum: etcd, Consul or ZooKeeper must keep quorum for leader elections to proceed. Losing quorum usually freezes failover rather than creating a second primary.
  • Demotion on lost contact: The old primary must notice it cannot renew the key and step down. Confirm how quickly this happens in your Patroni release.
  • Client routing: A load balancer or virtual IP that follows the leader should use Patroni's health checks so that writes stop reaching a demoted node.
  • Frozen processes: A host or PostgreSQL process that stalls and then resumes after the key expires is a gap that the DCS alone does not close.

Confirm the DCS version, the leader key timing settings and the demotion behavior for the Patroni version you run, then test them under a network partition.

What each control does and where it fails

No single control stops split-brain on its own. Each card below names what a control does, the failure it prevents, and the gap it leaves, so the controls can be layered and tested together.

DCS leader locks and TTL

A distributed configuration store such as etcd holds a leader key with a time-to-live, and only the node holding the key may act as primary. Patroni uses this pattern, so a primary that loses contact with the store must stop accepting writes once its lock expires. The gap is timing: if the TTL is longer than the time a stale primary keeps accepting writes, two nodes can briefly believe they lead. Check the TTL, loop and retry settings against your failover tests, and confirm the store has its own quorum.

HA docs

Linux watchdog device

A watchdog is a hardware or kernel timer that reboots the host unless a process keeps resetting it. Patroni can use one so that a primary that hangs or loses its leader lock is forced down even when its own software cannot act. The gap is coverage: a watchdog protects only the host it runs on, not a network path or a storage fault. Confirm the device exists on every node, that it is armed by the service, and that it is tested by freezing the host.

Fencing scripts

A fencing script powers off or isolates the old primary before a standby is promoted, so the old server cannot accept writes when it returns. repmgr supports fencing hooks around failover. The gap is access: fencing depends on out-of-band power control, a hypervisor API or a switch port command, and these can fail at the same moment as the server. Ask who owns the fencing credentials, how long a fence action takes, and what the script does when the fence device is unreachable.

Witness nodes for quorum

A witness is a small third participant that votes on which side of a network partition may promote a standby. It stops a two-node setup from promoting on both sides when the link between them breaks. The gap is placement: a witness in the same rack or failure domain as one data node gives the same partition view twice. Place it where a single network or power failure cannot take out the majority, and test what happens when it is down.

Synchronous replication to limit data loss

Synchronous replication makes a commit wait until a standby confirms it, so a promoted standby holds every acknowledged transaction. This limits the data lost when an old primary is discarded after a split. The gap is availability and scope: with synchronous commit, a failed standby can stall writes, and the protection covers only the standbys named in the setting. Review synchronous_standby_names and synchronous_commit against your recovery point target, and decide what the cluster does when no synchronous standby is available.

Replication docs

Client routing through HAProxy or a VIP

A proxy or virtual IP sends application connections only to the node that currently holds the leader role, so clients do not write to a demoted server. HAProxy checks a health endpoint, and a VIP moves with the leader. The gap is the connection that outlives the decision: an established session, a pooler holding server connections, or a cached DNS entry can keep reaching the old primary for a while. Verify how fast clients reconnect after a failover and whether pooled connections are closed during the switch.

Configuration options and when each fits

This table compares the settings that decide whether a cluster can promote a second primary: DCS quorum and TTLs, Patroni watchdog mode, repmgr fencing, witness placement and synchronous standby rules. Read each row as a trade-off between failing over quickly and promoting only when the old primary is certainly stopped. Confirm default values and exact parameter names against the version you run before setting any number.

SettingFaster failover favorsStricter fencing favorsWhen to choose it
DCS quorum size and leader lock TTLShorter TTL so a dead leader key expires soonerLonger TTL so brief network stalls do not trigger a leader changeChoose a short TTL only when the DCS cluster is on low-latency links and the watchdog is armed
DCS quorum membership (three or five nodes)Fewer nodes, simpler quorum loss recoveryOdd-sized quorum spread across failure domains, so one site loss keeps the leader key writableUse three nodes in separate failure domains for most clusters; confirm your site layout first
Patroni watchdog modeWatchdog off or set to fire late, so failover is not cut shortWatchdog required, so the host reboots if Patroni stops refreshing itRequire a hardware or kernel watchdog for any cluster where two primaries would cause data loss
Watchdog timeout versus loop and TTL timingTimeout close to the TTL, so the host resets only when it mustTimeout set below the TTL, so the old primary resets before a new leader is electedSet the watchdog timeout so the old leader stops before the leader key can expire; test the ordering
repmgr fence and promotion scriptsPromotion proceeds once the witness agrees the primary is downA fencing script that cuts power or storage before promotionUse fencing when a hung primary can still accept writes; a script that only logs is not fencing
repmgr witness server placementWitness in the same site as the primary, faster decisionsWitness in a third site, so an isolated site cannot promote itselfPlace the witness outside the primary and standby sites when sites can be partitioned from each other
Synchronous standby count and namesAsynchronous or fewer required standbys, so commits continue during a standby outageQuorum commit across several standbys, so acknowledged writes exist on more than one hostRequire synchronous standbys when lost commits are unacceptable, and accept that writes stop if none respond
Fencing of the old primary after promotionNo fencing, so the old node rejoins without manual workOld primary held read-only or powered off until its state is verifiedUse stricter fencing when storage is shared or a stale primary could reach clients through a VIP or DNS entry

Setting up split-brain protection in order

This sequence builds the quorum, leader lock, watchdog and fencing layers in dependency order so that only one node can ever accept writes, and each layer is confirmed before the next one depends on it. The final step documents the decision path that operators follow when a failure occurs.

  1. Place the quorum members in separate failure domains

    Before any software is configured, the team (usually the platform or database engineers, with the network team) decides where the distributed configuration store (DCS) members or the witness server will run. Each member should sit on separate hardware, power and network paths, so that losing one rack or one switch cannot remove a majority. Confirm the layout against your own environment, since the number of members and placement depend on your failure model. The step is done when a written map shows every quorum member, its failure domain and the minimum number of members that must survive for the cluster to keep a leader.

  2. Configure the leader key and its TTLs

    The database administrators set up the leader key in the DCS (for Patroni, the key lives under the cluster scope in etcd, Consul or a similar store) and tune its time-to-live and loop settings. The leader must renew the key before it expires, and the TTL must be long enough to ride out brief network jitter yet short enough that a failover completes within your recovery objective. Check the values against the Patroni and DCS documentation for your versions. The check: stop the current leader's Patroni agent, confirm the key expires within the configured TTL, and confirm that exactly one replica acquires the lock.

  3. Enable and verify the watchdog device

    The systems team enables a hardware or software watchdog device on each database host and gives the Patroni service permission to feed it. If the node loses its DCS connection or its Patroni process hangs, the watchdog forces a reboot, which means a node that cannot prove it holds the leader lock cannot keep accepting writes. Confirm that the device exists on the host, that the service user can open it, and that the watchdog setting in the Patroni configuration points to it. The check: list the watchdog device on each node, confirm that Patroni reports the watchdog as active, and verify that the watchdog is armed in the logs before any failover test begins.

  4. Write and test the fencing action

    The engineers write the fencing action that runs before a standby is promoted, for example a script that stops the old primary's service, blocks its storage writes or removes its virtual IP. In repmgr, this is the fence hook called by repmgrd, and in Patroni the equivalent protection comes from the leader lock together with the watchdog. Each action must be idempotent and must report success only when the old primary can no longer accept connections. Test the script in isolation on a non-production cluster first. The check: run the fencing action against a live primary, then confirm from a separate host that connections to the old address fail and that the script exits with a success code only when the fence holds.

  5. Route clients only to the leader

    The network or platform team places a proxy layer, such as HAProxy with a health check or a virtual IP managed by the cluster, in front of the database. The health check must return healthy only for the node that currently holds the leader role, so applications never reach a second primary through a stale address. Connection strings should point at the proxy, not at individual nodes. The check: run a query through the proxy, perform a switchover, and confirm that new connections land on the new leader and that connections to the former leader are refused.

  6. Test partition and failure scenarios

    The team deliberately creates the failures that cause split-brain: isolating the leader from the DCS while leaving client traffic running, killing the Patroni process, freezing the host, and cutting replication. For each scenario, they record which node holds the lock, whether the watchdog fired, whether the fence ran and whether any client wrote to the old primary. Schedule these tests in a staging environment that mirrors production topology, and repeat them after each configuration change. The check: a written results table in which every scenario shows exactly one writable primary at all times and a documented client reconnection outcome.

  7. Document the decision path for operators

    The on-call and database teams write a runbook that shows what an operator checks when the cluster reports two primaries or no primary: which command reveals the lock holder, when to trust the watchdog, when the fencing action is safe to run manually and who approves a forced promotion. The runbook should reference the actual host names, key paths and commands in your environment, and it should be reviewed alongside the test results. The check: a tabletop review in which an operator who did not build the cluster follows the runbook and reaches the correct action for each test scenario.

Tests that prove the second primary cannot appear

Run a split-brain test plan before the cluster takes production traffic, because a configuration that looks correct on paper can still allow two writable primaries under a real fault. Start by isolating the leader from the DCS while it keeps client traffic. Block the leader's access to the etcd, Consul or ZooKeeper endpoints (the DCS in use) with firewall rules, but leave the application path open. The pass condition is that the leader demotes itself or is fenced once its lock lapses, the lock moves to a healthy node, and writes from the application land on exactly one primary. This is the test most likely to expose a leader that keeps accepting writes after it has lost its lock.

Next, exercise the other failure modes one at a time. Pause the primary process with SIGSTOP so it stops responding without exiting, freeze the host at the hypervisor or kernel level, and cut the link between sites while the DCS quorum remains reachable from one side. Then kill the DCS leader itself and confirm the cluster either keeps its current primary or fails over only when the DCS quorum can still agree. For each case, check the watchdog or fencing action that should have fired (a Patroni watchdog reset, or a repmgr fencing script), and confirm with the vendor documentation and your own environment which action applies to your versions. Keep the test steps in a runbook so they are repeatable.

Record every result: the time each node saw the lock change, whether the old primary was writable at any point, what the watchdog or fence did, and how long client connections took to reach the new primary. The pass condition is one writable primary at all times and a fenced or demoted old primary, with the evidence kept with the change record. Repeat the full plan after each PostgreSQL minor or major upgrade, after any DCS or Patroni change, and after any change to network topology or site count. For the wider set of failover and switchover checks, including client reconnection measurements, see the sibling topic on PostgreSQL failover testing and switchover runbooks.

Security and operational considerations

A split-brain guard is only as strong as the systems that hold the leader lock and the accounts that can change it. The cards below cover the credentials, transport security, audit trail and manual override paths that an operator should verify before the cluster goes live and after every change to it.

DCS access and write permissions

The distributed configuration store (etcd, Consul or ZooKeeper, depending on the cluster design) holds the leader key. Only cluster members should be able to write to the leader key path, and no application or human account should have that right by default. Check the access control list on the leader key prefix, confirm each node authenticates with its own identity, and confirm that a read-only monitoring account cannot change leadership state.

Fencing credentials scoped to one action

Fencing scripts often need credentials to power off a host, call a hypervisor or cloud API, or change a storage attachment. Store those credentials in a secrets manager, give them permission for that single fence action only, and rotate them on a schedule. Confirm that the fencing account cannot create instances, read unrelated data or alter the database, and that a fencing failure is logged rather than retried silently.

Least-privilege replication account

The replication role used by standbys needs only the REPLICATION attribute and a pg_hba.conf entry for the replication pseudo-database from known member addresses. It should not be a superuser and should not own application objects. Review the role with the catalog, confirm the pg_hba.conf rules match the member IPs, and remove any leftover replication entries when a node is retired.

PostgreSQL auth methods

TLS between cluster members

Leader election traffic, replication streams and the health checks between Patroni, etcd and PostgreSQL can all carry credentials and data. Encrypt each channel with certificates issued by an internal CA, enforce certificate verification rather than trust-on-first-use, and restrict the client certificate names that each component accepts. Check that a node presenting an expired or foreign certificate is rejected and that the rejection shows up in logs.

Audit trail for promotion events

Every promotion, demotion, lock acquisition and fencing action should leave a record with a timestamp, the node involved and the reason. Forward the Patroni and DCS logs, along with the PostgreSQL server log entries that record promotion, to a store that the database operators cannot edit. Test the trail by forcing a failover in a non-production cluster and confirming that the sequence can be rebuilt from the logs alone.

Manual lock override authority

Operators sometimes clear a stale leader key or force a promotion during an incident, and that action is what most often creates two primaries. Define who may run manual overrides, require a second approver or an incident ticket for forced actions, and restrict the commands to named roles. Confirm that the override path is logged, that the fencing step still runs, and that the runbook states how to verify a single primary before and after the override.

Questions teams ask before split-brain protection goes live

Does PostgreSQL alone prevent split-brain?

No. PostgreSQL provides hot standby, synchronous and asynchronous replication, but it does not include software that detects a primary failure and promotes a standby. Automatic failover, and the fencing that keeps an old primary from accepting writes, must come from external tools such as Patroni, repmgr or pg_auto_failover. Those tools each rely on a different mechanism, so the protection you get depends on the tool you choose and how you configure it. The PostgreSQL failover documentation describes the built-in options and where external tooling begins.

What does split-brain protection cost, and what drives it?

Cost has two parts: the one-time design and build, and the recurring operation of the cluster. The build effort depends on the number of clusters, the number of sites, whether a distributed configuration store such as etcd already exists, how many fencing or witness components you need, and how well your network paths are documented. Recurring costs include retesting after upgrades, monitoring the lock store and watchdog, and staff time for failover drills. Ask any partner for a fixed-scope quote that lists each cluster, each site, each fencing method, the tests included and the retest rounds included. DeployOpen does not publish prices, and a quote follows from the written scope.

How long does a split-brain protection build take?

The duration depends on what already exists and how many decisions remain open. Teams with a working consensus store, documented network segments and an agreed failover tool usually need less time than teams that still have to choose the tool, provision the lock store and settle the fencing design. Other drivers include the number of clusters, access to change windows for test runs, approvals for firewall and power changes, and the time needed to prove the design under failure. Ask for a timeline that separates design, build, test and handover, and confirm which client dependencies sit on the critical path.

What does the client team need to provide?

The work depends on access and decisions from your side. Expect to provide a named technical owner, access to the hosts, hypervisors or cloud accounts where the nodes run, network diagrams that show how the nodes, the lock store and the clients reach each other, and the approved change windows for disruptive tests. Security teams should confirm how service accounts, certificates and watchdog permissions are handled. Your operations team should be ready to take over runbooks and alerts. Agree in writing who approves a test that will cause a controlled failover, because a split-brain test is only useful when someone can stop it.

Can our own team build split-brain protection without a partner?

Yes, if your team has experience operating PostgreSQL replication, a distributed consensus store and the Linux configuration needed for watchdog devices. Many teams do this in-house. The points that most often need outside review are the fencing design, the behavior during network partitions, and the test plan that proves the design works. A partner can review your design or run the test suite while your team keeps ownership. Whichever route you choose, the team that runs the cluster after go-live should be the team that understands the failure modes. Confirm internal skills before deciding.

Which mechanisms do the tools use to stop a second primary?

Patroni uses a leader lock in its distributed configuration store and can use a Linux watchdog device so the old primary reboots if it loses contact with that store. repmgr relies on its repmgrd daemon and fencing scripts you write, and often uses a witness server to help decide which side of a partition should promote. pg_auto_failover uses a monitor node to coordinate state. Each design has limits, for example a lock store that is unreachable from the primary but reachable from the standby. Check how each tool behaves under a partition before choosing, and test the exact configuration you will run.

How often should split-brain tests be repeated?

Repeat the full test suite after any change that touches the cluster's failover path, including PostgreSQL minor and major upgrades, tool upgrades, changes to the lock store, network changes, and changes to watchdog or fencing settings. Run smaller checks, such as confirming the leader lock and watchdog status, on a schedule your operations team sets. Record each result and the configuration it tested. Auditors and internal reviewers will ask for dated evidence, so keep test reports with the change records. Confirm the cadence and the evidence format with your compliance team before go-live.

How DeployOpen scopes split-brain protection work

DeployOpen plans, implements, hardens, tests and documents self-hosted PostgreSQL clusters in infrastructure you control, including your cloud accounts, data centers or air-gapped networks. For split-brain protection, the scope usually covers the fencing design itself: the DCS leader lock and its quorum, the Patroni watchdog device or repmgr fencing hook, the network paths between nodes and the DCS, and the client routing layer that decides where connections go after a failover. Scope and deliverables are agreed in writing before work starts, so you know which decisions DeployOpen makes with you, which ones your network or security team owns, and what evidence you receive at handover.

Deliverables typically include the configuration baseline for each node, the runbook for switchover and fenced failover, the partition and failure test results with measured outcomes, and documentation your operators can follow under pressure. Ask for the test matrix in the written scope: which faults are injected (network partition between the primary and the DCS, loss of the DCS quorum, hung storage, a host that stops responding without shutting down), what counts as a pass, and who retests after changes. Security testing of the failover design is available as a separate engagement, so the team that built the cluster is not the only one checking that a fenced primary cannot accept writes. Most engagements are fixed-scope, and ongoing testing, upgrades and cluster changes can be covered by a retainer once the first build is accepted. DeployOpen does not publish a price list, and a quote follows from the written scope. DeployOpen prepares systems, controls and evidence for your compliance reviews but does not issue audit reports, attestations or certifications.

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.