Sub topic 10
Causal consistency
This chapter assumes you know what a consistency model is, have read the chapters on linearizability and sequential consistency, and understand happens-before and vector clocks. The Python examples build directly on the vector clock comparison from the previous chapter.
The idea: preserve cause and effect, ignore the rest
Linearizability and sequential consistency force every client to see one total order of operations. That order costs coordination between replicas, and the coordination costs latency and availability.
Causal consistency asks for less. It requires every client to see operations in an order that respects causality. If operation a could have influenced operation b, nobody may observe b without having observed a first. Operations with no causal link ("concurrent" operations) may appear in different orders at different replicas.
A discussion thread shows why this matters:
- Alice posts "Is the build broken?"
- Bob reads that post and replies "Yes, I'm fixing it."
- Carol reads the thread.
Under eventual consistency, Carol's replica might receive Bob's reply before Alice's question. She would see an answer to a question that does not exist. Causal consistency rules this out. Bob's reply depends on Alice's post, so any replica that shows the reply must already show the post.
What counts as a causal dependency
Causality here uses the happens-before relation from the clocks chapter. Operation a happens before b in any of these cases:
- Program order. Both operations come from the same client session, and a was issued first.
- Reads-from. b is issued after its client read a value written by a.
- Transitivity. a happens before some c, and c happens before b.
Two operations are concurrent if neither happens before the other. For concurrent operations the model promises nothing about order. Two replicas may apply them in opposite orders, and clients may see different intermediate states.
How it relates to the other models
| Model | Order that clients must observe | Concurrent writes | Needs coordination on every write |
|---|---|---|---|
| Linearizable | One total order that matches real time | Ordered by real time | Yes |
| Sequential | One total order, any real-time offset | One agreed order | Yes |
| Causal | Any order that respects happens-before | May differ per replica | No |
| Eventual | None until replicas converge | May differ per replica | No |
Causal consistency is strictly weaker than sequential consistency. Every sequentially consistent history is also causally consistent, because a single total order that respects each client's program order and reads-from also respects causality. The reverse does not hold. Two clients may legitimately see two concurrent writes in different orders under causal consistency, and no single total order explains that.
Causal consistency is also strictly stronger than eventual consistency. The plain model has no convergence requirement, though, so a causal system can still leave two replicas permanently different after concurrent writes. Most real systems therefore add a convergence rule, usually called causal+ consistency. Concurrent writes to the same key are resolved by a deterministic function, such as last-write-wins or a CRDT merge, so that all replicas end in the same state. That function is the topic of the conflict resolution chapter.
Implementing it: dependency tracking and delayed delivery
A replica cannot know in advance what order messages will arrive in. To enforce causality it attaches a vector clock to each update and delays delivery of any update whose dependencies have not been delivered yet.
For an update from sender s carrying vector clock V, a replica with delivered-vector D may deliver it when both conditions hold:
V[s] == D[s] + 1. This is the next update froms, with no gaps.- For every other node
k,V[k] <= D[k]. Everything thatshad seen before sending has already been delivered here.
Otherwise the update waits in a pending buffer. This code implements the rule:
def deliverable(msg_clock, sender, delivered):
"""True if the message's causal dependencies are all delivered."""
if msg_clock.get(sender, 0) != delivered.get(sender, 0) + 1:
return False
return all(
msg_clock.get(k, 0) <= delivered.get(k, 0)
for k in msg_clock
if k != sender
)
class Replica:
def __init__(self):
self.delivered = {} # node -> number of its updates delivered here
self.pending = [] # updates waiting for dependencies
self.log = [] # values in the order they became visible
def receive(self, sender, clock, value):
self.pending.append((sender, clock, value))
self._drain()
def _drain(self):
progress = True
while progress:
progress = False
for item in list(self.pending):
sender, clock, value = item
if deliverable(clock, sender, self.delivered):
self.pending.remove(item)
self.delivered[sender] = clock[sender]
self.log.append(value)
progress = True
carol = Replica()
# Bob's reply arrives first. It depends on Alice's update A:1.
carol.receive("B", {"A": 1, "B": 1}, "Yes, I'm fixing it.")
print(carol.log) # []
# Alice's question arrives. Both can now be delivered, in causal order.
carol.receive("A", {"A": 1}, "Is the build broken?")
print(carol.log) # ['Is the build broken?', "Yes, I'm fixing it."]The loop in _drain repeats because delivering one update can unblock others that were waiting on it.
Concurrent updates take no part in this ordering. If one message carries {"A": 1} and another carries {"B": 1}, each passes deliverable on an empty replica, so they are delivered in whatever order they arrive. That freedom is why causal consistency needs no cross-replica coordination.
Costs and failure modes
- Metadata size. A vector clock has one entry per writer. With thousands of clients or nodes, the clock on every update becomes large. Production systems shrink it by tracking dependencies per key or per datacenter instead of per client, or by using explicit dependency lists that are pruned once an update is known to be everywhere.
- Visibility delay. A replica holds back an update until its dependencies arrive. One slow or lost message can stall many later updates behind it. This is the price of never exposing an effect before its cause.
- Hidden dependencies. The system only knows causality that passes through it. If Alice phones Bob and says "check the new post", Bob's next write is causally related to hers, but the database never saw that link and does not enforce it. This is the "external causality" problem.
- Concurrent writes still need a policy. Two clients can set the same key at the same time, and causal consistency does not say which wins. Without a merge rule, replicas can diverge permanently.
- Not a global invariant tool. Causal consistency cannot enforce "at most one user holds this username" or "the balance never goes negative". Those constraints require agreement on a single order, which means consensus.
Connection to session guarantees
Causal consistency is equivalent to the four session guarantees taken together: read-your-writes, monotonic reads, monotonic writes and writes-follow-reads. That equivalence is why the next chapter treats them as building blocks. A store that offers only some of them gives a cheaper, partial form of causality. For example, read-your-writes and monotonic reads alone fix the most visible user-facing anomalies without tracking dependencies between different users.
Exercise
A replica has delivered {"A": 2, "B": 1}. It receives an update from node C with clock {"A": 2, "B": 2, "C": 1}. Can it deliver the update now? What if the clock were {"A": 3, "C": 1}?
Show answer
The first update is not deliverable. It is C's first update (C: 1 equals 0 + 1), but its clock has B: 2, and the replica has delivered only one update from B, so it must wait for B's second update. The second update has the same problem for node A: A: 3 exceeds the delivered A: 2, so the replica has not yet seen A's third update, which this update depends on. It is buffered until A's third update is delivered.
Exercise
Two clients write to the same key at the same moment at different replicas. The store is causally consistent but has no conflict resolution rule. What can go wrong, and what does causal+ add?
Show answer
The writes are concurrent, so causal consistency allows replicas to apply them in different orders. The replicas can then end with different final values and stay that way. Causal+ adds a deterministic convergence rule for concurrent writes, such as last-write-wins or a CRDT merge, so every replica reaches the same value.