PostgreSQL High Availability: Patroni, repmgr, and Failover
Learn to build a production-grade PostgreSQL HA cluster using Patroni and repmgr.
20+ years shipping high-throughput database systems. Drawn from code that ran under real load.
- ✓Basic knowledge of PostgreSQL (installation, configuration, replication)
- ✓Familiarity with Linux command line and system administration
- ✓Understanding of distributed systems concepts (consensus, quorum)
- ✓Access to at least three servers or VMs for cluster setup
- Patroni uses distributed consensus (etcd/Consul) for automatic failover and cluster management.
- repmgr is a simpler, standalone tool for replication management and manual failover.
- Key HA components: replication, health checks, quorum, and fencing to prevent split-brain.
- Production best practices: use synchronous replication for zero data loss, test failover regularly, and monitor replication lag.
Think of a PostgreSQL HA cluster like a relay race team. The primary database is the lead runner, and replicas are backup runners. Patroni acts as the coach who watches the lead runner's health and instantly swaps in a backup if the lead falls. repmgr is like a manual substitution system where the coach decides when to swap. Both ensure the race (your application) continues without interruption.
In today's always-on world, database downtime can cost millions. PostgreSQL, while robust, is not immune to hardware failures, network partitions, or software crashes. High Availability (HA) ensures your database remains accessible even when a node fails. This tutorial dives into two popular PostgreSQL HA solutions: Patroni and repmgr. Patroni, built on distributed consensus (etcd, Consul, or Zookeeper), provides automatic failover and self-healing clusters. repmgr offers a simpler, more manual approach with robust replication management. We'll explore their architectures, setup, failover mechanics, and production pitfalls. By the end, you'll be able to design and operate a PostgreSQL cluster that survives node failures with minimal downtime. We'll also dissect a real-world outage caused by a misconfigured fencing mechanism, teaching you what not to do. Whether you're a DBA or a developer responsible for database reliability, this guide provides actionable insights for building resilient PostgreSQL deployments.
1. Understanding PostgreSQL High Availability Concepts
High Availability (HA) for PostgreSQL involves ensuring the database remains accessible despite node failures. Key concepts include: replication (streaming or logical), failover (automatic or manual), quorum (majority of nodes agree on primary), and fencing (isolating failed nodes to prevent split-brain). Patroni uses a distributed configuration store (etcd, Consul, Zookeeper) to maintain cluster state and elect a leader. repmgr relies on a dedicated monitoring database and manual or cron-driven failover. Both support synchronous and asynchronous replication. Synchronous replication guarantees zero data loss but impacts write performance. Asynchronous replication may lose some transactions during a crash but offers better performance. Understanding these trade-offs is crucial for designing an HA solution that meets your RPO (Recovery Point Objective) and RTO (Recovery Time Objective).
2. Setting Up Patroni with etcd
Patroni orchestrates PostgreSQL instances into a highly available cluster. It uses a distributed key-value store like etcd to store cluster state and leader election. To set up Patroni: install Patroni on each node, configure etcd, and create a Patroni configuration file (patroni.yml). The configuration defines the cluster name, PostgreSQL parameters, replication settings, and etcd endpoints. Patroni manages PostgreSQL via a REST API and automatically handles failover, replication, and recovery. Below is a minimal patroni.yml for a three-node cluster. After starting Patroni on each node, the cluster will elect a primary and replicas will stream from it.
3. Managing Failover with Patroni
Patroni automatically handles failover when the primary becomes unreachable. It uses a leader election algorithm based on etcd's distributed locks. When the primary fails, Patroni on the replicas detect the loss of the leader lock and hold an election. The replica with the most recent WAL position becomes the new primary. You can also trigger manual failover using patronictl failover. Patroni supports switchover (planned failover) for maintenance. During failover, Patroni ensures that the old primary is fenced (e.g., via pg_ctl stop or hardware watchdog) before promoting a new primary to prevent split-brain. The failsafe_mode option can be enabled to require a majority of etcd nodes for promotion, adding an extra safety net.
ttl (time-to-live) appropriately. A short TTL (e.g., 30s) speeds up failover but may cause false positives during transient network issues. A longer TTL (e.g., 60s) is more stable but increases downtime.4. Introduction to repmgr
repmgr (Replication Manager) is a simpler alternative to Patroni. It manages PostgreSQL replication and provides tools for monitoring, failover, and switchover. repmgr uses a dedicated database (repmgr metadata) to track cluster state. It supports both synchronous and asynchronous replication. Unlike Patroni, repmgr does not use distributed consensus; it relies on a single monitoring database. Failover can be manual or automated via cron jobs or event triggers. repmgr is easier to set up but lacks the automatic self-healing and quorum-based decisions of Patroni. It's suitable for smaller deployments or teams that prefer a more hands-on approach.
5. Fencing and Split-Brain Prevention
Fencing (also called STONITH - Shoot The Other Node In The Head) is critical to prevent split-brain scenarios where two nodes both think they are primary. In Patroni, fencing is achieved by using a watchdog device (e.g., Linux watchdog) or by issuing a pg_ctl stop command to the failed primary. repmgr relies on manual intervention or external fencing mechanisms. Without proper fencing, a network partition can lead to data corruption. Best practices: enable STONITH via hardware watchdog or IPMI, configure Patroni's failsafe_mode, and use synchronous replication to minimize data loss. Always test fencing by simulating network partitions.
failsafe_mode which requires etcd quorum for promotions.6. Monitoring and Alerting for HA Clusters
Monitoring is essential for maintaining a healthy HA cluster. Key metrics to monitor: replication lag, cluster state (primary/replica), etcd health, and Patroni API status. Use tools like Prometheus with the postgres_exporter and Patroni exporter. Set up alerts for replication lag exceeding thresholds, node failures, and etcd leader changes. Patroni exposes a REST API at /cluster that returns JSON with cluster status. You can integrate this with your monitoring stack. repmgr provides command-line tools like repmgr cluster show and repmgr standby follow. Additionally, monitor PostgreSQL logs for errors related to replication or failover.
7. Zero-Downtime Upgrades and Maintenance
One of the benefits of HA is the ability to perform upgrades without downtime. For PostgreSQL minor version upgrades, you can use a rolling upgrade: failover to a replica, upgrade the old primary, then fail back. For major version upgrades, use logical replication or tools like pg_upgrade with Patroni's switchover. Patroni supports switchover for planned role changes. repmgr also provides repmgr standby switchover. Always test upgrades in a staging environment. During maintenance, ensure that the application connection strings are updated to point to the new primary if using a connection pooler like PgBouncer or HAProxy.
The Split-Brain Nightmare: A Fencing Failure
remove_data_after_initdb to clean up the old primary's data. Also added failsafe_mode to prevent promotion without quorum.- Always enable fencing (STONITH) in production clusters.
- Test network partition scenarios regularly.
- Use synchronous replication to minimize data loss during failover.
- Monitor etcd cluster health as it's the single point of failure for Patroni.
- Document and practice failover procedures.
patronictl list. If primary is down, verify etcd health and trigger manual failover if needed.pg_stat_replication on primary. Ensure network bandwidth and replica resources are adequate. Consider using synchronous replication.pg_ctl stop -m fast. Use patronictl remove to clean up the rogue node. Investigate fencing configuration.ttl and loop_wait settings. Ensure the replica is in streaming replication mode.patronictl -c /etc/patroni.yml listpatronictl -c /etc/patroni.yml failover --master <old_primary> --candidate <new_primary>| File | Command / Code | Purpose |
|---|---|---|
| check_replication.sql | SELECT client_addr, state, sync_state, write_lag, flush_lag, replay_lag | 1. Understanding PostgreSQL High Availability Concepts |
| patroni.yml | scope: mycluster | 2. Setting Up Patroni with etcd |
| failover_commands.sh | patronictl -c /etc/patroni.yml list | 3. Managing Failover with Patroni |
| repmgr_register.sql | SELECT repmgr_standby_register( | 4. Introduction to repmgr |
| watchdog_setup.sh | sudo yum install watchdog -y | 5. Fencing and Split-Brain Prevention |
| patroni_health_check.sh | curl -s http://10.0.0.1:8008/cluster | jq . | 6. Monitoring and Alerting for HA Clusters |
| rolling_upgrade.sh | patronictl -c /etc/patroni.yml switchover --master node1 --candidate node2 | 7. Zero-Downtime Upgrades and Maintenance |
Key takeaways
Common mistakes to avoid
3 patternsDisabling fencing in Patroni to avoid complexity.
Using an even number of etcd nodes.
Not testing failover scenarios regularly.
Interview Questions on This Topic
Explain how Patroni achieves high availability for PostgreSQL.
Frequently Asked Questions
20+ years shipping high-throughput database systems. Drawn from code that ran under real load.
That's MySQL & PostgreSQL. Mark it forged?
3 min read · try the examples if you haven't