Designing Automated Failover for Distributed Databases
System DesignModel answerLast updated
Design a resilient database layer that automatically handles node failures while preventing data loss and ensuring only one primary accepts writes.
Context
You're building an automated failover system for a PostgreSQL cluster deployed across two availability zones. The cluster has one primary node that handles writes and multiple read replicas. Your system must keep the database available when the primary fails.
Your Task
Design a solution that automatically promotes a replica to primary when the original primary becomes unavailable. Your design should address:
-
Failure Detection: How does the system distinguish between an actual node failure and a temporary network issue?
-
Promotion Process: What steps occur when promoting a replica? How do you ensure all replicas remain consistent after promotion?
-
Write Safety: How do you guarantee that the old primary stops accepting writes before the new one starts? What prevents two nodes from acting as primary simultaneously?
-
Replication Trade-offs: Should replication be synchronous or asynchronous? How does this choice affect data loss (RPO) and system latency?
-
Client Routing: How do applications discover which node is currently primary after a failover completes?
Constraints
- The deployment spans exactly two availability zones
- Target recovery time under 30 seconds
- Workload: approximately 5,000 writes/second and 50,000 reads/second
- Network latency between zones is 1-2 milliseconds
Explain your reasoning for key decisions and mention potential failure modes in your design.
Hints
Hint 1
The core challenge is distributed consensus: who decides which node is primary, not just detecting failures
Hint 2
Two availability zones alone cannot achieve majority quorum - consider what this means for your consensus layer
Hint 3
Preventing split-brain requires multiple defense mechanisms, not just one health check
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Understanding the Core Problem
This is fundamentally a distributed consensus challenge, not merely a monitoring problem. The system must answer "who is the single primary right now?" in a way that all nodes agree on, even during network partitions. Weak solutions rely on a single health checker making promotion decisions; strong solutions use a consensus store as the source of truth.
Architecture Overview
Each database host runs PostgreSQL alongside an agent process responsible for cluster coordination. These agents communicate through a distributed consensus store (etcd or ZooKeeper) that holds cluster state:
Client Applications
↓
Connection Pools / Proxies
↓
PostgreSQL Primary ← Agent → etcd Cluster
PostgreSQL Replica ← Agent ↗
PostgreSQL Replica ← Agent ↗
Critical Insight: With only two availability zones, you cannot achieve consensus quorum. Three etcd nodes split 2-1 across two zones means losing either zone breaks quorum. The solution is adding a lightweight witness node in a third location (another AZ or region) to enable 2-out-of-3 voting even when one full AZ fails.
State Management via Consensus
The etcd cluster maintains these keys:
/primary/lease: Node identifier held with a 15-second TTL, renewed every 5 seconds. This is the authoritative answer to "who is primary?"/members/*: Each node's replication lag, WAL position, timeline, and eligibility tags/config/sync-standbys: Which replicas are currently in the synchronous replication set
Failure Detection Strategy
Avoid ping-based detection. Instead, use lease expiration:
- The primary continuously renews its lease while verifying it can write locally and Postgres responds
- If renewal fails (network partition from etcd, or local Postgres failure), the primary assumes it has been or will be replaced
- Replicas observe lease expiration through the consensus store, not through direct pings to the primary
- The TTL (15 seconds) absorbs transient network hiccups without triggering unnecessary failovers
This transforms the unreliable question "is the primary alive?" into the linearizable question "does it currently hold the lease?"
Replication Configuration and RPO
Synchronous replication with quorum acknowledgment:
Set synchronous_standby_names = 'ANY 1 (replica1, replica2)' in PostgreSQL. This requires one replica to acknowledge each commit before returning success to the client.
Trade-offs:
| Approach | RPO | Write Latency | Availability |
|---|---|---|---|
| Async | 5-10 seconds of WAL loss | ~1ms (local fsync) | Replica failures don't block writes |
| Sync with quorum | Zero for acknowledged txns | +2ms cross-AZ RTT | Writes continue if any one replica is healthy |
| Sync with ALL | Zero | +2ms | Writes stall if any replica is down |
Critical rule: Only promote replicas that were in the synchronous set. This enforcement is what makes RPO=0 actually achievable—otherwise sync replication just adds latency without guarantees.
Promotion Process
When the lease expires:
-
Eligibility check: Each replica determines if it can become primary:
- Must be in the current sync set (or within configured lag threshold for async setups)
- Must have the highest WAL position among reachable nodes
- Must not have a
nofailovertag
-
Leader election: Eligible replicas race to atomically create the lease key with their identity. etcd serializes these requests—exactly one succeeds.
-
Fence the old primary: Before accepting writes, the new primary must ensure the old one has stopped. Use multiple mechanisms:
- Lease-based self-fencing: Old primary demotes itself when it cannot renew
- API termination: Call cloud provider API to stop or isolate the old instance
- Watchdog timer: Kernel-level reboot if the agent process hangs
-
Execute promotion: Run PostgreSQL's
pg_promote(), which starts a new timeline to make divergent histories detectable -
Reconfigure replication: Other replicas see the new lease holder, update their upstream connection to the new primary, and follow the new timeline. PostgreSQL's streaming replication handles timeline switches automatically.
Split-Brain Prevention
Layer multiple safeguards:
- Consensus-based leadership: Only the lease holder may act as primary
- Agent self-demotion: If unable to renew the lease within TTL minus a safety margin, the agent immediately stops accepting writes
- Sync replication as a natural barrier: A partitioned old primary cannot get acknowledgments from replicas now following the new leader, causing commits to block rather than silently succeed
- Watchdog enforcement: Hardware-level reboot if software hangs
Critically, avoid designs where "a monitoring service pings the primary and promotes on timeout"—this monitor itself can be partitioned, creating two primaries.
Client Traffic Routing
Proxy-based approach (recommended):
Deploy HAProxy or PgBouncer instances that health-check each database node's /primary HTTP endpoint (returns 200 only for the lease holder). Proxies route write traffic to whichever node responds positively. Failover is transparent to applications, completing in 1-3 seconds as health checks detect the change.
Alternative options and trade-offs:
- DNS updates: Simple but slow (30-60s TTL propagation) and unreliable due to client caching
- Virtual IP floating: Fast (~2s) but requires Layer 2 networking control, often not available in cloud environments
- Service discovery (Consul/etcd): Clients query directly; requires SDK integration and retry logic
Common Mistakes to Avoid
- Ignoring the quorum problem: Two AZs cannot provide consensus availability
- Ping-based failover: Creates split-brain when the monitor is partitioned
- Sync replication without enforcement: Claiming RPO=0 but promoting replicas outside the sync set
- Single fencing mechanism: Defense in depth is essential for correctness
- Forgetting timeline divergence: After promotion, the old primary's WAL may conflict if it rejoins
Complexity Analysis
- Failover time: 15-20 seconds (TTL expiration + promotion + health check detection)
- Data loss: Zero for committed transactions when using quorum sync replication
- Operational overhead: Adds etcd cluster maintenance and agent deployment
This design provides strong consistency guarantees through consensus while maintaining practical recovery times for production systems.