Clocks & Ordering
Why physical clocks can't order events across machines, NTP and clock skew, the happened-before relation, Lamport clocks, vector clocks, hybrid logical clocks, and TrueTime.
"Which happened first?" is easy on one machine and surprisingly hard across many. Ordering events matters for conflict resolution (which write wins?), causality (show the question before the answer), snapshots, and debugging.
Physical clocks are unreliable
Each machine's quartz oscillator drifts (typically 10–200 parts per million: up to ~17 seconds per day). NTP synchronises clocks over the network, but:
- Accuracy over the internet is typically milliseconds; within a data centre, maybe sub-millisecond — never perfect.
- Corrections can make a clock jump backwards.
- VM pauses, leap seconds and misconfigured servers cause larger errors.
Consequence: if node A records a write at 10:00:00.005 and node B records one at 10:00:00.003, B's write may still have happened after A's.
Two kinds of clock on every machine:
| Clock | Use | Don't use for |
|---|---|---|
Time-of-day (wall clock): System.currentTimeMillis(), time.time() | Timestamps for humans, logs | Measuring durations (can jump) |
Monotonic: System.nanoTime(), time.monotonic() | Measuring elapsed time, timeouts | Comparing across machines (arbitrary origin) |
Happened-before
Leslie Lamport (1978) defined causality without clocks. Event a happened before b (written a → b) if:
- a and b are on the same process and a comes first, or
- a is sending a message and b is receiving that message, or
- there's a chain: a → c and c → b (transitivity).
If neither a → b nor b → a, the events are concurrent (a ∥ b): neither could have influenced the other.
Lamport clocks
Each process keeps a counter L:
- Before each local event, increment: L = L + 1.
- When sending a message, attach L.
- When receiving a message with timestamp T: L = max(L, T) + 1.
Guarantee: if a → b then L(a) < L(b). The converse is not true: L(a) < L(b) doesn't mean a happened before b (they may be concurrent). Breaking ties with process IDs gives a total order consistent with causality — useful for things like mutual exclusion and total-order broadcast — but Lamport clocks can't detect concurrency.
class LamportClock:
def __init__(self):
self.time = 0
def tick(self) -> int: # local event or send
self.time += 1
return self.time
def receive(self, remote: int) -> int:
self.time = max(self.time, remote) + 1
return self.timeVector clocks
To detect concurrency, each process keeps a vector of counters, one per process: V[i] = "how many events of process i I know about".
- On a local event at process i: V[i] += 1.
- On send: increment own entry, attach the whole vector.
- On receive: V = element-wise max(V, received), then increment own entry.
Comparing two vectors:
- V(a) ≤ V(b) element-wise (and not equal) → a happened before b.
- Neither ≤ the other → concurrent.
def compare(a: dict, b: dict) -> str:
keys = a.keys() | b.keys()
a_le_b = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
b_le_a = all(b.get(k, 0) <= a.get(k, 0) for k in keys)
if a_le_b and b_le_a: return "equal"
if a_le_b: return "before"
if b_le_a: return "after"
return "concurrent"
compare({"A": 2, "B": 1}, {"A": 2, "B": 3}) # 'before'
compare({"A": 3, "B": 1}, {"A": 2, "B": 3}) # 'concurrent' → a real conflictUses: detecting conflicting writes in Dynamo-style stores (Riak) so the application or a CRDT can merge siblings instead of dropping one; causal consistency; distributed debugging. Cost: the vector grows with the number of participants (version vectors track replicas rather than clients to keep it bounded; dotted version vectors refine this).
| Clock | Size | Captures causality? | Detects concurrency? |
|---|---|---|---|
| Physical | 1 timestamp | No (skew) | No |
| Lamport | 1 integer | One direction only | No |
| Vector | N integers | Yes, exactly | Yes |
Hybrid logical clocks (HLC)
HLCs combine a physical timestamp with a logical counter: they stay close to wall-clock time (so timestamps are meaningful to humans and usable for snapshot reads like "as of 10:00"), while still guaranteeing that if a → b then HLC(a) < HLC(b). Used by CockroachDB, YugabyteDB and MongoDB. Each timestamp is (max physical time seen, counter).
TrueTime: embracing uncertainty
Google Spanner uses GPS receivers and atomic clocks in every data centre. Its TrueTime API returns not a time but an interval [earliest, latest], guaranteed to contain the true time, typically a few milliseconds wide.
To commit a transaction with timestamp t, Spanner waits until earliest > t ("commit wait") before making it visible. After that wait, every node anywhere agrees the transaction is in the past — giving external consistency (linearizable transactions) globally, at the cost of a few milliseconds per commit. Better clocks mean shorter waits; AWS and others now offer similar bounded-error clock services.
- Wall clocks drift and jump; don't use them to order events across machines or to measure durations.
- Happened-before captures causality: program order, send before receive, transitivity.
- Lamport clocks: if a → b then L(a) < L(b); total order with tie-breaks; can't detect concurrency.
- Vector clocks capture causality exactly and detect concurrent (conflicting) updates.
- Hybrid logical clocks stay near physical time while respecting causality.
- Spanner's TrueTime exposes clock uncertainty and waits it out for global consistency.
QLamport clocks vs vector clocks?hard
A Lamport clock is a single counter per process, updated on events and messages, guaranteeing that causally earlier events have smaller timestamps; but a smaller timestamp doesn't imply causality, so concurrent events can't be identified. A vector clock keeps one counter per process; comparing vectors element-wise tells you exactly whether one event happened before another or whether they're concurrent, which is what conflict detection needs. The cost is size proportional to the number of processes.