Course contents

08. Distributed Systems Lesson 10 of 10

Logical Clocks

Why wall clocks misorder events across machines, how Lamport timestamps and vector clocks capture causality, and where hybrid clocks fit.

14 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Clocks on different machines drift and get stepped, so wall-clock timestamps can order even causally related events backwards.
  • Happened-before orders events by same-node sequence and message send → receive; all other pairs are concurrent.
  • Lamport clocks give causally later events larger numbers, but a larger number does not imply causality.
  • Vector clocks detect concurrency: if neither vector is ≤ the other, the updates conflict.
  • A merged write whose vector dominates all siblings resolves the conflict; vectors cost one entry per node.
  • Hybrid logical clocks keep timestamps near physical time without contradicting causality.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A logical clock assigns numbers to events so that the numbers respect causality rather than physical time. Lamport clocks (Leslie Lamport, "Time, Clocks, and the Ordering of Events in a Distributed System", 1978) give each event a single counter. Vector clocks (Fidge and Mattern, 1988) give each event a vector with one counter per node, which is enough to tell whether two events are causally related or concurrent. Hybrid logical clocks (Kulkarni et al., 2014) combine a physical timestamp with a logical counter.

Why it exists

Distributed systems constantly need to order events: which write is newer, which message came first, whether an update was made with knowledge of another. Physical clocks cannot answer that reliably across machines. Quartz oscillators drift (tens of parts per million is common), NTP corrections step or slew clocks, virtual machines pause, and leap seconds are handled differently by different systems. NTP typically keeps servers within a few milliseconds of each other, but any two events closer together than the error can be ordered backwards, and a misconfigured node can be off by much more. Last-writer-wins on wall-clock timestamps then silently discards newer data.

How it works

Happened-before. e → f if e and f are on the same node and e came first; or e is the sending of a message and f its receipt; or there is a chain of such steps. If neither e → f nor f → e, the events are concurrent (e ∥ f): neither could have influenced the other.

Lamport clocks. Each node keeps a counter L. It increments L before each event, attaches L to each message, and on receipt sets L = max(L, L_message) + 1. This guarantees e → f ⇒ L(e) < L(f). Breaking ties by node id yields a total order that all nodes agree on, which algorithms such as Lamport's mutual exclusion and some replicated logs use. The converse does not hold: L(e) < L(f) can be true for concurrent events, so Lamport timestamps cannot detect conflicts.

Vector clocks. Each node keeps a vector V with one entry per node. It increments its own entry on each event, attaches V to messages, and on receipt takes the element-wise maximum and then increments its own entry. Compare: V ≤ W if every entry of V is ≤ the matching entry of W. Then e → f if and only if V(e) < V(f), and if neither V(e) ≤ V(f) nor V(f) ≤ V(e), the events are concurrent. A replica can therefore decide whether an incoming version descends from what it has (replace it) or is concurrent (keep both as siblings and resolve).

Version vectors. Storage systems usually attach a vector per data item with one entry per replica that has coordinated writes, rather than per client or per event. Amazon's Dynamo paper (2007) described this, and Riak used it, later with dotted version vectors to avoid false conflicts. Clients read all siblings and write back a merged value whose vector dominates them.

Hybrid logical clocks. An HLC timestamp is a pair (l, c). l is the largest physical time the node has seen, c counts events within the same l. On send or local events, l = max(l, physical time), with c reset to 0 if l advanced and incremented otherwise; on receipt, l = max(l, l_message, physical time) and c is chosen so the new timestamp exceeds both the local and the message timestamp. HLC timestamps stay within the clock skew of physical time, respect happened-before, and fit in 64 bits.

Synchronised clocks with bounded uncertainty. Google Spanner's TrueTime exposes clock time as an interval with an explicit error bound (kept small with GPS and atomic clocks) and makes transactions wait out that uncertainty before committing, which yields externally consistent timestamps. Cloud providers now offer similar precise time services.

When to use it

  • Lamport clocks when you need a total order consistent with causality (ordering requests, tie-breaking) and do not need to detect concurrency.
  • Version vectors when replicas accept writes independently (multi-leader, leaderless) and you must detect conflicts rather than silently drop one.
  • Hybrid logical clocks for database transaction timestamps and MVCC when you want time-like values ("read as of 10:00") without trusting clocks for correctness.
  • Causal consistency: delivering messages or showing updates only after everything they depend on.

When not to

  • Within a single-leader system that already orders every write (a database primary, a Raft log): the log position is the order.
  • When last-writer-wins is acceptable for the data (caches, presence indicators) and occasional loss of a concurrent update does not matter.
  • When the number of writers is huge and unbounded: per-writer vectors grow without limit; use per-replica version vectors or a different conflict strategy.

Trade-offs

Choice You gain You pay
Wall-clock LWW Simple, small timestamps Lost updates whenever clocks disagree or writes are concurrent
Lamport clock One integer; total order consistent with causality Cannot detect concurrency
Vector / version vector Detects concurrent updates exactly One entry per node or replica on every value and message; application must merge siblings
Hybrid logical clock Causal and close to physical time, 64 bits Correctness of time-based reads still depends on a configured maximum clock offset
TrueTime-style bounded clocks External consistency Special time infrastructure and commit wait

Alternatives

  • A single sequencer or leader that orders all writes (a database primary, a Raft log, a Kafka partition).
  • CRDTs: data types whose concurrent updates merge automatically; many use version-vector-like metadata internally.
  • Application-level versions: optimistic concurrency with a version number checked on write, which turns concurrent updates into a retryable error.

Failure modes

  • Silent lost updates under LWW when clocks are skewed or a node's clock jumps forward (all its future writes win) or backward.
  • Sibling explosion: clients that never merge siblings let them pile up.
  • Vector growth and pruning: pruning old entries to bound size can make descendant versions look concurrent (or the reverse).
  • Exceeding the assumed clock offset in HLC-based databases: CockroachDB, for example, makes a node shut itself down when its clock drifts beyond the configured maximum offset relative to the cluster, rather than risk anomalies.

In production

Monitor clock offset on every node (chrony or NTP statistics) and alert well below the bound your database assumes. Avoid last-writer-wins for data where losing a concurrent update matters; if you must use it, use a logical or hybrid clock rather than raw wall-clock time. In leaderless stores, make sure clients read siblings and write merged values. Know which clock your database uses: CockroachDB and YugabyteDB use hybrid logical clocks, MongoDB uses a hybrid cluster time for causal consistency, Spanner uses TrueTime.

Common misconceptions

  • "NTP keeps clocks in sync, so timestamps are fine." Milliseconds of error are enough to reorder events, and clocks can jump.
  • "A higher Lamport timestamp means the event came later." Only for causally related events; concurrent events also get ordered numbers.
  • "Vector clocks resolve conflicts." They detect them; resolution is up to the application or a merge rule.
  • "Logical clocks measure time." They measure causality; they say nothing about how long ago something happened (HLCs add an approximation).

Interview angle

When a design has replicas accepting writes, ask how conflicts are detected. Explain why wall-clock last-writer-wins loses data, then contrast Lamport clocks (order, no concurrency detection) with vector clocks (detect concurrency, need merging). Mentioning version vectors in Dynamo-style stores, HLCs in CockroachDB and Spanner's TrueTime shows you know how the theory is used.

Model assumptions

This lesson is a scripted illustration, not a simulation: the simulator has no per-node clocks, so every message is a packet placed by hand and clock values are annotations. The lesson's tests recompute every Lamport, vector and hybrid clock value from the scripted messages using the textbook rules and check the annotations against them. Latencies (20 ms and 30 ms one way), clock offsets (+50 ms, −40 ms) and physical clock readings are illustrative. In the vector steps each send carries a write; the receive of a message counts as an event, as in the standard vector clock rules.

The lesson as textEvery step of the simulation, written out.
  1. 1. Wall clocks put events in the wrong order

    Three replicas keep the value x and resolve conflicts with last writer wins: the write with the later timestamp survives. Node A’s clock runs 50 ms fast, Node B’s 40 ms slow, which is well within what drifting or badly synchronised clocks do.

    A writes x = 1 and tells B and C. B receives it and afterwards writes x = 2, 70 ms later in real time. But B stamps its write …00.080 while A stamped its own …00.100. When both reach C, C keeps x = 1: the newer write is silently discarded.

    NTP usually keeps clocks within milliseconds, but clocks still drift, get stepped and disagree, and events closer together than the error are ordered at random. Scripted illustration.

    Scene: Node A, whose clock is 50 ms fast, writes x = 1 and sends it to B and C. Node B, 40 ms slow, receives it and then writes x = 2 with an earlier timestamp. Node C applies last writer wins and keeps the older value x = 1.

    Key idea: Timestamps from different machines’ clocks cannot be trusted to order events, even events that were causally related.

  2. 2. Happened-before instead of time

    Leslie Lamport (1978) proposed ordering events by cause, not by clock. Event *e* happened before *f* (written e → f) if they occur on the same node in that order, or *e* sends a message that *f* receives, or there is a chain of such steps.

    Here A sends m1 to B, and B, after receiving it, sends m2 to C. So A’s send → B’s receive → B’s send → C’s receive: C’s receive is causally after A’s send. C’s own local event at the start has no chain to or from A’s send: the two are concurrent (e ∥ f). Neither could have influenced the other, whatever the wall clocks say.

    Scripted illustration.

    Scene: A sends m1 to B; B then sends m2 to C. A’s send happened before C’s receive through B. C’s earlier local event is concurrent with A’s send.

    Key idea: Happened-before: same-node order plus message send → receive, transitively. Everything else is concurrent.

  3. 3. Lamport timestamps: a counter per node

    Each node keeps a counter L. Before every event it adds 1. A message carries the sender’s L, and a receiver sets L = max(its own L, the message’s L) + 1.

    A sends m1 with L = 1. B had one local event (L = 1), receives m1: max(1, 1) + 1 = 2, then sends m2 with L = 3. C had three local events (1, 2, 3) and receives m2: max(3, 3) + 1 = 4.

    The guarantee: if e → f then L(e) < L(f). Ties are broken by node id, which gives a total order every node agrees on, used for example to order requests in Lamport’s mutual exclusion algorithm. Scripted illustration.

    Scene: A sends m1 with Lamport timestamp 1. B, at 1, receives it and moves to 2, then sends m2 with 3. C, at 3 after three local events, receives m2 and moves to 4.

    Key idea: Lamport clocks: increment on every event, take the max on receive. Causally later events always get larger numbers.

  4. 4. Bigger number does not mean “caused by”

    A and C both write x without having heard from each other: A’s write gets L = 2, C’s gets L = 3 (C simply had more earlier events). Both send their write to B.

    Ordering by Lamport timestamp, B keeps C’s value and drops A’s. But the writes were concurrent: nothing C knew depended on A’s write. Lamport clocks give the implication only one way: e → f implies L(e) < L(f), but L(e) < L(f) does not imply e → f. They cannot tell “later” from “concurrent”, so a conflict is hidden instead of detected.

    Scripted illustration.

    Scene: A writes x with Lamport timestamp 2 and C writes x with timestamp 3, without any message between them. B keeps C’s write because 3 is larger, although the writes were concurrent.

    Key idea: Lamport timestamps order events consistently but cannot detect concurrency: concurrent writes look ordered.

  5. 5. Vector clocks detect concurrent updates

    A vector clock keeps one counter per node, here [A, B, C]. A node increments its own entry on each event, sends the whole vector, and on receive takes the element-wise max and then increments its own entry.

    A writes x = 1: [1,0,0], sent to B. B merges and counts the receive: [1,1,0], then writes x = 2: [1,2,0], sent to C. Meanwhile C wrote x = 3 on its own: [0,0,1].

    Compare: V ≤ W if every entry of V is ≤ W’s. [1,0,0] ≤ [1,2,0], so B’s write descends from A’s and may replace it. [1,2,0] and [0,0,1] are each larger somewhere: concurrent. C keeps both as siblings instead of picking one. After the receive, C’s clock is [1,2,2]. Scripted illustration.

    Scene: A writes x = 1 with vector [1,0,0] and sends it to B. B receives it and writes x = 2 with [1,2,0], sent to C. C had written x = 3 with [0,0,1]; the two vectors are concurrent, so C keeps both versions.

    Key idea: Vector clocks: V < W means W saw V; neither ≤ the other means concurrent, a real conflict to resolve.

  6. 6. Merge the siblings, then the conflict is gone

    Someone has to resolve the conflict: the application (for a shopping cart, the union of both carts), a merge rule, or the user. C writes the merged value with a clock that has seen both versions: [1,2,3], which is ≥ [1,2,0] and ≥ [0,0,1].

    When A and B receive it, it dominates what they have, so they simply replace their versions; no new conflict. That is how Dynamo-style stores (Amazon’s 2007 Dynamo paper, Riak) used vector clocks; in storage systems they are usually version vectors, with one entry per replica rather than per client.

    The cost: one entry per node, carried on every message and stored with every value. Scripted illustration.

    Scene: C writes the merged value with vector [1,2,3] and sends it to A and B. Because it dominates their versions, both replace their copies without a new conflict.

    Key idea: A merged write whose vector dominates all siblings ends the conflict; vectors cost one entry per node.

  7. 7. Hybrid logical clocks: close to real time, still causal

    Many databases want timestamps that are close to wall-clock time (for queries “as of 10:00”) and still respect causality. A hybrid logical clock (HLC, Kulkarni et al., 2014) is a pair (l, c): l tracks the largest physical time seen, c is a counter for events within the same l.

    A sends with (100, 0). B’s physical clock reads only 95, but on receive l = max(own l, message l, physical) = 100, and since that equals the message’s l, c = 0 + 1: (100, 1), later than A’s send although B’s clock is behind. C’s clock reads 130, ahead of everything: (130, 0).

    CockroachDB, YugabyteDB and MongoDB’s cluster time use hybrid clocks; Spanner instead waits out the uncertainty of its TrueTime clocks. Scripted illustration.

    Scene: A sends a message stamped (100, 0). B’s clock reads 95 but its hybrid clock becomes (100, 1) on receipt, and it sends (100, 2) to C. C’s clock reads 130, so its hybrid clock becomes (130, 0).

    Key idea: HLCs stay within clock skew of physical time but never let a receive look earlier than its send.

  8. 8. What to remember about logical clocks

    Wall clocks on different machines cannot order events reliably. Lamport clocks give every event a number consistent with happened-before, but cannot detect concurrency. Vector clocks can: two vectors that are not ≤ each other mark a real conflict that must be merged.

    Hybrid logical clocks combine both worlds: timestamps near physical time that never contradict causality.

    Scene: Three nodes, A, B and C, connected to each other.

    Key idea: Order by causality, not by clocks: Lamport for a consistent order, vectors to detect conflicts, HLC for time-like causal timestamps.