Introduction to data replication
easy 25 minReplication keeps the same data on several machines and keeps the copies up to date.
See it run
Copies of the same data: how they are added, what they serve, and who is allowed to write.
Operations
Grow a replicated set
From one database to three replicas and a failover. The read and write numbers are an example.
Step 1 of 8
One server
writes per second
100
reads per second
primary 1000
Single point of failure
It holds A, B and C and does all the work. If it dies, everything stops.
Step 1: One server
primary = start() # 1 everything on one serverreplica = copy_of(primary) # 2 a full copy firstprimary.write("D") # 3 the replica has no D yetsend_changes(primary, replica) # 4 the change log travelsreplica.apply_changes() # 5 the copies agreeadd_replicas("US-West", "EU") # 6 more reads, nearer users# 7 the primary crashespromote(best_replica()) # 8 a replica takes over- Who writes
- One leader
- Main cost
- Copies lag
- One server only
- single point of failure
Say out loud what each copy serves. A replica nobody reads from is still useful: it is a standby.
In the real world
The same introduction to data replication doing real jobs. Pick one and step through it.
Why a replica is not a backup.
Step 1 of 3
Three healthy copies
writes per second
100
reads per second
spread
Primary and two replicas hold all the orders.
Step 1: Three healthy copies
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Reading your own write from a replica
majorThe replica may not have it yet, so users think their change was lost and send it again.
Wrongpool.write(save_profile)return pool.read(profile) # may be oldRightpool.write(save_profile)return pool.read_from_primary(profile)Adding replicas for write load
criticalEvery copy repeats every write. The primary stays as busy as before.
Wrong# writes at 95%add_replicas(3)Right# writes at 95%reduce_or_batch_writes()then_shard()Treating a replica as a backup
criticalDeletes and corruption are copied within moments.
Wrongbackups = [replica_1]Rightbackups = daily_snapshots + archived_logrestore_test_every_month()Unlimited fallback to the primary
majorWhen replicas die, all their reads land on the primary and can take the writes down too.
Wrongnode = replica or primaryRightnode = replicaif node is None and primary.has_room(): node = primaryelif node is None: shed_low_value_reads()
Interview tips
How to explain it
- Same data, several machines, kept up to date.
- Availability, read scaling, nearness.
- Copies can briefly disagree.
Memory trick: SAFE
- Scale reads.
- Availability: survive failures.
- Failover to a replica.
- Eventual or strong consistency.
Reach for it when
- One server must not be able to stop you.
- Reads dominate.
- Users are far from the data.
Look elsewhere when
- Writes are the limit: shard.
- The data no longer fits: shard.
- You need older versions: backups.