Replication
One database machine can die, or get more reads than it can handle. Copies help with both.
Why copy data
Replication keeps full copies of the same database on several machines. If one machine dies, the others still have the data. Copies can also share the reads and sit near far-away users. Every copy holds all the data, so replication does not let you store more. It is not a backup either: a mistaken delete is copied everywhere.
Primary and replicas
One machine is the primary (also called the leader). All writes go to it. It sends each change to the replicas (followers), which apply it in order. Reads can go to any replica. Adding replicas gives more room for reads, but every write still goes to the one primary.
Replication lag
Replicas get each change a little after the primary. This delay is replication lag, often a few milliseconds, but it can grow to seconds under load. So a user can save a change, reload, and see the old value. A simple fix: for a short time after a user writes, send that user's reads to the primary.
Synchronous or asynchronous
With synchronous replication, the primary waits for a replica to confirm before it tells the client "saved". No confirmed write is lost if the primary dies, but each write is slower. With asynchronous replication, the primary replies at once and sends the change after. Writes are fast, but the last few can be lost if the primary dies. Many setups wait for one replica and let the rest catch up.
Failover
When the primary dies, writes stop. Failover promotes the most up to date replica to be the new primary. The old primary must be kept out. If it comes back still acting as primary, two machines take writes, and the data can conflict.
Remember
- Writes go to the primary; reads can go to replicas.
- Replicas lag, so a user may not see their own write.
- Sync is safer, async is faster.
- Failover promotes a replica; keep the old primary out.