SysDesignAtlas

Time, Clocks & Ordering

Why wall-clock timestamps lie, Lamport and vector clocks, hybrid logical clocks, and how TrueTime buys strong consistency by waiting out uncertainty.

HLDHard9 min readclocksorderingcausalityvector-clocks
Confidence

#Why you can't trust a timestamp

Ordering events by wall-clock time seems obvious and is quietly wrong.

Clock skew — two servers simply disagree about what time it is. Machines correct themselves against time servers over the network (NTP, the Network Time Protocol), which typically holds them within a few milliseconds of each other on a good network, and tens to hundreds of milliseconds on a bad one. That's an eternity — thousands of operations can occur inside the uncertainty window.

Clocks jump. NTP corrections can step the clock backwards. A VM migration or a leap second adjustment can make the clock suddenly jump forwards or backwards. Code that assumes time only ever moves forwards breaks in ways that are extremely hard to debug.

The consequence — last-write-wins silently loses data:

   Server A (clock 3ms fast)  Server B (correct clock)
   t=10.003  write X=1        t=10.001  write X=2
             (real: 10.000)             (real: 10.001)

   B's write really happened LAST, but A's timestamp is higher.
   Last-write-wins keeps X=1. B's write is silently discarded.

No error, no conflict, no log line. The data is just gone. This is the single most important practical consequence of clock skew, and naming it is a strong signal.

#Happens-before

Since physical time is unreliable, stop asking "when did this happen?" and ask "could this one have caused that one?" That's ordering by cause rather than by clock. Event A happens-before B (written A → B) if:

  1. A and B are in the same process and A came first, or
  2. A is sending a message and B is receiving it, or
  3. Transitively: A → C and C → B.

If neither A → B nor B → A, they are concurrent — genuinely unordered, and no amount of clock precision changes that. Concurrency is the interesting case, because it's exactly where conflicts live.

#Lamport clocks

A counter per process, with one rule for messages:

   Local event:      counter++
   Sending msg:      counter++, attach counter
   Receiving msg:    counter = max(counter, received) + 1

Guarantee: if A → B then L(A) < L(B).

The crucial limitation: it only works in one direction. If A caused B, A's number is smaller — but a smaller number does not prove causation. The two events may have been entirely unrelated and simply counted differently. So a Lamport clock can put everything in an order that never contradicts cause and effect, but it cannot tell you which pairs were genuinely simultaneous — which is exactly where conflicts hide.

Useful when every node needs to sort events into the same order without talking to each other — for example, to decide which of two writes wins, identically on every replica. Equal counters are broken by appending the process ID, so (5, node-A) comes before (5, node-B). Not useful for conflict detection.

#Vector clocks

One counter per node, carried as a vector.

   3 nodes, each tracks [A, B, C]

   A does work:      [1,0,0]
   A → B (message):  B updates to [1,1,0]
   B does work:      [1,2,0]
   C does work:      [0,0,1]     ← independent

   COMPARING [1,2,0] and [0,0,1]:
     1 > 0 but 0 < 1  → neither dominates → CONCURRENT ✓

Comparison rule: V1 → V2 if every element of V1 ≤ the corresponding element of V2 and at least one is strictly less. If neither dominates, the events are concurrent — a genuine conflict that the application (or a CRDT) must resolve.

This is what lets Dynamo-style stores return siblings — both conflicting versions, handed back to the application to merge — instead of silently picking a winner. The vector clock proves the two versions are concurrent rather than one overwriting the other.

Cost: the vector grows with the number of nodes that have ever written. In a system with many clients this becomes unwieldy — a million clients means a million-entry vector. Systems then prune old entries, but a pruned vector has lost information, so two versions that really were sequential can wrongly look concurrent. Version vectors — one entry per replica rather than per client — are the practical variant, because the number of replicas is small and fixed.

#Hybrid Logical Clocks (HLC)

The pragmatic modern answer, and worth naming because it's what many current systems use (CockroachDB, YugabyteDB, MongoDB).

An HLC timestamp is a pair: (physical_time, logical_counter).

   On event / send:
     pt = max(local_physical, last_pt)
     if pt == last_pt: counter++       else: counter = 0

   On receive(m_pt, m_counter):
     pt = max(local_physical, last_pt, m_pt)
     counter = appropriate max + 1 when times tie

What you get: timestamps that are close to physical time (so they're human-meaningful and usable for time-range queries), while still guaranteeing that causally related events are ordered correctly even when clocks skew. It captures causality like a Lamport clock, stays bounded in size (unlike vector clocks), and doesn't require special hardware (unlike TrueTime).

That combination — bounded size, causal correctness, physical meaning — is why HLC has become the default choice for new distributed databases.

#TrueTime and commit-wait

Spanner's approach: instead of pretending clocks are exact, make the uncertainty explicit and wait it out.

GPS receivers and atomic clocks in every datacenter keep skew tightly bounded. The API returns an interval, not a point:

   TT.now() → [earliest, latest]     typically ~1-7ms wide

   COMMIT WAIT:
     assign the transaction timestamp T = TT.now().latest
     then WAIT until TT.now().earliest > T
     only then release locks and acknowledge

By waiting out the uncertainty window, Spanner guarantees that when a transaction commits, its timestamp is definitely in the past everywhere. That makes timestamps from different machines safely comparable. The result is external consistency (also called strict serializability): if transaction T1 finishes before T2 starts — even on another continent — T2 is guaranteed a later timestamp and sees T1's effects. A bonus: you can read a consistent snapshot of the whole database "as of" any past timestamp without taking locks, because every commit's timestamp is trustworthy.

The cost is explicit: every read-write transaction pays a few milliseconds of deliberate waiting. Spanner trades latency for the strongest consistency guarantee available — a clean PACELC "PC/EC" system: it picks consistency both during a partition (PC) and in normal operation (EC), paying with availability and latency respectively.

The insight worth stating: you cannot eliminate clock uncertainty, but you can measure it and wait for it to pass. That's a fundamentally different strategy from pretending it doesn't exist.

#Choosing

NeedUse
Display a timestamp to a humanWall clock (accept it's approximate)
Measure a duration or timeoutMonotonic clock
Deterministic total order, no conflict detectionLamport clock
Detect concurrent writes / conflictsVector clocks (version vectors)
Causal ordering with physical meaning, bounded sizeHLC
Externally consistent transactions across regionsTrueTime-style bounded clocks + commit-wait
Ordering within one partitionA sequence number — simplest thing that works

#The condensed version

When a design involves multiple writers to the same data:

"I'm not going to order these by wall-clock timestamp — clock skew between servers is typically several milliseconds and can be much worse, and NTP can step a clock backwards, so last-write-wins would silently discard the write that actually happened last. For conflict detection I'd use version vectors so I can tell concurrent writes apart from sequential ones. For ordering with physical meaning I'd use hybrid logical clocks. And where I control the write path, the simplest correct answer is a per-entity sequence number from a single ordering point."

That answer identifies the failure, quantifies it, and gives three graded solutions ending with the simplest one — which is the shape of a strong response to nearly any distributed systems question.

#Check yourself

How does clock skew make last-write-wins silently lose data?Show answer
If server A's clock runs ahead, its earlier write gets a later timestamp than B's genuinely later write, so LWW keeps A's and discards B's — with no error anywhere.
Wall clock versus monotonic clock: what is each for?Show answer
Wall clock: absolute time for display, and it can jump backwards. Monotonic clock: always increases, for measuring durations, timeouts and rate limits. A duration measured on the wall clock can come out negative.
When are two events concurrent in the happens-before sense?Show answer
When neither could have caused the other — not in the same process in order, not linked by a message, and not transitively connected. That's exactly where conflicts live.
What can and can't a Lamport clock tell you?Show answer
If A caused B, then L(A) < L(B). But a smaller number doesn't prove causation, so it can't detect concurrent events — fine for a deterministic tiebreak, useless for conflict detection.
How do vector clocks detect concurrent writes?Show answer
One counter per node. V1 precedes V2 if every entry is ≤ and at least one is <. If neither vector dominates — say [1,2,0] and [0,0,1] — the events are concurrent and the store returns both as siblings.
Why have hybrid logical clocks become the default in new databases?Show answer
An HLC is (physical time, logical counter): close to real time so it's meaningful, causally correct despite skew, bounded in size unlike vector clocks, and needs no special hardware.
How does Spanner's commit-wait give external consistency?Show answer
TrueTime returns an uncertainty interval. A transaction takes the interval's latest time as its timestamp, then waits until even the earliest bound has passed it before acknowledging, so its timestamp is in the past everywhere.
What's the simplest correct way to order writes to one entity?Show answer
A sequence number from a single ordering point — one partition or one owner for that entity.

#What to carry forward

  • Wall-clock timestamps lie: skew and backward jumps make last-write-wins silently lose data.
  • Measure durations with a monotonic clock, never the wall clock.
  • Lamport clocks give a consistent order; vector clocks detect concurrency; HLCs give causal order with physical meaning.
  • TrueTime makes uncertainty explicit and waits it out — paying milliseconds per commit for external consistency.
  • When you control the write path, a per-entity sequence number is the simplest correct order.
00:00
/ 9m