Unique IDs with causality
hard 30 minNumber events so that a cause always comes before its effect, even when clocks disagree.
See it run
Number events on three servers, and see which clock can tell cause, order and conflict.
Operations
Lamport clock
One counter for each server.
Step 1 of 8
Start
events
Three servers, all counters at 0.
Step 1: Start
def tick(): n = n + 1 return ndef receive(m): n = max(n, m) + 1 return n- Size
- One number
- Can tell
- Cause before effect
Receive: the larger one, plus one.
In the real world
The same unique ids with causality doing real jobs. Pick one and step through it.
The same two events with three kinds of number.
Step 1 of 3
Wall clock
| Post | Reply | Order | |
|---|---|---|---|
| Wall clock | 1,040 | 1,010 | wrong |
The post has time 1,040 and the reply 1,010. Sorted, the reply is first.
Step 1: Wall clock
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A smaller number as a cause
majorConcurrent events also have numbers.
Wrongif L(a) < L(b): a_caused_b()Rightif vector(a) <= vector(b): a_before_b()Forgetting to pass it on
criticalOne service without the timestamp breaks every chain through it.
Wronghttp.post(url, body)Righthttp.post(url, body, headers={"X-Clock": clock.tick()})Trusting any timestamp
criticalOne wrong clock pulls all others ahead.
Wrongl = max(l, m.l, pt)Rightif m.l - pt > MAX_AHEAD: refuse()l = max(l, m.l, pt)A vector entry per user
majorThe vector becomes larger than the data.
WrongV[user_id] += 1RightV[replica_id] += 1
Interview tips
Explain it in one line
- Number events by what was seen, not by the clock on the wall.
CLOCK
- Causality, Logical time, Ordering.
- Concurrency, Knowledge of what was seen.
Good rules
- Receive: max + 1.
- Vectors: each larger somewhere means conflict.
- Hybrid: refuse times too far ahead.
Expect these questions
- Does a smaller number prove a cause?
- Why not vectors everywhere?
- Would a sequence do?