Sub topic 7
Eventual Consistency and its Anomalies
This chapter assumes you know what replication is, that a consistency model is a contract on histories, and that linearizability is the strongest common contract. You should be comfortable reading short Python programs.
What eventual consistency promises
Eventual consistency is a weak contract. It says: if clients stop writing to a data item, then after some period all replicas will hold the same value, and every read will return it.
That promise has three parts worth separating.
- Liveness only. The contract says replicas converge "eventually". It gives no bound on how long that takes. It is a statement about where the system ends up, not about what any read returns along the way.
- It needs quiescence. The guarantee applies once writes stop. Under continuous writes, replicas may never all agree at one instant.
- It needs convergence. If two replicas receive conflicting writes, something must pick a winner or merge them, or they will stay different forever. Later chapters cover conflict resolution.
In practice, "eventually" is usually milliseconds to seconds. During a network partition or a failed replica, it can be minutes or hours.
Why systems accept it
A write to a strongly consistent system must wait for coordination with other replicas. An eventually consistent system acknowledges a write after it reaches one replica, or a few, and propagates it in the background. This gives three benefits:
- Lower latency, because clients do not wait for distant replicas.
- Higher availability, because any reachable replica can serve reads and writes, even during a partition.
- Easier scaling across regions.
The cost is that clients can observe states that a single-copy system would never show. These are the anomalies.
How replicas converge
Eventually consistent stores use background mechanisms to spread updates. These are the usual ones:
- Asynchronous replication. The replica that takes the write sends it to peers after replying to the client.
- Read repair. When a read contacts several replicas and sees different versions, it writes the newest version back to the stale ones.
- Anti-entropy. A background process compares replica contents, often with hash trees, and copies missing data.
- Hinted handoff. If a replica is down, another node stores the write temporarily and delivers it when the replica returns.
The stale read in the diagram is legal under eventual consistency. The write was acknowledged before Client B's read began, so this history is not linearizable. It is still allowed, because the contract only demands convergence.
The anomalies
Because the contract constrains so little, a client can see several kinds of surprising behavior. Each is a different way the history departs from a single copy.
| Anomaly | What the client sees | Typical cause |
|---|---|---|
| Stale read | An old value after a newer one was acknowledged | Read served by a replica that has not yet received the write |
| Read-your-writes violation | A client writes, then reads and does not see its own write | Write goes to one replica, read goes to another |
| Non-monotonic reads | A read returns a newer value, then a later read returns an older one | Successive reads routed to replicas at different staleness |
| Causality violation | A reply is visible before the message it answers | Updates arrive at a replica out of causal order |
| Lost update | One of two concurrent writes silently disappears | Last-write-wins resolution or a read-modify-write race |
| Divergent replicas | Replicas keep different values | No conflict resolution for concurrent writes |
Read-your-writes violation
A user posts a comment and reloads the page. The load balancer sends the read to a replica that has not received the comment yet. The user thinks the post failed and posts again.
Non-monotonic reads
Time appears to move backward. A client reads x = 2 from a fresh replica, then reads x = 1 from a stale one. This is often more confusing than plain staleness, because the client has already seen the newer state.
Causality violation
Alice posts "Is the server down?" and Bob replies "No, it is up." If a replica delivers Bob's reply before Alice's question, a reader sees an answer to nothing. Pure eventual consistency does not preserve this order. Causal consistency, covered later, does.
Lost updates
Two clients each read a counter at 5 and write back 6. The correct result is 7. If the store resolves the two writes by keeping only one, an increment is lost. Replicas converge, so the eventual consistency contract is met, yet the data is wrong from the application's point of view.
You can see the lost update in a small simulation. Two replicas each accept a write with a timestamp, and the merge keeps the later timestamp.
def lww_merge(a, b):
"""Last-write-wins: keep the (timestamp, value) pair with the larger timestamp."""
return a if a[0] >= b[0] else b
# Both clients read the counter at 5 and write back 6.
replica1 = (100, 6) # client 1 wrote at t=100
replica2 = (101, 6) # client 2 wrote at t=101
merged = lww_merge(replica1, replica2)
print(merged) # (101, 6)
print("expected 7, got", merged[1]) # expected 7, got 6Both replicas converge to (101, 6), so the system is eventually consistent. One increment is gone. Counting without loss needs a different data structure, such as the grow-only counter shown in a later chapter.
Divergence and clock problems
Last-write-wins depends on timestamps, and physical clocks on different machines drift. A client whose clock runs ahead can overwrite newer data from a client with a correct clock. This is a correctness problem, not only a tuning one.
What eventual consistency does not say
Several misconceptions are common.
- "Eventual" does not mean "soon". The contract sets no time limit. Real systems have measured behavior, and you should measure it.
- It does not mean "no guarantees at all". Convergence is a real property. Many systems add stronger guarantees on top, such as session guarantees.
- It does not mean data loss is acceptable. A write that is acknowledged and then lost because of a crash before replication is a durability failure, which is a separate issue.
- It is not a single model. Systems that call themselves eventually consistent differ in conflict handling, ordering and staleness bounds.
Measuring staleness
You can quantify the gap instead of guessing. Two common measurements are:
- Time-based staleness: how long after a write completes can a read still return an older value.
- Version-based staleness: how many versions behind the returned value is.
Here is a small simulation that estimates the fraction of stale reads when replication has a random delay.
import random
def stale_read_fraction(trials=10000, max_delay_ms=50, read_after_ms=20, seed=1):
"""Write at t=0 to replica 1. Replica 2 receives it after a random delay.
A read from replica 2 at read_after_ms is stale if the delay is longer."""
rng = random.Random(seed)
stale = 0
for _ in range(trials):
delay = rng.uniform(0, max_delay_ms)
if delay > read_after_ms:
stale += 1
return stale / trials
print(round(stale_read_fraction(), 2)) # about 0.6
print(round(stale_read_fraction(read_after_ms=50), 2)) # 0.0With a uniform delay from 0 to 50 ms, a read at 20 ms is stale about 60% of the time. A read at 50 ms is never stale. Real delays have long tails, so real distributions are less tidy. Look at high percentiles, not the average.
Living with the anomalies
You have three broad options.
- Accept them. For view counts, recommendations, or caches, a stale or slightly wrong value is harmless.
- Strengthen the contract. Add session guarantees, causal consistency, or quorum reads, which the next chapters cover.
- Handle them in the application. Use idempotent operations, version checks, and merge-friendly data types so that conflicts do not lose data.
Summary
Eventual consistency guarantees only convergence once writes stop. It trades single-copy behavior for latency and availability. The cost shows up as stale reads, read-your-writes violations, non-monotonic reads, causality violations and lost updates. Each can be reduced with a stronger contract or with careful application design.
Exercise
A client writes x=1 and gets an acknowledgment. It then reads x from a different replica and receives 0. A moment later, it reads again from a third replica and receives 1, and then a fourth read from the second replica returns 0 again. Name each anomaly shown, and say whether the system could still be eventually consistent.
Show answer
The first read of 0 is a stale read and a read-your-writes violation, because the client's own acknowledged write is not visible. The read of 1 followed by 0 is a non-monotonic read, because the client saw a newer value and then an older one. The system can still be eventually consistent, because the contract only requires that replicas converge once writes stop. If the second replica receives x=1 later and all reads then return 1, the contract holds.
Exercise
Two clients concurrently increment a counter that holds 10. Each reads 10 and writes 11. The store uses last-write-wins and the replicas converge to 11. Is the system eventually consistent? Is the result correct? Name a way to avoid the problem.
Show answer
The system is eventually consistent, because the replicas converge to one value. The result is wrong, because two increments should give 12. This is a lost update. You can avoid it by using a merge-friendly data type such as a grow-only or PN counter CRDT, by sending the increment as an operation instead of a value, or by using a compare-and-set that fails when the version has changed.