Sub topic 9
Tracking causality with vector clocks
This chapter assumes you know how a key is replicated to N nodes through a preference list, and that a write is acknowledged by W replicas. It also assumes you can read short Python snippets. Quorums decide how many replicas must answer. They do not tell you what to do when two replicas hold different values for the same key. Vector clocks answer that question.
The problem: which write is newer?
Suppose two clients update the key cart:42 at nearly the same moment through different coordinators. Replica A receives one value first, and replica B receives the other. When a reader later contacts both replicas, the store has to decide between three cases:
- One value is a newer version of the other, so the old one can be discarded.
- The values are identical, so nothing needs to be done.
- The two writes did not know about each other, so neither can safely replace the other.
Wall-clock timestamps cannot separate the last two cases reliably. Server clocks drift, and NTP corrections can move a clock backward. A timestamp can only say "this write has a larger number". It cannot say "this write was made by a client who had seen the other one". If you pick the larger timestamp, you may silently discard a legitimate update.
What you need is a record of causality. Write A happened before write B if the client that issued B had already seen A, directly or through a chain of reads and writes. If neither happened before the other, the writes are concurrent. Concurrent means "neither saw the other". It does not mean "at the same instant".
How a vector clock works
A vector clock is a map from node id to a counter. Each stored version of a value carries one. The rules are short:
- A new key starts with an empty clock.
- When a coordinator accepts a write, it takes the clock the client supplied (the context from its earlier read), increments its own counter, and stores the result with the value.
- To compare two clocks, check each component. Clock
ais beforebifais less than or equal tobin every component and the clocks are not equal. If neither dominates the other, the versions are concurrent. - A component missing from a clock counts as 0.
- To merge clocks, take the component-wise maximum.
| Comparison of clocks | Meaning | What the store does |
|---|---|---|
| `a` before `b` | `b` descends from `a` | Keep `b`, drop `a` |
| `a` after `b` | `a` descends from `b` | Keep `a`, drop `b` |
| equal | Same version | Keep one copy |
| concurrent | Neither saw the other | Keep both as siblings |
Implementing it
The compare function is the core. The helpers below it increment a clock, merge two clocks, and decide what happens when a new version arrives at a replica.
def compare(a: dict, b: dict) -> str:
"""Compare two vector clocks mapping node id -> counter."""
keys = set(a) | set(b)
a_le_b = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
b_le_a = all(b.get(k, 0) <= a.get(k, 0) for k in keys)
if a_le_b and b_le_a:
return "equal"
if a_le_b:
return "before"
if b_le_a:
return "after"
return "concurrent"
def increment(clock: dict, node: str) -> dict:
new = dict(clock)
new[node] = new.get(node, 0) + 1
return dict(sorted(new.items()))
def merge(a: dict, b: dict) -> dict:
return {k: max(a.get(k, 0), b.get(k, 0)) for k in sorted(set(a) | set(b))}
def add_version(versions: list, clock: dict, value: str) -> list:
"""versions is a list of (clock, value) pairs held by one replica."""
for existing, _ in versions:
if compare(clock, existing) in ("before", "equal"):
return versions # incoming write is obsolete or a duplicate
survivors = [(c, v) for c, v in versions if compare(c, clock) == "concurrent"]
return survivors + [(clock, value)]
v1 = {"a": 1}
v2 = increment(v1, "a") # client X updates through node a
v3 = increment(v1, "b") # client Y updates through node b, same context
print(v2, v3) # {'a': 2} {'a': 1, 'b': 1}
print(compare(v1, v2)) # before
print(compare(v2, v3)) # concurrent
replica = add_version([], v1, "cart=[book]")
replica = add_version(replica, v2, "cart=[book, pen]")
replica = add_version(replica, v3, "cart=[book, mug]")
print(replica) # two siblings: v2 and v3
resolved = increment(merge(v2, v3), "a")
replica = add_version(replica, resolved, "cart=[book, pen, mug]")
print(resolved) # {'a': 3, 'b': 1}
print(replica) # one version: the resolved oneThe resolved write dominates both siblings, so add_version removes them. This is how a client that has read both siblings can collapse them back into one version.
A worked scenario
The sequence below shows two clients that start from the same version, write through different coordinators, and produce siblings.
Neither write is lost. The store did not choose between them. It kept both and returned them with their clocks. The reader merged the clocks, so the new write dominates both siblings.
Where the clock lives in the API
For this to work, the client must take part. A get returns the value or values plus an opaque context, which is the merged clock of what was returned. A put sends that context back. The coordinator uses it as the starting clock before it increments its own counter.
Gotchas and edge cases
Clock growth
Every node that coordinates a write for a key adds a component to that key's clock. Over a long time, with many coordinators and failovers, clocks grow without bound. Dynamo stores a timestamp with each component and drops the oldest component once the clock passes a size threshold, such as 10 entries. This bounds the size, but it can make the store treat an ordered pair of versions as concurrent, because the dropped history was the proof of ordering. The cost is extra siblings, not lost data.
Server ids or client ids
Putting node ids in the clock keeps clocks small, because the number of servers is limited. Putting client ids in the clock gives more precise causality, but the clock grows with the number of clients, and a client that loses its counter after a restart can reuse a counter value for a different write. Most stores use server ids.
Coordinator retries
If a client times out and retries a put through a different coordinator, the same logical write may be recorded twice with different clocks. The two versions look concurrent, and the reader sees siblings that hold the same value. Application-level merging should be idempotent for this reason.
Equal clocks with different values
Two versions with equal clocks should hold the same value. If they do not, something has gone wrong, for example a coordinator that reused a counter after losing local state. Treat this as a bug and surface it, not as a case for add_version to resolve silently.
Vector clocks and version vectors
Strictly, a vector clock tracks events between processes, while a version vector tracks versions of one data item across replicas. Key-value stores usually implement the second and call it the first. A known weakness of plain version vectors is that concurrent writes handled by the same coordinator can be mistaken for a sequence. Dotted version vectors fix this by attaching the single event that created each version. If your store lets one coordinator accept concurrent writes to the same key, plan for it.
Where this fits in the design
Quorums with R + W > N make sure a read sees at least one replica that took part in the latest successful write. Vector clocks let the reader tell, among the versions it collected, which ones are obsolete and which are concurrent. Together they cover the read path, though neither makes the store linearizable. Read repair and Merkle-tree anti-entropy, covered later, reuse the same comparison to decide which replica is stale.
Exercise
Replica 1 holds a version with clock {a:2, b:1}. Replica 2 holds a version with clock {a:1, b:2, c:1}. A reader fetches both. What does compare return, what does the store return to the client, and what clock should the client's follow-up write use if it merges the values and the coordinator is node c?
Show answer
Neither clock is less than or equal to the other (a is higher in the first, b and c are higher in the second), so compare returns "concurrent". The store returns both values as siblings. The merged context is the component-wise maximum, {a:2, b:2, c:1}. Coordinator c increments its own counter, so the new version's clock is {a:2, b:2, c:2}. It dominates both siblings, so both can be discarded.
Exercise
A client does a put on an existing key without supplying a context, and the coordinator is node a. The key currently has the single version {a:3}. What happens, and why?
Show answer
The coordinator starts from an empty clock and increments its own counter, producing {a:1}. Compared with {a:3}, the new clock is "before", so add_version treats the write as obsolete and drops it. If the coordinator were a different node, for example b, the new clock {b:1} would be concurrent with {a:3} and the store would keep both as siblings. In both cases the blind write fails to replace the existing version, which is why clients should read before they write.