Skip to content

Clocks, ordering and why timestamps lie

Deep diveConcept

Two servers stamp two writes, and the later one loses because a clock ran fast. Across machines, time is a guess. Here is why clocks disagree, and how Lamport clocks and version vectors order events by cause instead of by time.

01 The later write that lost

The easy way to order events across machines is to stamp each one with the time and sort. Many stores resolve conflicting writes exactly like that: keep the one with the newest timestamp, last write wins. It only works if every machine's clock agrees, and they do not.

Last write wins, judged by two clocks that disagree
Step 1 of 4
Server clocks (example times)
+5 s fastA 12:00:05
B 12:00:00
Writes received
Empty
Stored title
Empty
  • stamping a write
  • just arrived
  • discarded
  • kept

The real time is 12:00:00. Server A's clock has drifted 5 seconds fast; B's is right. Both store a document title, and the newest timestamp wins.

12:00:00 real time

Five seconds of skew is large, but the effect does not need large skew. It needs two writes closer together than the clocks' disagreement, and on a busy key, writes milliseconds apart are normal.

02 Why clocks drift, jump and repeat

Each machine counts time with a quartz oscillator, and no two run at quite the same rate. Google's Spanner paper assumes a drift of up to 200 microseconds per second, which, left alone, adds up to about 17 seconds a day. NTP corrects this by asking time servers and nudging the clock, typically to within a few milliseconds on a good network and tens of milliseconds over the internet.

  • Corrections can jump. If a clock is far off, NTP may step it, and a step can go backwards. Code that subtracts two wall-clock readings can get a negative duration.
  • Pauses freeze time for one process. A long garbage-collection pause or a paused virtual machine means a process acts on a timestamp it read seconds ago.
  • Leap seconds. A leap second has made clocks repeat a second; the one in June 2012 crashed or hung a number of Linux servers. Many providers now smear it over a day instead.
  • Nobody checks. A machine whose NTP has silently stopped working still returns a confident time.
Wall clock
const start = Date.now();
await work();
// Can be negative if NTP
// stepped the clock back.
const ms = Date.now() - start;
Monotonic clock
const start = performance.now();
await work();
// Only ever moves forward,
// so this is a real duration.
const ms = performance.now() - start;

Use a monotonic clock (performance.now() in Node and browsers, time.monotonic() in Python, System.nanoTime() in Java) for durations and timeouts. It cannot jump backwards, but it means nothing outside its own machine, so it cannot order events across machines either.

03 What order actually means

Leslie Lamport's 1978 paper made a different point: across machines, what you can know for sure is not when things happened but what could have caused what. Event a happened before event b if:

  • they ran on the same process, a first; or
  • a is sending a message and b is receiving that message; or
  • there is a chain of those from a to b.

If neither happened before the other, the two events are concurrent: no information could have travelled from one to the other, so no correct system can depend on their order. Ana's two saves were not concurrent; her second came after her first on her own device. A timestamp from the wrong clock reversed a real, causal order.

04 Lamport clocks: counters instead of time

A Lamport clock is a counter per process, with three rules. It needs no synchronised time at all.

Lamport clocks on three processes
Step 1 of 8
Lamport counter on each process
P1: 0
P2: 0
P3: 0
Events, with their Lamport time
Empty
  • process acting
  • event just stamped

Three processes, each with a counter at 0. The rules: add 1 before every event; put the counter on every message you send; on receiving, jump to the larger of your counter and the message's, then add 1.

The guarantee goes one way: if a happened before b, then a's number is smaller. Break ties by process id and you get a single total order that every process agrees on and that never puts an effect before its cause, which is what you want for ordering a replicated log.

The converse does not hold. A smaller number does not mean "happened before": c got 1 and send m1 got 2, yet they were concurrent. From Lamport numbers alone you cannot tell "one caused the other" from "these crossed". To detect conflicting writes, you need more.

05 Version vectors: spotting writes that crossed

A vector clock keeps one counter per process instead of one in total. Used to version the values in a replicated store, with one entry per replica, it is called a version vector. Comparing two vectors entry by entry gives one of three answers: one is behind or equal in every entry (it came before), the other way round, or each is ahead somewhere (concurrent).

Version vectors catch two writes that crossed
Step 1 of 9
Replica X
Empty
Replica Y
Empty
  • just written
  • compared
  • replaced
  • kept as a sibling

A shopping cart is stored on two replicas, X and Y, and either one accepts writes. Each version carries a version vector: one count per replica that has written to it. Nothing is stored yet.

This is how Amazon's Dynamo kept shopping carts: concurrent versions were kept as siblings and merged by the application. Riak does the same. The comparison itself is a few lines:

vv.py
def compare(a: dict, b: dict) -> str:
nodes = a.keys() | b.keys()
a_le_b = all(a.get(n, 0) <= b.get(n, 0) for n in nodes)
b_le_a = all(b.get(n, 0) <= a.get(n, 0) for n in nodes)
if a_le_b and b_le_a:
return "same version"
if a_le_b:
return "a came before b"
if b_le_a:
return "b came before a"
return "concurrent: keep both"
def merge(a: dict, b: dict) -> dict:
# The newest count each replica has seen, from either side.
return {n: max(a.get(n, 0), b.get(n, 0)) for n in sorted(a.keys() | b.keys())}
Text
$ python3 vv.py
start vs ana: a came before b
ana vs ben: concurrent: keep both
merged: {'X': 3, 'Y': 1}
ana vs merged: a came before b
ben vs merged: a came before b

The cost is size and work. The vector grows with the number of replicas that wrote a value, and someone has to merge siblings. A union merge is easy for a cart, but it has a known flaw: an item deleted on one side and kept on the other comes back.

06 Which clock for which job

Clocks and what they can promise
ClockGives youCannot do
Wall clock (NTP)A time humans can read, close to real timeOrder events closer together than the skew
Monotonic clockDurations and timeouts on one machineCompare anything between machines
Lamport clockOne total order that respects cause and effectTell concurrent events from causal ones
Version vectorDetect concurrent writes to the same valueStay small with many writers; merge for you
Hybrid logical clockLamport's guarantee in a timestamp close to real timeRemove skew; it only stops skew breaking causality
TrueTime (Spanner)A time interval guaranteed to hold the real timeRun without GPS and atomic clocks in the data centre

Hybrid logical clocks (Kulkarni and others, 2014) pair a physical time with a small counter: take the larger of your clock and any timestamp you receive, and count up when the physical part does not move. CockroachDB uses them. Google's TrueTime goes the other way: it reports how uncertain the time is, typically a few milliseconds, and Spanner waits out that uncertainty before it commits, so timestamp order matches real order.

07 When timestamps bite

ORDER BY created_atSorting events from many machinesRows written on different servers within the skew can come back in the wrong order. If order matters, take a sequence number from one place, or use a logical clock.
span.start < parent.startChild spans that start before their parentIn tracing, each service stamps its spans with its own clock, so a child can appear to start before the call that made it. Tracing UIs often have a clock-skew adjustment; it guesses, using the fact that a call encloses its child.
UPDATE … USING TIMESTAMPLast write wins by defaultStores such as Cassandra resolve conflicts per column by timestamp. Writes from a server with a fast clock win, and a write within the skew of another is lost without an error.
if (Date.now() > expiresAt)Leases and locks on wall timeA lock that expires by one machine's clock and is checked by another's can be held by two holders at once. Use a monotonic clock locally, and fencing tokens across machines.
{A:1,B:4,C:2,…}Vectors that keep growingOne entry per writer means vectors grow with every client that writes. Keep entries per replica, not per client, and prune with care: pruning can turn a causal order into a false conflict.

08 Check yourself

Question

Two servers' clocks are 50 ms apart. A store resolves conflicts by last write wins. When can it drop the write that really came last?

Question

Event x has Lamport time 3 and event y has Lamport time 7. What do you know?

Question

Version {X:2, Y:1} meets version {X:1, Y:3}. What should the store do?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?