Replication and Replicas
Replication is keeping copies of the same data on more than one machine. In leader-follower replication, one leader takes every write and the followers copy the leader.
A write reaches the leader first
A write changes the city on the leader. The new value is then copied to each follower in turn.
leader = {"name": "Ana", "city": "Lisbon"}
follower1 = dict(leader)
follower2 = dict(leader)
leader["city"] = "Porto"
print("Leader after write:", leader)
follower1["city"] = leader["city"]
print("Follower 1 after copy:", follower1)
follower2["city"] = leader["city"]
print("Follower 2 after copy:", follower2)Followers serve the reads
Reads go to the followers in turn. The counts show the leader serving none of the reads.
leader = {"name": "Ana", "city": "Porto"}
followers = [dict(leader), dict(leader)]
names = ["Follower 1", "Follower 2"]
counts = {"Follower 1": 0, "Follower 2": 0, "Leader": 0}
reads = ["city", "name", "city", "name", "city", "name"]
for i in range(len(reads)):
server = names[i % 2]
counts[server] = counts[server] + 1
print("Read of", reads[i], "served by", server)
print("Reads per server:", counts)A write sent to a follower
This demo sends a write straight to a follower. The model refuses the write and the follower keeps the copied value.
leader = {"name": "Ana", "city": "Porto"}
follower = dict(leader)
def write_to_follower(data, key, value):
return "Refused: followers do not accept writes"
result = write_to_follower(follower, "city", "Braga")
print(result)
print("Follower after the attempt:", follower)
print("Leader still holds:", leader)Example
leader = {}
follower1 = {}
follower2 = {}
leader["name"] = "Ana"
follower1["name"] = leader["name"]
follower2["name"] = leader["name"]
print("After first write and copies:", leader, follower1, follower2)
leader["city"] = "Porto"
follower1["city"] = leader["city"]
follower2["city"] = leader["city"]
print("After second write and copies:", leader, follower1, follower2)
print("Read of city from Follower 2:", follower2["city"])Key points
- Replication: the same data is stored as copies on several machines.
- Leader: the one copy that accepts writes and sets the current value.
- Follower: a copy that receives changes from the leader and serves reads.
- Use followers to share read work across machines and to keep a copy if one machine fails.
In this example, each write lands on the leader and is then copied to both followers. Every copy ends with the same values, and a read served by a follower returns the copied city.
Note
A write sent to a follower is refused, because only the leader accepts writes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
In leader-follower replication, which copy accepts a write?