Sub topic 9
Ordering events: happens-before and vector clocks
Replicas accept writes independently, so a system needs a way to say which write came first. This chapter covers what "first" can mean when machines have no shared clock. It also covers how Lamport clocks and vector clocks track it, and how a store uses them to find concurrent writes.
This chapter assumes you know the earlier material on replication and consistency models as contracts on histories. You should also be able to read short Python functions.
Why wall clocks are not enough
Each machine has its own physical clock. Clocks drift, get corrected by NTP (the Network Time Protocol), and can jump backward. Two servers that stamp events with 10:00:00.003 and 10:00:00.001 may have recorded them in the opposite real order.
Many ordering questions do not need real time anyway. A reply to a message must come after the message. Two unrelated writes on different continents have no meaningful order. What matters is whether one event could have influenced the other.
The happens-before relation
Leslie Lamport defined the happens-before relation, written a → b. It is the smallest relation that satisfies three rules:
- If
aandboccur on the same process andaoccurs first, thena → b. - If
ais the sending of a message andbis its receipt, thena → b. - If
a → bandb → c, thena → c. The relation is transitive.
If neither a → b nor b → a holds, the events are concurrent, written a ∥ b. Concurrent does not mean simultaneous. It means no chain of messages connects them, so neither could have affected the other.
The relation is a partial order. Some pairs are ordered and some are not. Causal consistency, covered in the next chapter, is defined in terms of this relation.
In the diagram, A's write of x happens before B's write of y, because a message path connects them. C's write of z is concurrent with both.
Lamport clocks
A Lamport clock is a single integer counter per process. It gives each event a number that respects happens-before.
- Before each local event, increment the counter.
- When sending a message, attach the current counter value.
- When receiving a message, set the counter to
max(local, received) + 1.
class LamportClock:
def __init__(self):
self.time = 0
def tick(self):
"""Record a local event."""
self.time += 1
return self.time
def send(self):
"""Record a send event and return the timestamp to attach."""
return self.tick()
def receive(self, remote_time):
"""Record a receive event given the sender's timestamp."""
self.time = max(self.time, remote_time) + 1
return self.time
p1, p2 = LamportClock(), LamportClock()
sent = p1.send() # 1
got = p2.receive(sent) # 2
print(sent < got) # True: send happened before receive
# Concurrent events on different processes
p3, p4 = LamportClock(), LamportClock()
e1 = p3.tick() # 1
e2 = p3.tick() # 2
f1 = p4.tick() # 1
f2 = p4.tick() # 2
f3 = p4.tick() # 3
print(e2 < f3) # True, yet e2 and f3 are concurrentThe guarantee runs one way only. If a → b, then L(a) < L(b). The reverse is false. The last line of the example shows L(e2) < L(f3) even though no message connects the two events. A Lamport timestamp cannot tell you whether two events are concurrent.
Lamport clocks are still useful. If you break ties with a process ID, you get a total order that agrees with causality. Systems use this to order requests in a replicated log. The total order is arbitrary for concurrent events, though, so it hides conflicts instead of detecting them.
Vector clocks
A vector clock fixes this limitation. Each process keeps one counter per process, stored here as a dictionary from node name to integer. The rules mirror Lamport's:
- On a local event or a send, increment your own entry.
- On a receive, take the element-wise maximum of your clock and the received clock, then increment your own entry.
def increment(clock, node):
new = dict(clock)
new[node] = new.get(node, 0) + 1
return new
def merge(a, b):
return {k: max(a.get(k, 0), b.get(k, 0)) for k in set(a) | set(b)}
def receive(local, remote, node):
return increment(merge(local, remote), node)
def compare(a, b):
"""Compare two vector clocks given as dicts of node -> counter."""
keys = set(a) | set(b)
le = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
ge = all(a.get(k, 0) >= b.get(k, 0) for k in keys)
if le and ge:
return "equal"
if le:
return "before"
if ge:
return "after"
return "concurrent"
a1 = increment({}, "A") # A writes: {"A": 1}
b1 = receive({}, a1, "B") # B reads A's write, then writes: {"A": 1, "B": 1}
c1 = increment({}, "C") # C writes alone: {"C": 1}
print(compare(a1, b1)) # before
print(compare(b1, c1)) # concurrent
print(compare(c1, c1)) # equalMissing entries count as zero, so {"A": 1} and {"A": 1, "B": 0} compare as equal.
The comparison rule is: clock a is before clock b when every counter in a is less than or equal to the matching counter in b, and at least one is strictly less. If each clock has some counter larger than the other's, the events are concurrent. Unlike Lamport clocks, vector clocks give both directions: a → b exactly when V(a) < V(b).
| Property | Lamport clock | Vector clock |
|---|---|---|
| Size per timestamp | One integer | One integer per process |
| `a → b` implies smaller timestamp | Yes | Yes |
| Smaller timestamp implies `a → b` | No | Yes |
| Can detect concurrency | No | Yes |
| Gives a total order | Yes, with tie-breaking | No, partial order only |
Using vector clocks to detect conflicting writes
Dynamo-style stores attach a vector clock to every value. When a client writes, it sends back the clock of the version it read. The replica increments its own entry and stores the result.
When a replica holds two versions of the same key, it compares their clocks:
- If one is
beforethe other, the older version is obsolete. The replica discards it. - If they are
concurrent, neither write saw the other. The replica keeps both as siblings and returns them on the next read. The application, or a rule such as a CRDT merge, must resolve them. The conflict resolution chapter covers those rules.
This is the main practical use of vector clocks. They turn silently lost updates into visible conflicts.
Costs and failure modes
- Size grows with the number of writers. Each client or server that ever coordinates a write can add an entry. Systems cap the size by pruning the oldest entries, which can make old and new versions look concurrent when they are not. This costs extra siblings but does not lose data.
- Node identity matters. If a node restarts and loses its counter, it can reuse a value and produce a clock that falsely looks equal or older. Persist the counter, or give each restart a new identifier.
- Vector clocks detect conflicts but do not resolve them. Something else must choose a winner or merge the siblings.
- They track causality the system can see. If two clients communicate outside the database, such as by phone, the store cannot know that one write depended on the other. It will report those writes as concurrent.
- Version vectors versus vector clocks. Many stores track one entry per replica and per key, which is technically a version vector. It counts updates to a data item, not every event in a process. The comparison logic is the same.
Exercise
Exercise
Three replicas hold these versions of one key: V1 = {"A": 2, "B": 1}, V2 = {"A": 2, "B": 3}, V3 = {"A": 3, "B": 1}. Which pairs are ordered, which are concurrent, and which versions would a replica keep after comparing them all?
Show answer
V1 is before V2, because A is 2 and 2 and B is 1 and 3, so every counter is less than or equal and one is strictly less. V1 is also before V3, because A is 2 and 3 and B is 1 and 1. V2 and V3 are concurrent: V2 has the larger B counter (3 against 1) and V3 has the larger A counter (3 against 2). The replica discards V1 as obsolete and keeps V2 and V3 as siblings for later resolution.
Exercise
A Lamport clock assigns timestamp 4 to event X and timestamp 7 to event Y. Can you conclude that X happened before Y? What would you need to know?
Show answer
No. Lamport timestamps only guarantee that if X happened before Y, then 4 < 7. The reverse does not hold, so X and Y may be concurrent. To decide, you need vector clocks for both events, or knowledge of a message path from X to Y.