AlgoViz

Unique IDs with causality

hard 30 min

Number 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

Server A0Server B0Server C0

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

PostReplyOrder
Wall clock1,0401,010wrong

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

    major

    Concurrent events also have numbers.

    Wrong
    if L(a) < L(b): a_caused_b()
    Right
    if vector(a) <= vector(b): a_before_b()
  • Forgetting to pass it on

    critical

    One service without the timestamp breaks every chain through it.

    Wrong
    http.post(url, body)
    Right
    http.post(url, body, headers={"X-Clock": clock.tick()})
  • Trusting any timestamp

    critical

    One wrong clock pulls all others ahead.

    Wrong
    l = max(l, m.l, pt)
    Right
    if m.l - pt > MAX_AHEAD: refuse()l = max(l, m.l, pt)
  • A vector entry per user

    major

    The vector becomes larger than the data.

    Wrong
    V[user_id] += 1
    Right
    V[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?