Failover Automation
Automatic failover patterns. Health checks, failure detection, split-brain prevention, and DNS TTL management during database failover.
Database failover automation can reduce recovery time, but a timeout alone cannot prove that a primary is dead. Set detection thresholds from your recovery objective, election behavior, measured network and storage latency, and tolerance for false promotion. Before routing writes to a promoted replica, make sure the former primary cannot still accept writes; then recover it as a replica and test the full sequence regularly.
Failover Automation
A primary can stop responding while its database process is still running. That is where automatic failover gets dangerous: the replica may see a dead node when the problem is only a network partition or a paused host.
Failover automation can help, but only if the promotion and recovery steps work under the failures the system is meant to handle.
Introduction
Failover automation can shorten the time between a primary failure and restored service. It does not guarantee a quiet incident: the system still has to decide whether the primary is truly unavailable, select a safe replica, prevent the old primary from accepting writes, and redirect clients. The time depends on the database, its coordinator, replication state, and recovery path.
Automation adds its own failure modes: both nodes may accept writes, a lagging replica may be promoted, or a temporary network problem may trigger an unnecessary failover. This guide covers health checks, failure detection, split-brain prevention, and DNS during a primary change.
What Automatic Failover Means
Automatic failover detects a primary failure and promotes a replica without an operator issuing each step. The goal is to reduce downtime and data loss. Detection, election, fencing, and traffic routing still need to work together, and each has different failure modes.
Safe Failover and Recovery Sequence
A failed health check is evidence that a check could not reach the primary; it is not proof that the primary has stopped running. A partitioned or paused host may still accept writes. Do not connect a single failed probe directly to a promotion command.
Use a coordinator and a defined single-writer safeguard for the database you run. The sequence is:
- Confirm the configured failure condition and check that the candidate replica is eligible under your data-loss policy.
- Establish quorum or another authoritative election decision. Fence the former primary, or use a lease/watchdog mechanism that guarantees it stops accepting writes before the new primary does.
- Promote the candidate and then route write traffic to it.
- Keep the former primary isolated. After confirming the new primary is authoritative, rewind or rebuild the former primary and rejoin it as a replica. Never let it return as a writer based only on its local state.
For PostgreSQL, failover orchestration is external to the database. PostgreSQL’s failover documentation describes the need to tell a restarted old primary that it is no longer primary; pg_rewind can synchronize a former primary with the new one when its prerequisites are met. Patroni’s watchdog can add a fence against a node that stops updating its leader lease. Those mechanisms are system-specific and need to be configured and tested for the failure modes you expect. PostgreSQL failover documentation, pg_rewind documentation, and Patroni watchdog documentation describe these behaviors.
Health Checks and Failure Detection
A health probe can report that the primary is unreachable, but it cannot prove the process has stopped. A short window may trigger an unnecessary promotion; a long one adds downtime.
Types of Health Checks
Database-level checks verify the process is accepting connections: pg_isready for PostgreSQL, TCP connection to the database port, SHOW GLOBAL STATUS for MySQL.
Query-level checks run an actual query to confirm the engine can process work. SELECT 1 proves the query engine is functional, not just the network layer.
Replication checks verify the replica is receiving changes from the primary. A replica that cannot keep up is a poor failover candidate—it would become primary with missing data.
# PostgreSQL probe for monitoring; a failed probe alone must not promote a replica.
pg_isready -h "$PRIMARY_HOST" -p "$PRIMARY_PORT" -U "$CHECK_USER"
Failure Detection Timeout Tradeoffs
There is no safe timeout that fits every cluster. Work backward from the service’s recovery time objective (RTO): subtract measured election, fencing, promotion, and client-recovery time, then leave a margin for tail latency. The remainder is the detection budget. If those steps already consume the RTO, a shorter health-check timeout will not meet the objective safely.
Set the detection window using measurements from the system’s failure domains. Include network round-trip time and variance between coordinator members, storage or fsync latency on the coordinator, election behavior, and the longest host pauses you need to tolerate. Then decide how much false-promotion risk the service can accept. etcd’s tuning guidance makes the same point: slow disks can delay heartbeats, and network latency affects heartbeat and election settings. Measure under load and test partitions and pauses before changing a production threshold. etcd tuning documentation.
Use that remainder to set the probe interval and failure window. Test both sides of the threshold: failures that should recover, and pauses or partitions that must not create a second writer.
Split-Brain Prevention
Split-brain occurs when two nodes both believe they are the primary. Both accept writes, data diverges, and reconciliation becomes painful or impossible.
A network partition is one common source of split-brain. If the primary loses connectivity but keeps running, it may continue accepting writes while a replica promotes. When the network recovers, both databases can contain writes the other never received.
Quorum-Based Prevention
Quorum can prevent an isolated node from promoting itself: a node becomes primary only when a majority agrees. A three-node cluster needs two votes. If one node loses contact with the others, it has only one vote; the remaining two can elect a primary.
Raft consensus protocols work this way. etcd, Consul, and some database clustering solutions implement similar logic.
Here’s the failure scenario that quorum is designed to prevent: the primary loses network connectivity to Node C but keeps running. Node C cannot reach the primary, so it tries to promote itself. Without quorum, Node C has 1 vote and should not promote. The two remaining nodes have 2 votes and can elect a new primary between themselves. The old primary, still believing it is primary, continues running — but it cannot accept writes because it cannot form a quorum. Fencing then isolates the old primary cleanly.
The 2-node case is where it gets messy. If one primary and one replica both lose sight of each other, each sees itself as having the majority — 1 out of 2 is not a majority. Neither should promote. That means a 2-node cluster cannot do safe automatic failover; you need a third node, a witness, or a tiebreaker. Patroni handles this by requiring the consensus store (etcd) to agree before promoting. If etcd itself is partitioned, Patroni sits tight rather than risking split-brain.
Configuration matters as much as the concept. etcd documents a 100 ms default heartbeat interval and a 1000 ms default election timeout, but those values are not universal recommendations. Its guidance says to account for member round-trip time and latency variance; slow disks can also delay heartbeats and trigger elections. Tune the coordinator using its current-version documentation and production-like measurements, not a copied timeout. etcd tuning documentation.
Fencing
Quorum prevents a replica from promoting without majority agreement, but it does not stop the old primary from continuing to accept writes. If the primary lost network connectivity rather than crashing, it keeps running and may have a local write queue that never reached the replica. When the network recovers, you have two nodes with divergent data. Fencing closes this gap by physically isolating the old primary before the new primary starts accepting writes.
STONITH (Shoot The Other Node In The Head) achieves this by power-cycling or isolating the failed node through an out-of-band channel. The method depends on your environment:
| Method | How it works | Best for |
|---|---|---|
| IPMI / iLO / iDRAC | Fencing agent sends a power reset command over the BMC network | Bare metal, on-prem |
| Cloud provider API | AWS StopInstances, GCP resetInstance via API call |
Cloud VMs |
| Switch port disable | Network switch disables the port connected to the old primary | Environments with managed switches |
| Upsi or PDU control | Power distribution unit cuts power to the specific node | Data centers with intelligent PDUs |
Patroni can use a watchdog as an extra safeguard against split-brain. It tries to activate the watchdog before promoting a node; if the watchdog is required but cannot be activated, that node refuses leadership. A watchdog can reset a host that stops sending keepalives, including when Patroni is stalled or the VM is paused. It does not replace testing the device, lease settings, and timing together. Patroni watchdog documentation.
Resource fencing revokes access to a resource without power-cycling the node. Depending on the architecture, this might revoke storage access, disable a network path, or stop the old instance through a management API. These controls are external to PostgreSQL; PostgreSQL’s documentation notes that it does not provide the system software for detecting a primary failure and notifying a standby. Choose a fence that prevents writes, and verify its success before the new primary accepts them. PostgreSQL failover documentation.
Power fencing makes the node unavailable, but the out-of-band control path must survive the failure that triggered fencing. Resource fencing can be faster, but a bad ACL or an incomplete rule may leave the old primary able to write. Pick the method that matches your failure domains, and have the promotion controller verify the fence rather than assuming the request succeeded.
Fencing adds real operational overhead. You need to configure and test the mechanism, monitor its health, and make sure your operators understand what happens during a failover. If you are running a smaller team or a development environment where 24/7 availability is not a hard requirement, semi-automatic failover (an operator confirms the old primary is isolated before triggering promotion) is often more practical than building full fencing support.
Recovery Exercise
Run this exercise in an isolated environment before enabling automatic promotion, repeat it on a schedule, and repeat it after changing the coordinator, storage, network, or failover configuration. Record detection time, fence completion, promotion time, client recovery, and any data loss against your RTO and RPO.
- Network partition: Block the primary from reaching the replica or coordinator while leaving the database process running. Confirm that the replica does not accept writes until quorum and the old-primary fence are established. Heal the partition and verify the old primary cannot rejoin as writer.
- Paused or slow host: Pause or heavily delay the primary or its coordinator path. Confirm that a timeout does not produce two writable primaries, and that the watchdog or fence behaves as designed when the host resumes.
- Genuine host loss: Hard-power-off the primary through the hypervisor or cloud control plane, or terminate its VM at the infrastructure layer. Do not stop PostgreSQL cleanly. Promote the eligible replica, reconnect an application through the normal endpoint, and verify writes and alerts. Restore the old host only after isolation is confirmed; rebuild or rewind it as a replica and check that replication is healthy.
Automatic promotion can reduce manual steps, but it does not remove on-call responsibility. Keep paging for an uncertain fence, an ineligible replica, failed client recovery, or a former primary that cannot safely rejoin.
Prometheus, HAProxy, and Patroni Patterns
Common tooling patterns for managing failover:
Prometheus Alertmanager + Blackbox Exporter
Monitor the primary with Prometheus. This rule sends an alert; it should not call a promotion command directly. A failover controller must apply the quorum, candidate, and fencing checks described above.
groups:
- name: database_failover
rules:
- alert: DatabasePrimaryDown
expr: probe_success{job="db-primary-check"} == 0
labels:
severity: critical
annotations:
summary: "Database primary is down"
The example omits for because its value should come from the measured detection policy for the cluster. Configure alert duration separately from the controller’s election and fencing checks.
HAProxy for Connection Routing
HAProxy can health-check database backends and route connections through a stable endpoint. It does not promote a database replica or prove that the old primary is fenced; connect its write routing to the database coordinator’s confirmed leader state.
backend db_write
option tcp-check
tcp-check connect
tcp-check send PING\r\n
tcp-check expect string PONG
server primary db-primary:5432 check inter 5s fall 3 rise 2
server replica1 db-replica1:5432 check inter 5s fall 3 rise 2 backup
This backend sketch is not a complete promotion policy. Do not let a routing health check send writes to a read-only replica; the database coordinator must confirm promotion first.
Patroni for PostgreSQL
Patroni automates PostgreSQL failover using distributed consensus (etcd, ZooKeeper, or Consul) for leader election. It manages leader election, replication, automated failover with safety checks, and post-failover recovery.
Patroni runs on each PostgreSQL node and uses a distributed configuration store (DCS) to manage the leader lock. If the lock cannot be renewed, a replica can seek leadership according to the cluster’s election and safety rules. The DCS helps coordinate that decision; it does not by itself prove that the old database process has stopped accepting writes. Configure and test the watchdog or other fence as part of the same recovery path.
Operators interact with Patroni through patronictl. Common commands:
# Check cluster health
patronictl list
# Trigger manual failover (for maintenance)
patronictl switchover
# View failover history
patronictl history
Patroni’s watchdog and DCS lease settings work together; check the watchdog documentation when configuring them. A former primary still needs the recovery sequence above before it rejoins as a replica. For PostgreSQL, that may mean pg_rewind when its prerequisites are met, or a fresh base backup.
You also need to operate the DCS and keep it available to the PostgreSQL nodes. Across many clusters, that coordination layer becomes a platform concern. It can help make leader election consistent, but it does not remove the need to test fencing and recovery.
Vitess and CockroachDB
Vitess and CockroachDB have automatic failover built in as core features. If you want failover that works without custom configuration, managed distributed databases handle this internally.
Vitess started as YouTube’s MySQL sharding middleware, and it handles failover at the vtgate layer. When a MySQL tablet fails, Vitess’s topology service detects it and promotes a replica. The vtgate layer starts routing queries to the new primary automatically — your application just sees a connection reset and retries. One thing worth knowing: Vitess also reshards transparently during failover, so a node failure during a migration does not block the resharding process. The downside is that Vitess is a full platform. You need a ZooKeeper or etcd cluster for topology state, plus vtgate, vtconsul, and vttablet running on every node. It is not a drop-in database — it is a platform you commit to running.
CockroachDB works differently. It is distributed at the storage layer using Raft consensus, so failover is not a separate process — it is how replication works by default. When a node fails, Raft rebalances replicas to the remaining nodes without any external tooling. A 3-node cluster can lose 1 node with no downtime and only minor latency impact. There is no promotion step because CockroachDB treats all replicas as equally valid — reads come from any replica, writes need a majority. The tradeoff is cost: CockroachDB’s resource requirements are higher than vanilla PostgreSQL, and you pay for that operational simplicity.
Mean Time to Recovery (MTTR)
MTTR measures average recovery time. For database failover, it includes:
- Time to detect failure
- Time to decide on failover
- Time to execute promotion
- Time for replicas to catch up to new primary
Treat MTTR as a measured result, not a default target. Track detection, election, fencing, promotion, routing, and client reconnection separately, then compare the end-to-end recovery time with your RTO. A health-check interval multiplied by the number of missed checks is only a rough estimate; coordinator behavior, network variance, storage latency, and host pauses can change the result. Test those conditions rather than extrapolating from a clean lab run.
Promotion time and replica readiness depend on the database and its current workload. For PostgreSQL, pg_promote() waits for promotion to complete when called with its default wait option, but the time still depends on recovery state and WAL. Async replication can leave the candidate behind the primary, so compare its position with your RPO before promotion. PostgreSQL recovery functions describe pg_promote(); the standby server documentation describes WAL replay.
Data safety depends on the candidate’s receive and replay position. With asynchronous replication, writes acknowledged by the old primary may not have reached the standby before failure; compare the candidate with the service’s RPO before promoting it. PostgreSQL’s synchronous replication can wait for configured standby acknowledgments, but the guarantee depends on the synchronous_commit policy. After promotion, the former primary may also need rewind or a rebuild before it can catch up as a replica. See the PostgreSQL replication documentation.
Real-World Case Study: Patroni at Spotify
Spotify runs one of the largest PostgreSQL clusters managed by Patroni in production. Patroni handles automatic failover for their hundreds of PostgreSQL clusters using etcd as the consensus backend.
The challenge at Spotify’s scale was not the failover itself — Patroni’s failover is reliable — but managing the post-failover state across their service mesh. When a PostgreSQL primary fails and a replica promotes, hundreds of application servers that had connections to the old primary need to reconnect to the new primary. Without connection pooling (Spotify uses PgBouncer in front of PostgreSQL), this would cause a connection storm as all applications simultaneously try to reconnect.
Spotify’s solution was aggressive connection pooling at every tier. PgBouncer sits in front of every PostgreSQL cluster. When failover happens, PgBouncer detects connection failures and reconnects to the new primary with exponential backoff. The connection pooling layer absorbs the reconnection burst rather than letting it hit the database directly.
The operational lesson: failover automation handles the database layer, but your connection pooling and application reconnection logic must be equally resilient. Patroni’s failover works reliably, but if your application crashes on connection errors instead of retrying gracefully, you still get an outage.
Real-World Case Study: AWS RDS Failover
For a standard Amazon RDS Multi-AZ DB instance deployment, AWS says failover typically takes 60–120 seconds, with longer times possible for large transactions or lengthy recovery. This is specific to that deployment type; Multi-AZ DB clusters have a different failover path and timing. AWS RDS Multi-AZ DB instance failover documentation.
During failover, clients can receive connection errors. If your connection pool cannot recover and reconnect to the new primary, requests can continue to fail after the database has recovered.
The lesson: managed failover does not eliminate application-level connection resilience. RDS handles the database failover; your application must handle the connection interruption. Use the RDS endpoint (which automatically resolves to the new primary after failover) rather than hardcoding the primary’s IP. Configure your database client to retry on connection failure with exponential backoff. Test failover explicitly — RDS allows you to trigger a manual failover to verify your application handles it correctly.
Quick Recap Checklist
- Health checks use multiple consecutive failures to avoid false positives
- Quorum and a verified fence or lease/watchdog ensure only one primary can accept writes
- Fencing (STONITH) isolates old primary before new primary promotes
- DNS TTL set to 60 seconds or lower before failover
- Connection pooling absorbs reconnection bursts during failover
- Measure each recovery phase against the service’s RTO and RPO
- Exercise partition, paused-host, and host-loss recovery on a schedule and after relevant changes
- Rejoin the former primary only after isolating it and rebuilding or rewinding it as a replica
- 2-node clusters cannot do safe automatic failover — use manual or add witness
- Check the candidate’s replication position against the RPO; understand what the configured synchronous-commit policy guarantees
- Alert at lag exceeding your RPO threshold
Related Posts
- Database Replication — Replication fundamentals these systems build on
- Database Scaling — Scaling strategies including replication
- Consistent Hashing — Related distribution mechanisms
DNS TTL Management During Failover
When the primary changes, applications must connect to the new primary. DNS-based discovery handles this: point your database hostname to the current primary’s IP, update DNS on failover.
The problem: DNS caching. If your TTL is 1 hour, clients might keep connecting to the failed IP for an hour after failover.
Low TTL Before Failover
Set a low TTL (60 seconds or less) on your database DNS records before you need failover. This lets you update quickly when the time comes.
gcloud dns record-sets transaction start --zone=db-zone
gcloud dns record-sets transaction remove db-primary.example.com. A 300 \
--zone=db-zone --ttl=60
gcloud dns record-sets transaction add db-replica1.example.com. A 300 \
--zone=db-zone --ttl=60
gcloud dns record-sets transaction execute --zone=db-zone
Application-Level DNS Caching
Applications cache DNS lookups at the OS or library level regardless of your TTL. Ensure your database client re-resolves hostnames on connection failure or periodically.
The issue goes deeper than your TTL settings. Most operating systems cache DNS as a performance feature — Linux with systemd-resolved holds onto results for the full TTL, but also keeps a negative cache for failed lookups that can persist for minutes. Language runtimes layer their own caching on top of this. The JVM is the worst offender: it caches DNS lookups indefinitely by default, until the process restarts. Go’s standard library also caches forever unless you use a dialer with a deadline set. So even with a 60-second TTL, a JVM application that resolved db-primary.example.com at startup will keep hammering the old IP until someone restarts the process.
PgBouncer and ProxySQL solve this by sitting between your application and the database. Your application connects to the pooler endpoint, the pooler tracks which backend is primary, and when failover happens, the pooler reconnects to the new primary. Your application just sees a connection reset and retries — no DNS involved. This is the cleanest solution if you can add a pooling layer.
If a pooler is not an option, most database clients re-resolve the hostname when retrying a failed connection. PostgreSQL’s Go driver, the Java driver, and Node.js pg all do this. For JVM apps, set networkaddress.cache.ttl=0 in your security policy. In Kubernetes, use a headless service or an ingress controller that tracks the primary via labels — Kubernetes updates its endpoints automatically when a pod fails, which sidesteps DNS caching problems entirely.
When to Use / When Not to Use Automatic Failover
Use automatic failover when:
- Your RTO requires recovery faster than a tested operator-led process can provide
- You run multi-AZ deployments where node failure is a realistic scenario
- You have 3+ database nodes so quorum-based promotion is safe
- Your application handles brief write unavailability gracefully
Do not use automatic failover when:
- You have only 2 nodes — quorum-based failover cannot work safely with 2
- Your database runs on shared storage (SAN) where primary and replica share failure domain
- Your team can respond faster manually than the automation can detect and act
- You lack monitoring that distinguishes node failure from slow node
Automatic vs Semi-Automatic vs Manual Failover Trade-offs
| Dimension | Automatic Failover | Semi-Automatic (Operator-Triggered) | Manual Failover |
|---|---|---|---|
| Recovery time | Measure against RTO; varies by system | Includes operator decision time | Depends on diagnosis and response |
| False positive risk | Higher — can trigger on transient issues | Lower — human verifies first | None |
| Split-brain risk | Depends on election and fencing design | Lower if the operator verifies the fence | Depends on the runbook |
| Operational complexity | High | Medium | Low |
| Best suited for | 24/7 services with SLA | Business hours ops, critical data | Non-critical dev/staging |
| Requires | Quorum, fencing, watchdog | Alerting + runbook | On-call engineer |
| Data loss risk | Low (with sync rep) | Very low | Depends on async lag |
What Automation Cannot Solve
Automation handles node failure, not root cause failure. If a bad deployment corrupts data on the primary, promoting a replica spreads the corruption. You still need backups, point-in-time recovery, and tests that verify your recovery procedures actually work.
Automation also does not eliminate runbooks. When something unexpected happens, operators need documented procedures, not just alerts.
Production Failure Scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Spurious failover from network blip | Primary demoted unnecessarily, brief write outage | Set the detection window from RTO and measured latency; verify the fence before promotion |
| Split-brain from network partition | Two primaries accept writes, data diverges | Use quorum-based promotion, implement fencing (STONITH) |
| Fencing failure leaves old primary writing | Data corruption, split-brain continues | Test fencing regularly, monitor fencing state |
| Promotion of lagging replica | Data loss — missing writes not yet replicated | Check replication position before promotion, use semi-sync replication |
| DNS TTL too high | Clients keep connecting to failed primary for minutes | Set TTL to 60s or lower before failover, use connection pooling |
| Cascade failure during failover | Multiple nodes fail during transition | Keep cluster stable during failover, avoid concurrent config changes |
| Automation runs during planned maintenance | Primary demoted while operator working | Pause automation during maintenance windows, use manual mode |
Interview Questions
With 2 nodes, quorum-based failover cannot work safely. If the primary fails and the replica promotes, there is no third vote to break ties — any network partition that splits the nodes at the same time as the primary failure creates a split-brain scenario where both nodes believe they are primary. The only safe configuration with 2 nodes is manual failover or shared-nothing failover where one node can definitively prove it is the only one that can serve writes (via shared storage or fencing). The recommendation is to add a third node or use a witness/arbitrator node to enable quorum-based failover.
The old primary may still be running and accepting writes, even though the replica cannot reach it. Keep it fenced after promotion and treat the new primary as authoritative. When the old host returns, do not simply replay its local writes or let it rejoin as a writer; the two timelines may have diverged. Rewind it to follow the new primary when the database supports that and the prerequisites are met, or rebuild it from a fresh backup. PostgreSQL documents pg_rewind for this recovery path.
Start from the service RTO and measure the time spent in detection, election, fencing, promotion, and client recovery. Tune Patroni's loop_wait, ttl, and retry_timeout with the documented timing relationships and the latency of the configured DCS. Shortening timers can reduce detection time, but network jitter, slow storage, or a paused host can also cause lease loss and a false promotion. Test those conditions before changing production values. Synchronous replication can reduce data loss for acknowledged writes, but it does not replace fencing or coordinator checks.
Quorum allows only a majority partition to elect a leader. With three voting nodes, two votes form a majority, so an isolated node cannot elect itself. A two-node cluster cannot form a majority when the nodes lose contact; a witness can provide a third vote if the failover system supports it. Quorum coordinates the election, but it does not by itself stop a former primary from accepting writes. The database also needs a verified fence or lease/watchdog behavior that enforces a single writer.
STONITH ("Shoot The Other Node In The Head") powers off or isolates the former primary so it cannot accept writes after a new one is promoted. The coordinator should confirm that the fence succeeded before routing writes to the new primary. Power control is one option; storage or network fencing and a correctly configured lease/watchdog can serve the same single-writer purpose. Whatever method you choose, test that its control path still works during the failure being simulated.
Clients cached the old IP with a 1-hour TTL. After failover, the DNS record points to the new primary's IP, but clients ignore the update for up to an hour. During this window, writes to the failed primary's IP fail with connection errors. If the old primary is still running (not properly shut down), it may accept writes that are never replicated to the new primary — data divergence. Prevention: set database DNS TTL to 60 seconds or less before deploying failover automation. Use a database-specific DNS endpoint (like RDS endpoint or a dedicated CNAME) that resolves to the current primary rather than hardcoding IPs. Some setups use a virtual IP (VIP) that floats to the new primary — the application connects to the VIP and the network handles the switch without DNS changes.
loop_wait, ttl, and retry_timeout interact with Patroni's leader lease and the configured DCS. There is no fixed detection time that applies to every cluster. Use the documentation for the Patroni and DCS versions you run, then measure network round-trip variation, coordinator storage latency, host pauses, and the full recovery path. The value is acceptable only if it meets the RTO without causing unsafe promotions in those tests. See Patroni's dynamic configuration guide, its watchdog documentation, and the etcd tuning guide.
A timeout may have expired while the primary was partitioned, paused, or overloaded rather than stopped. If the coordinator allowed a replica to promote without fencing or an equivalent lease/watchdog guarantee, the old primary could still accept writes. Reproduce the failure in an isolated exercise, verify which check or lease expired, and confirm the fence before routing writes. Set detection windows from measured failure-domain latency and the RTO; do not copy a fixed count of checks from another cluster. Also verify the candidate's replication position against the data-loss policy.
A standard Multi-AZ DB instance deployment switches to its standby after an infrastructure problem. AWS says these failovers typically take 60–120 seconds, though database activity and recovery can extend that time. Existing connections can fail, so applications should reconnect through the RDS endpoint and handle interrupted transactions safely. Test the failover with your application and connection pool; the endpoint does not make the interruption disappear. This timing applies to the DB instance deployment, not every RDS Multi-AZ configuration. See AWS's failover documentation.
In raw mode (native PostgreSQL), pgpool-II does not handle replication — it just routes queries to a single PostgreSQL backend. Failover in raw mode means detecting backend failure and switching to a standby — pgpool can do this but you must configure watchdog for HA. In replication mode, pgpool maintains a real replication connection to multiple PostgreSQL servers and replicates writes across them. Failover in replication mode is more complex — pgpool can detect failed nodes but must also manage the replication state. For most automatic failover setups with PostgreSQL, Patroni + PgBouncer is preferred over pgpool-II because Patroni handles failover coordination with etcd/consul while pgpool focuses on connection pooling. pgpool-II works well for read load balancing but Patroni is the standard for HA.
A witness node (or arbitrator) participates in quorum but does not store data. With 2 data nodes + 1 witness: if the primary fails, the replica + witness have 2 votes (majority of 3), allowing promotion. If the witness fails, the 2 data nodes can still communicate and continue operating — the primary does not promote spuriously. This gives you safe automatic failover with 2 data nodes without requiring a 3rd full data node. The tradeoff: the witness is a single point of failure for the election itself (if both the witness and one data node fail simultaneously, you lose quorum). Also verify that your failover tool (Patroni, etc.) supports witness/arbitrator nodes and that the witness's network is reliable and in the same failure domain as the data nodes.
Automatic failover can shorten recovery when the failure matches the tested policy, but a false detection can disrupt service or create split-brain if quorum and fencing are incomplete. Semi-automatic failover adds an operator check, which can help when false promotion would be costly and a responder is available. Manual failover leaves more decisions to the operator and may take longer, depending on diagnosis and response time. Choose based on the service's RTO/RPO, failure modes, and whether the team can run the recovery procedure reliably. In every mode, keep an alert path for uncertain fencing, unsafe replica lag, or failed recovery.
When the primary fails, all application instances that had connections to it receive connection errors nearly simultaneously. Each instance's connection pool or ORM sees the failure and independently starts retrying with exponential backoff — but without coordination, all instances retry at the same times (they failed at the same time). This creates a connection storm that can overwhelm the new primary or the connection pooler. Prevention: use PgBouncer or ProxySQL in front of the database — the pooler maintains its own connection pool to the database and handles reconnection internally, absorbing the burst rather than letting it hit the database directly. Configure pooler reconnection with jitter and exponential backoff. At the application level, implement circuit breakers that temporarily stop sending requests to the database during failover, allowing the pooler time to stabilize.
Patroni requires a distributed consensus store (etcd, Consul, ZooKeeper). For production: use 3 or 5 etcd nodes for HA — a 3-node etcd cluster tolerates 1 failure, 5-node tolerates 2. Place etcd nodes on separate hardware and network segments from the PostgreSQL primaries to avoid correlated failures. Etcd performance matters: use SSDs for etcd data directory, network locality between etcd nodes and Patroni nodes, and monitor etcd write latency (should be < 10ms). If etcd becomes slow, Patroni loops hang and failover detection slows down. For read-heavy workloads, etcd can handle thousands of reads per second, but ensure your etcd cluster is not overutilized — dedicated etcd clusters for critical Patroni deployments are recommended over sharing with other workloads.
Estimate recovery by measuring each phase: detection, election, fence, promotion, routing, and client reconnection. The health-check interval multiplied by missed checks is only a rough estimate; it omits jitter, coordinator storage latency, host pauses, and fencing time. Measure end-to-end recovery under representative failure exercises and compare it with the service RTO. Separately compare the candidate's replication position with the RPO, since asynchronous replication may leave committed writes unavailable on the promoted replica.
First confirm the new primary is accepting writes and the former primary is fenced. Check that client traffic reaches only the new primary. Keep the former node isolated while you inspect its state; if its timeline diverged, use the database's supported rewind procedure or rebuild it from a base backup before adding it as a replica. Then verify replication lag and confirm the cluster has its expected redundancy. Document any step that needed operator intervention and update the exercise or runbook.
Start with the coordinator and failover logs to see which check, lease, or election decision triggered promotion. Compare that timeline with network, CPU, and storage metrics on the former primary; a paused or overloaded host can look like a dead one to a remote probe. Then verify whether fencing completed before the new primary accepted writes. Use those results to tune the detection policy against the RTO and false-promotion risk, and confirm the candidate's replication position before promotion.
HAProxy can stop routing to an unhealthy backend, but it does not promote a PostgreSQL replica. A backup server entry changes routing preference; it does not make a read-only standby writable. Let Patroni or another coordinator promote the replica and confirm it is the leader, then update HAProxy's write route from that confirmed state. A TCP probe such as pg_isready can report whether a server accepts connections, but it is not a leader-election or fencing check.
Hardware failures and software bugs require different recovery approaches. Hardware failure (power supply, disk, memory) typically leaves the database in a clean state — the last committed transaction is well-defined. Software bugs (corrupt indexes, half-applied transactions, crashed writer process) can leave the database in an inconsistent state where promotion to primary is dangerous because the replica may carry forward corrupted data. Design for both: implement checksum verification on replication data to detect corruption before promotion. Use post-promotion verification that runs consistency checks (PostgreSQL's pg_checksums, MySQL's CHECK TABLE) before accepting writes on the new primary. For software bugs causing inconsistency, prefer a full data comparison between candidate replica and primary before promotion rather than blindly promoting the first replica that responds. Consider separating failure classes — hardware failure triggers immediate promotion, software inconsistency triggers alert-and-review before automatic promotion. Maintain backups that are independent of the replication chain so you can restore to a known-good state regardless of which replica you promote.
Long-running transactions that started on the primary before failover may fail when the replica promotes — the transaction's session is interrupted, and if it attempts to commit, the new primary may not have the transaction in its state. The new primary also has a different timeline: transactions that were in-flight on the old primary but not yet committed may be lost. Strategies: keep transaction durations short — long-running transactions are more likely to span a failover event. Use application-level transaction retry logic that catches connection errors and re-executes failed transactions (idempotent operations). Avoid multi-statement transactions that hold locks across the failover window. For critical transactions, consider using synchronous replication so the replica is current at promotion time. Monitor in-flight transaction count as part of your failover metrics — a sudden spike in long-running transactions before failover increases the chance of transaction failures during promotion.
Further Reading
Official Documentation:
- Patroni Documentation — PostgreSQL HA template using distributed consensus
- Consul Documentation — Service mesh and distributed coordination
- etcd Documentation — Distributed key-value store for shared configuration and service discovery
- pg_bouncer Documentation — Connection pooler for PostgreSQL
Tools and Patterns:
- Patroni: Automates PostgreSQL failover using etcd/ZooKeeper/Consul for leader election
- HAProxy: Connection routing and health checking for database clusters
- Prometheus + Alertmanager: Health check monitoring and automated alert-based failover triggering
- Vitess: MySQL sharding middleware with built-in failover
- CockroachDB: Distributed SQL with automatic failover as a core feature
Case Studies:
- Spotify Engineering Blog — PostgreSQL at scale with Patroni (see archive for failover patterns)
- AWS RDS Patroni Automation — Reference architecture for AWS-managed PostgreSQL failover
Monitoring Queries:
-- PostgreSQL: Check Patroni cluster status
SELECT member_name, role, state, sync_state
FROM pg_stat_get_wal_senders();
-- Check for fencing state
SELECT pg_is_in_recovery();
Conclusion
Automatic failover can reduce recovery work, but it does not eliminate on-call responsibility. The system still needs a measured detection policy, a verified single-writer safeguard, and tested procedures for client recovery and restoring redundancy.
Repeat the exercise after changes to the coordinator, storage, or network, and include it in scheduled operations reviews. If any test ends with two writable primaries or the former primary returning as writer, the failover path is not ready.
Category
Related Posts
Database Backup Strategies: Full, Incremental, and PITR
Learn database backup strategies: full, incremental, and differential backups. Point-in-time recovery, WAL archiving, and RTO/RPO planning.
Database Capacity Planning: A Practical Guide
Plan database capacity from measured growth, retention, workload, and provisioning time. Includes a storage forecast and PostgreSQL-specific memory guidance.
Connection Pooling: HikariCP, pgBouncer, and ProxySQL
Learn connection pool sizing, HikariCP, pgBouncer, and ProxySQL, timeout settings, idle management, and when pooling helps or hurts performance.