Skip to content

Replication (Master-Slave / Master-Master)

Keeping copies of the same data on multiple machines.

Why Replicate?

ReasonDescription
High AvailabilitySystem stays up if node fails
Fault ToleranceNo single point of failure
Read ScalingSpread reads across replicas
Disaster RecoveryReplica in different data center
Low LatencyReplica 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-SlaveMaster-Master
Write nodeOnly masterBoth nodes
ConflictsNonePossible
ComplexityLowHigh
Write scalingLimitedBetter
Use caseRead-heavy appsHigh availability writes