Skip to content
Optimal Lab

System design · interactive

Clocks and ordering

Three servers exchange messages. Which events happened before which? Machine clocks drift, so their timestamps can contradict cause and effect. Logical clocks track causality instead of time.

P1P2P3a100msb110msc105msd120mse130msf75msg100msh150ms

Left to right is real time. Arrows are messages.

sorted by wall clock: f a g c b d e h

P3's clock runs 40 ms slow, so by wall time g (100 ms) happened before e (130 ms), even though g is receiving e's message. Timestamps from different machines can't order events.

Timestamps

Step 1 of 4

  1. 1

    Physical clocks drift

    NTP keeps them within milliseconds, not exactly. Last-write-wins with wall clocks can silently drop the newer write.

    Spanner uses GPS and atomic clocks plus waiting out the uncertainty.

  2. 2

    Lamport clocks

    If A caused B, A's number is smaller. A single counter gives a total order everyone agrees on, but can't tell causal from coincidental.

    on receive: t = max(t, msg.t) + 1

  3. 3

    Vector clocks

    One counter per node. Compare slot by slot: all ≤ means happened-before; mixed means concurrent, so you have a real conflict.

    Dynamo-style stores use them to spot conflicting writes.

  4. 4

    Hybrid logical clocks

    Wall time plus a logical counter: close to real time, but never violating causality. CockroachDB and MongoDB use them.

    Ordering is a design decision.

In production

Tools and technologies

Distributed databases choose a clock to order events.

Not tied to one language — use these names when you search docs or design a system.