Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Prevent Data Loss During Database Replication Failover

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Database replication failover is the process of automatically switching from a primary database to a standby replica when the primary fails or becomes unreachable. Without proper safeguards, this switch can lead to data loss—typically when the replica is behind on applying transactions or when failover is triggered during a network partition. This guide outlines concrete steps to minimize or eliminate data loss during failover, covering configuration, testing, and operational practices.

What You'll Need

  • Access to your database configuration files (e.g., PostgreSQL postgresql.conf, MySQL my.cnf, or your cloud provider's settings).
  • Administrative privileges on both primary and replica servers.
  • A monitoring tool or script to check replication lag and health.
  • A documented runbook or checklist for failover procedures.
  • Optional: A staging environment that mirrors production for testing failover.

Step-by-Step

  1. Enable synchronous replication where possible. In synchronous replication, the primary waits for the replica to confirm a transaction before acknowledging it to the client. This guarantees zero data loss if the primary fails, as long as the replica is still available. For PostgreSQL, set synchronous_commit = on and define synchronous_standby_names. For MySQL, use semi-synchronous replication with rpl_semi_sync_master_enabled = 1 and rpl_semi_sync_slave_enabled = 1. Be aware that synchronous replication increases latency and can block writes if the replica is down.
  2. Monitor replication lag continuously. Lag is the time or number of transactions the replica is behind the primary. Use built-in tools like pg_stat_replication for PostgreSQL or SHOW SLAVE STATUS for MySQL. Set up alerts when lag exceeds a threshold (e.g., 5 seconds or 100 transactions). If lag is high, failover will lose recent writes.
  3. Configure automatic failover with a quorum. If using a cluster manager (e.g., Patroni, Pacemaker, or cloud-managed services), ensure that failover only triggers when a majority of nodes agree the primary is down. This prevents a network partition from causing both nodes to think the other is dead and split-brain. For example, with three nodes, require at least two to agree.
  4. Test failover regularly in a staging environment. Simulate primary failure (e.g., kill the primary process, disconnect network) and observe whether the replica promotes without data loss. Verify that the promoted replica has all committed transactions. Automate this test if possible, and document the results.
  5. Use a replication slot or GTID to track positions. PostgreSQL replication slots ensure the primary retains WAL segments until the replica has consumed them, preventing the replica from falling too far behind. MySQL GTIDs (Global Transaction Identifiers) allow replicas to know exactly which transactions they have applied, making failover safer. Enable these features and monitor their status.
  6. Set a failover policy that prioritizes data integrity over availability. If you must choose, configure your system to refuse to promote a replica that is significantly behind, rather than promoting it and losing data. For example, in Patroni, set maximum_lag_on_failover to a small value. This means failover may not happen if the replica is too far behind, but you avoid silent data loss.
  7. Before manual failover, verify the replica is current. If you are doing a manual switch, check replication lag first. If lag is non-zero, decide whether to wait for it to catch up or accept the loss. In many cases, you can also stop writes on the primary, wait for the replica to catch up, then promote it.
  8. After failover, verify data integrity immediately. Run checks like row counts on critical tables, compare checksums, or use tools like pt-table-checksum (Percona Toolkit) for MySQL. This catches any discrepancies early.
  9. Document and rehearse the failover procedure. Even with automation, have a runbook that lists every step, including how to check lag, how to promote, and how to redirect applications. Rehearse it at least quarterly.

Common Mistakes

  • Assuming asynchronous replication is safe. Asynchronous replication can lose data by design. If you use it, you must accept potential data loss or implement additional safeguards like periodic backups.
  • Ignoring replication lag alerts. Many failures happen after lag has been high for a while. If you don't act on alerts, failover will lose data.
  • Not testing failover. Failover that has never been tested will likely fail in production. Test both clean switches and abrupt failures.
  • Misconfiguring synchronous replication. Setting synchronous_commit without listing standby names, or using it with multiple replicas, can cause unexpected blocking or data loss if not understood.
  • Forgetting about application connection timeouts. If the application doesn't reconnect quickly after failover, it may queue writes that are lost.

Tips

  • Use a load balancer or connection pool that supports automatic failover detection, so applications reconnect to the new primary without manual intervention.
  • Keep backups as a last resort. Even with replication, take regular backups and test restoration. Replication is not a backup—it doesn't protect against accidental data deletion or corruption.
  • If using a cloud provider, understand their failover semantics. Some managed services (like Amazon RDS Multi-AZ) handle failover automatically, but you should still know the RPO (Recovery Point Objective) they provide.
  • Consider using a tool like pg_rewind (PostgreSQL) to quickly reattach the old primary after failover, reducing the time it takes to restore redundancy.
  • Monitor not just lag, but also replication errors. A broken replication channel is worse than a lagging one.

Troubleshooting

Failover did not happen automatically. Check if the cluster manager's quorum is intact. If the primary is isolated but still running, it may not be detected as down. Verify network connectivity and that the health checks are configured correctly.

Replica is too far behind to promote without data loss. If you must fail over, consider using a point-in-time recovery (PITR) from backups to recover the lost transactions after promotion. This is complex and should be rehearsed.

Split-brain occurred (both nodes are primary). This is a critical situation. Immediately stop writes on one node, keep the one with the most recent data, and then re-establish replication. Use fencing mechanisms (like STONITH) to prevent this in the future.

Replication is stuck after failover. The old primary may need to be re-initialized or re-synced. Use tools like pg_rewind or rebuild the replica from a backup. Do not just restart replication without checking consistency.

Application still writes to the old primary. Update connection strings or DNS entries. Use a proxy that routes to the current primary.

Frequently Asked Questions

Q: Can I guarantee zero data loss with asynchronous replication?
A: No. Asynchronous replication inherently risks losing transactions that were committed on the primary but not yet sent to the replica. To guarantee zero data loss, you must use synchronous replication or a similar mechanism.

Q: What is the difference between RPO and RTO?
A: RPO (Recovery Point Objective) is the maximum acceptable data loss measured in time (e.g., 5 seconds). RTO (Recovery Time Objective) is the maximum acceptable downtime. Failover design aims to minimize both, but they often trade off against each other.

Q: How often should I test failover?
A: At least quarterly, and after any major configuration change. More frequent testing (monthly) is better if your environment allows it.

Q: Does synchronous replication slow down my database?
A: Yes, it adds latency because the primary waits for the replica's acknowledgment. The impact depends on network distance and workload. You can mitigate by using a local replica or by tuning synchronous_commit levels (e.g., remote_write in PostgreSQL).

Q: What is a replication slot and why is it important?
A: A replication slot in PostgreSQL ensures the primary keeps the WAL files needed by a replica, even if the replica is disconnected. Without it, the primary might delete WAL segments, making the replica unable to catch up. It's crucial for preventing lag from becoming unrecoverable.

Q: Can I use backups as a substitute for replication?
A: No. Backups provide a point-in-time snapshot, but they don't give you real-time failover. You would lose all data since the last backup. Replication is for high availability; backups are for disaster recovery.