Clocks, ordering and why timestamps lie
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.
- 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.
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.
const start = Date.now();await work();// Can be negative if NTP// stepped the clock back.const ms = Date.now() - start;
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,
afirst; or ais sending a message andbis receiving that message; or- there is a chain of those from
atob.
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.
- 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).
- 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:
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
| Clock | Gives you | Cannot do |
|---|---|---|
| Wall clock (NTP) | A time humans can read, close to real time | Order events closer together than the skew |
| Monotonic clock | Durations and timeouts on one machine | Compare anything between machines |
| Lamport clock | One total order that respects cause and effect | Tell concurrent events from causal ones |
| Version vector | Detect concurrent writes to the same value | Stay small with many writers; merge for you |
| Hybrid logical clock | Lamport's guarantee in a timestamp close to real time | Remove skew; it only stops skew breaking causality |
| TrueTime (Spanner) | A time interval guaranteed to hold the real time | Run 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.