Appearance
Replication (Master-Slave / Master-Master)
Keeping copies of the same data on multiple machines.
Why Replicate?
| Reason | Description |
|---|---|
| High Availability | System stays up if node fails |
| Fault Tolerance | No single point of failure |
| Read Scaling | Spread reads across replicas |
| Disaster Recovery | Replica in different data center |
| Low Latency | Replica closer to user geographically |
Master-Slave Replication (Primary-Replica)
One MASTER node handles ALL writes. One or more SLAVE nodes handle reads and sync from master.
How Replication Works Internally
- Master writes to its own storage
- Master writes change to binary log (binlog)
- Slaves read binlog continuously
- Slaves apply same changes to their storage
MySQL = binlog replication. PostgreSQL = WAL (Write Ahead Log) shipping.
Synchronous vs Asynchronous Replication
- Asynchronous (default): Master commits write immediately. Slaves sync in background. Fast writes but slaves might be slightly behind.
- Synchronous: Master waits for at least one slave to confirm. Slower writes, zero data loss.
- Semi-synchronous: Master waits for just ONE slave to confirm. Balance of safety and speed.
Replication Lag Problem
Master has balance = 800 (just written). Slave has balance = 500 (not yet synced). User writes to master, reads from slave → sees old value. Solutions: read your own writes from master, sticky sessions, sync replication for critical reads.
Failover & Split-Brain Risk
Split-brain: Master appears down (network issue, not actual crash), new master elected, old master comes back, two masters accepting writes. Solved by STONITH (Shoot The Other Node In The Head) or fencing mechanisms.
Master-Master Replication (Multi-Primary)
Two or more nodes EACH can accept reads AND writes. Both masters sync changes to each other.
The Write Conflict Problem
User A writes to Master 1: balance = 800
User B writes to Master 2: balance = 600 (same row, same time)
When they sync → CONFLICT — Which value wins?Conflict Resolution
- Last Write Wins (timestamp): simple but can lose data
- Route same DATA ENTITY to same master (essentially sharding)
- CRDTs: conflict-free data structures
- Consensus (Raft/Paxos): majority must agree before write accepted. Used by CockroachDB, Google Spanner.
Master-Slave vs Master-Master
| Master-Slave | Master-Master | |
|---|---|---|
| Write node | Only master | Both nodes |
| Conflicts | None | Possible |
| Complexity | Low | High |
| Write scaling | Limited | Better |
| Use case | Read-heavy apps | High availability writes |