Sub topic 1
Why replication creates consistency questions
Prerequisites
This chapter assumes you can do the following:
- Describe a client-server system, including what a network timeout means.
- Use a key-value store or database, with
get/putorSELECT/UPDATEoperations. - Read short Python programs with classes, dictionaries, and lists.
You do not need to know any consistency models yet. This chapter explains why they are needed. Later chapters define them.
Why systems replicate data
Replication means keeping copies of the same data on more than one machine. Teams do it for three main reasons:
- Availability. If one machine fails, another copy can still serve requests.
- Latency. A copy near the user answers faster than a distant one.
- Read throughput. Many replicas can serve reads in parallel, so one machine is not the bottleneck.
A single machine has a simple rule. After you write x = 1, every later read of x returns 1, because there is one place the value can live. Replication removes that guarantee. Once the value lives in several places, the copies can disagree, and the system must say which answers are acceptable.
The core problem: copies update at different times
A write must travel over a network to every replica. Networks are slow and unreliable, and machines fail independently. So replicas receive the same write at different times, or never receive it. Between the first and last arrival, a reader can see either the old value or the new one, depending on which replica it contacts.
The following sketch shows this with one leader and one follower. The leader accepts writes. It ships them to the follower later, as real asynchronous replication does.
class Replica:
def __init__(self, name):
self.name = name
self.data = {}
class Cluster:
def __init__(self):
self.leader = Replica("leader")
self.follower = Replica("follower")
self.pending = [] # writes accepted but not yet shipped
def write(self, key, value):
self.leader.data[key] = value
self.pending.append((key, value))
def replicate(self):
while self.pending:
key, value = self.pending.pop(0)
self.follower.data[key] = value
def read(self, replica, key):
return replica.data.get(key)
c = Cluster()
c.write("x", 1)
print(c.read(c.leader, "x")) # 1
print(c.read(c.follower, "x")) # None, a stale read
c.replicate()
print(c.read(c.follower, "x")) # 1The write succeeded, yet a read from the follower returned None. Nothing is broken in the code. The window between write and replicate is the replication lag, and any read that lands in that window is a stale read: it returns a value that is out of date.
Replication strategies and where disagreement comes from
How replicas receive writes determines what kinds of disagreement are possible.
| Strategy | Who accepts writes | Typical disagreement |
|---|---|---|
| Single-leader | One leader, followers copy it | Followers lag behind the leader |
| Multi-leader | Several leaders, each copies the others | Two leaders accept conflicting writes to the same key |
| Leaderless | Any replica, the client contacts several | Replicas miss writes, so reads must compare answers |
Single-leader replication has no write conflicts, because one machine orders all writes. It still has lag, and it has a failover problem: if the leader dies, a follower that missed recent writes may be promoted, and those writes are lost or contradicted later.
Multi-leader and leaderless designs accept writes in more than one place. They gain availability and low latency. They pay with conflicts: two clients write the same key at nearly the same time on different replicas, and the system must decide what the final value is.
Synchronous versus asynchronous replication
The leader can acknowledge a write at different points:
- Synchronous: the leader waits until followers confirm the write before replying
ok. A follower is rarely behind, but a slow or dead follower stalls every write. - Asynchronous: the leader replies
okimmediately and ships the write in the background. Writes are fast and tolerate slow followers, but acknowledged writes can be lost if the leader crashes before shipping them. - Semi-synchronous: the leader waits for some followers, such as one, and ships to the rest in the background. This is a common compromise.
Each choice trades latency and availability against how closely the copies agree. That is the same trade-off that the rest of this tutorial formalizes.
Failure cases that make this harder
Lag is only the simplest source of trouble. These cases come up in real systems:
- Unknown write outcome. A client sends a write and the connection times out. The write may have applied, may apply later, or may never apply. The client cannot tell which. Retrying a non-idempotent operation, such as incrementing a counter, can apply it twice.
- Network partition. A partition is a network failure that splits replicas into groups that cannot talk to each other. Both groups may keep running and accept different writes.
- Reads from different replicas. A client's first read may hit a fresh replica and its second read a stale one. The user sees data go backward in time.
- Out-of-order delivery. Messages can arrive in a different order than they were sent. Two replicas that apply the same writes in different orders can end with different values.
- Clock disagreement. Machines have clocks that drift. Using timestamps to decide which write is newer can pick the wrong one.
Why this becomes a question about contracts
Without replication, a developer never has to ask "which value will I read?" With replication, the answer varies, so the system must state what it guarantees. A guarantee about which values reads and writes may return is a consistency model. The next chapter defines this precisely as a contract on histories, meaning the recorded sequences of operations that clients performed and observed.
Two points set the direction for the rest of the tutorial:
- Stronger guarantees cost something. Making replicas agree before answering needs coordination, which adds latency and can block during failures.
- Weaker guarantees move work to you. If the system allows stale or conflicting reads, the application must tolerate them or repair them.
Neither choice is wrong in general. A shopping cart that occasionally shows an old item is a mild problem. A bank balance that lets two withdrawals both succeed is a serious one. Choosing well requires knowing what the available contracts are, which is the goal of the following chapters.
Key terms
- Replica: one copy of the data on one machine.
- Replication lag: the delay between a write on one replica and its arrival on another.
- Stale read: a read that returns a value older than the latest completed write.
- Conflict: two writes to the same data that were accepted independently and cannot both be the final value.
- Partition: a network failure that prevents some replicas from communicating.
Exercise
In the Python sketch, client A calls write("x", 1) and gets ok. Client B then reads x from the follower and gets None. Name the cause, and name one way to change the replication design so B's read would not be stale, along with its cost.
Show answer
The cause is replication lag: the leader acknowledged the write before shipping it to the follower, so the follower had not yet applied it. One fix is synchronous replication, where the leader replies ok only after the follower confirms the write. The cost is higher write latency, and writes stall if the follower is slow or unreachable. Reading only from the leader also avoids the stale read, at the cost of losing read scaling and locality.
Exercise
A client sends "increment counter" to a leader and the connection times out before any reply. Why is it unsafe to simply retry, and what does this show about replicated systems?
Show answer
The write may already have been applied, or may still be applied later, so a retry can increment the counter twice. The client cannot distinguish a lost request from a lost reply. This shows that a write's outcome can be unknown, so systems and clients need idempotent operations or request identifiers to make retries safe.