AlgoViz

Unique IDs with causality

hard 30 min

Number events so that a cause always comes before its effect, even when clocks disagree.

Video lesson · Chapter 1 of 5

A number on a letter travels between servers

0:00 / 4:22

Happened before, in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 1 min.

What it is

Causality is the relation between a cause and its effect. A reply is caused by its question. An edit is caused by the version it changes. An ID with causality carries enough information that the effect never sorts before the cause.

Ordinary timestamps cannot promise that, because every computer has its own clock. Logical clocks count events and messages instead of seconds.

In one line: track how events relate, not what the wall clock said.

Why it exists

Time-ordered IDs are nearly sorted. When one clock is ahead, a reply can get a smaller ID than the message it answers.

Sometimes order is not enough. If two people changed the same thing without knowing of each other, we want to know that both happened, so that neither change is lost.

A short history

  1. 1978

    Leslie Lamport's paper on time, clocks and the ordering of events defines happened-before and a simple counter that respects it.

  2. 1988

    Colin Fidge and Friedemann Mattern independently describe vector clocks.

  3. 2007

    Amazon's Dynamo paper describes a store that uses vector clocks to find conflicting versions of an object.

  4. 2014

    A technical report of the University at Buffalo introduces hybrid logical clocks, which combine clock time with a small counter.

Words to know

Happened before
Written a → b: a could have influenced b.
Concurrent
Neither happened before the other.
Clock skew
The difference between two clocks at one moment.
Lamport clock
One counter for each process: larger than everything it has seen.
Vector clock
One counter for every process, kept by each of them.
Hybrid logical clock
Clock time plus a small counter that keeps causes in order.
Total order
Every two events have an order, sometimes an arbitrary one.
Partial order
Only related events have an order.

How it works

Step through the idea, or press Play.

Step 1 of 3

Count. Each event raises a counter

Understand it

Start here

Chess by post

Letters that say what they have seen
AshaLee1: e4

The date on the letter was never needed, only what the writer had seen.

What we want to know

  • Cause and effect

    An effect never sorts before its cause.

  • Independence

    Which events did not know of each other?

  • No common clock

    It works with clocks that disagree.

  • Only what matters

    Related events are ordered, others may be in any order.

Problem

Why wall clocks fail

One clock is half a second behind

ServerIts clock saysEventReally
A10:00:01.000X: the questionfirst
B, behind10:00:00.600Y: the answer to X0.1 s later
Sorted by clock, the answer comes before the question. With a counter, X carries 5; B has 3 and continues at max(3, 5) + 1 = 6.

Definition

Happened before

Three rules

  1. 1

    Same process

    If a comes before b in one process, then a → b.

  2. 2

    Message

    If a is the sending and b the receiving of one message, then a → b.

  3. 3

    Chain

    If a → b and b → c, then a → c.

If neither a → b nor b → a, they are concurrent. That does not mean at the same moment. It means neither could have known of the other.

Who could have influenced whom?

C1 is concurrent with A1, A2, B3 and B4. It happened before C5, which is in the same process.

One number

Lamport clocks

Three rules for one counter L

EventRule
Something happens hereL = L + 1
SendL = L + 1, put L in the message
Receive mL = max(L, m) + 1

The promise, and what it is not

a→b;⇒;L(a)<L(b)butL(a)<L(b);⇏;a→ba \to b ;\Rightarrow; L(a) < L(b) \qquad\text{but}\qquad L(a) < L(b) ;\not\Rightarrow; a \to b
In the picture above C1 has number 1 and A2 has number 2, and they are concurrent.

Three processes

Add the process name to break ties, and the pairs (number, name) give one total order that everybody agrees on. That is enough for mutual exclusion, for replicated state machines and for queues. Reading a real time from it is impossible.

Many numbers

Vector clocks

Rules for a vector V with one counter for each process

EventRule
Something happens hereV[me] = V[me] + 1
SendV[me] = V[me] + 1, send the whole vector
Receive WTake the larger of each pair, then V[me] = V[me] + 1

Comparing

XYAnswerWhy
[2, 1, 0][2, 2, 0]X before YEvery number of X is at most that of Y, one is smaller
[2, 0, 1][1, 2, 0]ConcurrentX is larger in one place, Y in another
[2, 2, 0][2, 1, 0]Y before XThe first rule, the other way round
[1, 1, 0][1, 1, 0]The sameAll equal
Session guarantees and merging conflicts are in consistency models; versions of stored objects are in data versioning.

Good

  • Finds concurrent events
  • Full cause and effect
  • The answer is exact

Not so good

  • One counter for each writer, in every event
  • Every message carries it
  • Writers come and go, so old entries must be removed
  • Not a sortable number

What it costs

1,000 writers×8 B=8 KB in every message5 replicas×8 B=40 B1{,}000\ \text{writers} \times 8\ \text{B} = 8\,\text{KB in every message} \qquad 5\ \text{replicas} \times 8\ \text{B} = 40\,\text{B}
So stores count per replica, not per client.

Both

Hybrid logical clocks

A hybrid logical clock (HLC) is a pair: l, the largest clock time seen so far, and c, a counter for events with the same l. It follows the real clock when it can, and the counter when it must.

An HLC timestamp as an ID

PartBitsJob
l: time48Milliseconds; sorts by real time
c: counter16Keeps cause before effect inside one l
NodevariesBreaks ties, makes the ID unique
Python
def local_or_send():    old = l    l = max(l, pt)    c = c + 1 if l == old else 0def receive(msg):    old = l    l = max(old, msg.l, pt)    if l == old == msg.l: c = max(c, msg.c) + 1    elif l == old:        c = c + 1    elif l == msg.l:      c = msg.c + 1    else:                 c = 0
The two rules. pt is the physical time of this machine, msg is the timestamp in the message.

Order and bound

e→f⇒(le,ce)<(lf,cf)0≤le−pte≤εe \to f \Rightarrow (l_e, c_e) < (l_f, c_f) \qquad 0 \le l_e - pt_e \le \varepsilon
ε is the largest difference between two clocks. l is never behind the own clock, and at most ε ahead of it.

Receiving a message

Without the first check one machine with a clock in next year would pull everyone's time there. A full counter must wait for the next millisecond.

Architecture

Passing the clock along

The timestamp travels with every message

A web app calls the post service and the reply service. Each service has its own hybrid clock. The post service writes the post to PostgreSQL and publishes an event to Kafka with its timestamp. The reply service reads the event, moves its clock forward and writes the reply with a larger timestamp to its own PostgreSQL.
Put it in the request header, in the event and in the answer. One place that forgets it breaks the chain.

Compare

Which clock?

Wall clockLamportVectorHybrid
Size8 bytes8 bytes8 bytes per writer8 bytes, plus node
Cause before effectNoYesYesYes
Finds concurrencyNoNoYesNo
Near real timeYesNoNoYes
Many nodesYesYesNoYes
DifficultyNoneSimpleMediumMedium

Choosing

Simpler

Often a sequence is enough

All messages of one chat can go through one leader or one partition. It numbers them 1, 2, 3. Cause before effect follows at once, the numbers have no gaps a reader must worry about, and a client can ask for everything after 41. You need logical clocks when no single place sees all related events.

How databases order transactions

SystemWayCost
CockroachDBHybrid logical clocks; default maximum offset 500 msUncertain reads may have to restart
YugabyteDBHybrid logical clocksSimilar
TiDBOne timestamp oracleA call to it for timestamps
SpannerTrueTime: special clocks with a known errorHardware, and waiting out the error
The first two accept clock error, the third avoids many clocks, the fourth measures the error.

Care

Using them safely

Do

  • Use a hybrid clock for sortable IDs across services
  • Lock the counter, or use one atomic value
  • Add the node to every ID
  • Watch clock offset and refuse absurd times
  • Test with clocks that are wrong on purpose

Do not

  • Read a smaller Lamport number as a cause
  • Use vectors with thousands of writers
  • Ignore a full counter
  • Mix clock types in one column
  • Trust wall clocks alone for last writer wins

Summary

The whole topic in one minute.

Happened-before has three rules: order inside one process, send before receive, and chains of both. A Lamport clock gives every effect a larger number than its cause. A vector clock also says when two events were concurrent, and grows with the number of writers. A hybrid clock keeps causes in order and stays near real time.

For IDs, use a hybrid clock plus a node number. For conflicts, use vectors with few writers. For a chat, one sequence for each conversation is often simpler than all of them.

  • Happened before: same process, message, chain. Everything else is concurrent.
  • Receive rule: take the larger, add one.
  • Lamport gives order, vector also finds concurrency, hybrid gives order near real time.
  • A smaller number does not prove a cause.
  • The chain must be unbroken: carry the timestamp in every message.

Sources