Clocks and event ordering
Machine clocks drift and jump, so timestamps can't order events across nodes; use logical clocks for causality (Lamport, vector) or hybrid clocks that also stay close to wall time.
Analogy: Two friends' watches disagree by a minute, so the times on their texts can't say who wrote first. But if Bea's text replies to Ana's, Ana's came first, whatever the watches say.
How it works
- Wall clocks drift and NTP can step them backwards: never order cross-node events by
now(). - A Lamport clock is a counter: if a caused b, L(a) < L(b), but a smaller value proves nothing.
- Vector clocks keep one counter per node, so they detect concurrent writes, at one entry per writer.
- HLC is wall time plus a logical counter: causal like Lamport, close to real time, 64 bits.
- TrueTime exposes clock uncertainty (~1–7 ms in 2012); Spanner waits it out before a commit is visible.
Check yourself
Answer to mark it learned; your answers aren't scored.
A multi-region store resolves conflicts with last-write-wins on wall-clock timestamps. Users say some profile edits revert in the database itself, not in a cache. Metrics show one region's clocks running 2 s fast. What's the cause and the fix?
Go deeper
Full explanation
A machine's wall clock is a quartz crystal corrected by NTP. It drifts, and NTP can step it forwards or backwards, so now() on two nodes disagrees by about a millisecond on a LAN and tens of milliseconds over the internet. Never order cross-node events by wall time, and measure timeouts with a monotonic clock.
What you usually need is causal order: if a could have influenced b (same process, or through a message), a happened before b.
- Lamport clock: a counter. Increment on each event, attach it to messages, and on receipt jump to
max(local, received) + 1. If a → b then L(a) < L(b), but not the reverse: it can't detect concurrency. - Vector clock: one counter per node, compared element-wise. If neither dominates, the writes are concurrent, a real conflict. Dynamo used them; the cost is one entry per writer.
- Hybrid logical clock (HLC): wall time plus a logical counter. Causal like Lamport, close to real time, fits in 64 bits. CockroachDB uses it.
- TrueTime (Spanner): GPS and atomic clocks expose the uncertainty ε, and commits wait it out.
Code A hybrid logical clock in 25 lines
import time
class HLC:
"""Hybrid logical clock (Kulkarni et al., 2014). Timestamps are (l, c) tuples."""
def __init__(self):
self.l, self.c = 0, 0 # l: max wall time seen, c: logical counter
def _pt(self) -> int:
return time.time_ns() // 1_000_000 # physical time in ms (may drift or step)
def now(self) -> tuple[int, int]: # local or send event
old = self.l
self.l = max(old, self._pt())
self.c = self.c + 1 if self.l == old else 0
return (self.l, self.c)
def update(self, ml: int, mc: int) -> tuple[int, int]: # receive event
old = self.l
self.l = max(old, ml, self._pt()) # never go behind anything we've seen
if self.l == old == ml:
self.c = max(self.c, mc) + 1
elif self.l == old:
self.c += 1
elif self.l == ml:
self.c = mc + 1
else:
self.c = 0 # our wall clock moved ahead: reset
return (self.l, self.c)
# Tuples compare lexicographically: (1080, 0) < (1080, 1) < (1081, 0)Real example
A profile service stores display_name in a multi-region database with last-write-wins by wall-clock timestamp. NTP breaks in the EU region and its clocks run 2 s fast. A user renames themselves through EU, then a second later fixes a typo through US. The US write carries an earlier timestamp, so every replica silently keeps the typo. With HLC timestamps, the US node reads the EU version first, its clock jumps past that stamp, and the fix wins. Also alert on clock offset.
Trade-offs +3 · −3
+ You gain
- Logical clocks order causally related events correctly with no clock sync at all.
- Vector clocks detect truly concurrent writes, so you can merge them instead of silently dropping one.
- HLC timestamps stay near wall time: readable, usable for snapshots and TTLs, and 64 bits.
− You pay
- Lamport clocks can't tell concurrent events from ordered ones.
- Vector clocks grow with the number of writers and need pruning.
- HLC and TrueTime still rely on a bounded skew; break the bound and the guarantees go.
Use it when
Multi-writer or multi-region data, conflict detection, causal messaging, MVCC snapshots, and any time you are tempted to sort events from different machines by timestamp.
Avoid it when
When one leader or one database already sequences every write (a Raft log index, a Postgres sequence): use that order instead of building clocks.
Numbers to know 4
- NTP accuracy: ~1 ms or better on a LAN, tens of ms over the public internet.
- Spanner (2012): TrueTime ε is a ~1–7 ms sawtooth, ~4 ms most of the time; assumed drift 200 µs/s.
- 200 µs/s of drift = 6 ms after 30 s, ~17 s after a day without sync.
- CockroachDB max clock offset defaults to 500 ms; a node 80% of that off from half the cluster shuts down (docs, Nov 2026).
Common pitfalls 3
- Measuring timeouts or durations with wall time: an NTP step makes them negative or huge. Use a monotonic clock.
- Last-write-wins on wall-clock timestamps: one fast clock silently discards newer writes.
- Treating a lower Lamport timestamp as proof that an event happened first.
Interview questions 2
Answer out loud first, then reveal.
Why not order events across services by timestamp?Show answer
Because each clock drifts and NTP corrects it in steps, so nodes disagree by milliseconds or more, enough to invert writes that are causally related. Last-write-wins on wall time then silently drops data. If one service owns the data, I let its log or sequence define the order. Across nodes I use a logical clock: Lamport for a total order consistent with causality, vector clocks to detect conflicts, or HLC to stay close to real time.
How does Spanner get external consistency from physical clocks?Show answer
TrueTime returns an interval, not a point, with ε around 1–7 ms in the 2012 paper, backed by GPS and atomic clocks. A commit takes the interval's latest bound as its timestamp, then waits until that time has surely passed everywhere before making it visible. Any transaction that starts later gets a larger timestamp. The wait overlaps Paxos replication. Without that hardware, CockroachDB uses HLC plus a max-offset bound and restarts reads that fall in the uncertainty window.