Distributed systems constantly need to know which event came first: which write wins, whether one update saw another, whether a snapshot is consistent. Wall clocks can't answer reliably, because every machine's clock drifts, jumps and disagrees with its neighbors. Logical clocks sidestep physical time and capture causality directly: Lamport timestamps give an order consistent with cause and effect, vector clocks detect when two events are truly concurrent, and hybrid logical clocks and Spanner's TrueTime bring physical time back with explicit bounds on its error.
Think of it like
Holiday photos from three cameras
Three friends come home with photos from three cameras whose clocks were never set properly, so sorting by timestamp produces nonsense. But some ordering is certain: if Bea's photo shows her holding the postcard Ana wrote, Bea's photo came after Ana wrote it. If two photos have no such link, you genuinely can't tell which came first, and for most purposes it doesn't matter. Logical clocks track exactly these "could have influenced" links instead of trusting the cameras.
Why wall clocks lie
Each machine keeps time with a quartz oscillator whose frequency varies with temperature and manufacturing. Clocks are corrected by NTP, which estimates the offset to a time server over a network with variable delay, so it can only be as accurate as that delay is symmetric. The result is that two servers in the same rack typically disagree by anything from microseconds to milliseconds, and occasionally by much more.
Quartz drift (Google's assumed bound)
200 ppm
about 17 s per day if never corrected
NTP over the internet
Tens of ms
much better on a LAN; worse with asymmetric routes
Spanner TrueTime uncertainty ε
1 to 7 ms
2012 paper; GPS and atomic clocks in every data center
CockroachDB default max offset
500 ms
nodes that drift too far shut themselves down
- Skew: two clocks show different times at the same instant.
- Drift: a clock runs slightly fast or slow, so skew grows between corrections.
- Jumps: NTP may step a clock backward or forward, and an operator or VM migration can do the same. A timestamp taken later can be smaller than one taken earlier.
- Leap seconds: an extra second inserted into UTC. The June 2012 leap second sent many Linux servers into CPU-burning livelocks, and in January 2017 a negative duration made part of Cloudflare's DNS service fail. Google and AWS now smear the second over many hours instead, and the CGPM has voted to stop adding leap seconds by 2035.
- Pauses: a GC pause, a VM being descheduled or a laptop sleeping can freeze a process between reading the clock and using the value.
Wall clocks versus monotonic clocks
Time-of-day (wall) clock
- Seconds since the Unix epoch, synchronized by NTP
- Roughly comparable across machines
- Can jump backward or forward at any moment
- Use for timestamps shown to humans and for coarse cross-machine ordering
Monotonic clock
- Counts from an arbitrary point, such as boot
- Never goes backward (its rate may be slewed slightly)
- Meaningless on any other machine
- Use for durations, timeouts, leases, rate limits and heartbeats
| Platform | Wall clock | Monotonic clock |
|---|---|---|
| JavaScript | Date.now() | performance.now() |
| Python | time.time() | time.monotonic() |
| Java | System.currentTimeMillis(), Instant.now() | System.nanoTime() |
| Go | time.Now() (wall part) | time.Since(start) uses the monotonic reading automatically (Go 1.9+) |
| Linux | CLOCK_REALTIME | CLOCK_MONOTONIC |
import time
start = time.time()
do_work()
elapsed = time.time() - start # BUG: negative or huge if NTP steps the clock meanwhile
start = time.monotonic()
do_work()
elapsed = time.monotonic() - start # correct: monotonic time never goes backwardHappened-before
Leslie Lamport's 1978 paper Time, Clocks, and the Ordering of Events in a Distributed System replaced "which happened first in real time" with a question the system can actually answer: could event a have influenced event b? Influence can travel only along two routes: forward in time within one process, and from the sending of a message to its receipt.
Lamport timestamps
- 1
Keep a counter
Every process holds an integer C, starting at 0.
- 2
Tick on every event
Before a local event or a send, increment C. The event's timestamp is the new C.
- 3
Attach to messages
Every message carries the sender's timestamp.
- 4
Jump on receive
On receiving a message with timestamp t, set C = max(C, t) + 1. The receive event can never look older than the send that caused it.
Breaking ties by process ID turns Lamport timestamps into a total order that every node computes identically: compare (C, processId) pairs. That is enough for many algorithms, such as Lamport's distributed mutual exclusion, totally ordered multicast, and the operation IDs that CRDT libraries like Automerge use to order edits deterministically. What it can't do is tell you whether two writes conflict: (5, A) < (7, B) is true whether or not A's event influenced B's.
Vector clocks
A vector clock (Fidge and Mattern, 1988) keeps one counter per process instead of one overall. Each event's vector records how many events of every process it has (transitively) seen. Comparing two vectors then answers the causality question exactly, including "neither".
- 1
Start
Process i holds a vector V of N zeros, one entry per process.
- 2
Local event or send
Increment your own entry: V[i] += 1. Attach a copy of V to any message.
- 3
Receive
Take the element-wise maximum with the incoming vector, then increment your own entry.
- 4
Compare
a happened before b if every entry of V(a) is ≤ the matching entry of V(b) and at least one is smaller. If each vector has an entry larger than the other's, the events are concurrent.
| V(a) | V(b) | Relation | Why |
|---|---|---|---|
| [A:2, B:1, C:0] | [A:2, B:2, C:0] | a → b | Every entry ≤, and B's entry is smaller |
| [A:2, B:1, C:0] | [A:1, B:2, C:0] | a ∥ b | a is ahead on A, b is ahead on B |
| [A:3, B:0, C:1] | [A:3, B:0, C:1] | Equal | The same event (or identical history) |
| [A:1, B:4, C:2] | [A:1, B:3, C:2] | b → a | Every entry of b is ≤ a's, B's is smaller |
The simulation above shows the vectors updating as messages flow between processes; compare any two events by the rule above. The cost is size: a vector has one entry per participant, so it grows with the number of processes that ever write, and every message carries it.
Vector clocks in Dynamo and Riak
Amazon's Dynamo (2007) used vectors, one entry per coordinating server, to version every value of its shopping cart service. Instead of overwriting conflicting versions, it kept them all as siblings and returned them to the application to merge. Press play on each flow to follow the example from the Dynamo paper.
- Riak exposes the same model: with
allow_multenabled, conflicting writes become siblings and a read returns all of them with a causal context. Riak 2.0 introduced dotted version vectors (the default for buckets that use bucket types) so that many clients writing through the same server don't produce an explosion of false siblings. - Vector size: Dynamo bounded each vector by dropping the oldest entry once it exceeded a threshold (10 in the paper). That can, rarely, make a descendant look concurrent, which costs an unnecessary sibling but never loses data.
- Today: DynamoDB does not expose siblings; it uses a leader per partition and conditional writes. Cassandra uses per-cell last-writer-wins timestamps. Sibling-based designs are now less common than CRDTs, which merge automatically.
Vector clocks versus version vectors
Vector clock
- Orders events in a message-passing system
- One entry per process; every event and message ticks it
- Used for causal broadcast, debugging, consistent snapshots
- Grows with the number of processes
Version vector
- Orders versions of one data item across replicas
- One entry per replica (or writer); only updates tick it
- Used to detect conflicting replicas in Dynamo, Riak and file sync tools
- Merged when replicas synchronize
The two use the same comparison rule and are often called by the same name; the Dynamo paper says "vector clock" for what is really a version vector. The distinction matters when sizing them: entries per replica stay small, while entries per client grow without bound.
Hybrid logical clocks
Logical clocks lose all connection to real time, which you need for "read as of 10:00", TTLs and human-readable history. A hybrid logical clock (Kulkarni et al., 2014) keeps a pair (l, c): l is the largest physical time this node has seen, from its own clock or from any message, and c is a small logical counter that orders events sharing the same l. HLC timestamps respect causality like Lamport clocks, stay within the clock skew of real time, and fit in 64 bits.
- 1
Local event or send
If the physical clock has moved past l, set l to it and reset c to 0. Otherwise keep l and increment c.
- 2
Receive (l_m, c_m)
Set l to the maximum of the old l, l_m and the physical clock. Then c is 0 if the physical clock won, the incremented counter of whichever side supplied the winning l, or max(c, c_m) + 1 if both did.
- 3
Compare
Order by l, then by c. Larger always means "not earlier", and causally later events always compare larger.
TrueTime and commit wait
Google's Spanner takes the opposite approach: make physical time trustworthy by measuring its error. Every data center has time masters with GPS receivers and atomic clocks. TT.now() does not return a single time but an interval [earliest, latest] that is guaranteed to contain the true time, with half-width ε of a few milliseconds. Spanner then simply waits out the uncertainty.
Choosing a clock
| Clock | Size | Captures | Detects concurrency? | Close to real time? | Used by |
|---|---|---|---|---|---|
| Wall clock | 64 bits | Approximate real time | No | Yes, within skew | Cassandra LWW, logs, TTLs |
| Lamport timestamp | One counter | An order consistent with causality | No | No | Total-order broadcast, CRDT operation IDs |
| Vector clock / version vector | One counter per process or replica | Exact causality | Yes | No | Dynamo, Riak, causal broadcast |
| Hybrid logical clock | Physical time + small counter (64 bits in the paper) | Causality plus approximate real time | No | Yes, within skew | CockroachDB, YugabyteDB, MongoDB cluster time |
| TrueTime | An interval | Real time with a bounded error | No | Yes, within ε | Spanner |
Implementation
A Lamport clock for total ordering and a vector clock that can tell "before", "after", "equal" and "concurrent" apart. Vectors are maps so processes can join over time.
from typing import Literal
VC = dict[str, int]
Order = Literal["before", "after", "equal", "concurrent"]
class LamportClock:
def __init__(self) -> None:
self.time = 0
def tick(self) -> int:
self.time += 1
return self.time
def receive(self, remote: int) -> int:
self.time = max(self.time, remote) + 1
return self.time
def compare(a: VC, b: VC) -> Order:
keys = a.keys() | b.keys()
a_smaller = any(a.get(k, 0) < b.get(k, 0) for k in keys)
b_smaller = any(b.get(k, 0) < a.get(k, 0) for k in keys)
if a_smaller and b_smaller:
return "concurrent"
if a_smaller:
return "before"
if b_smaller:
return "after"
return "equal"
class VectorClock:
def __init__(self, node_id: str) -> None:
self.id = node_id
self.v: VC = {}
def tick(self) -> VC:
self.v[self.id] = self.v.get(self.id, 0) + 1
return dict(self.v)
def receive(self, remote: VC) -> VC:
for k, n in remote.items():
self.v[k] = max(self.v.get(k, 0), n)
return self.tick()
a, b = VectorClock("A"), VectorClock("B")
m = a.tick() # {'A': 1}
b.receive(m) # {'A': 1, 'B': 1}
x, y = a.tick(), b.tick()
print(compare(m, y)) # before
print(compare(x, y)) # concurrentKey takeaways
- Physical clocks drift, skew and jump; never order cross-machine events by wall time alone, and measure durations with a monotonic clock.
- Happened-before (a → b) means a could have influenced b; events with no such path are concurrent, whatever the wall clock says.
- Lamport timestamps give a total order consistent with causality in one integer, but can't detect concurrency.
- Vector clocks and version vectors characterize causality exactly, letting stores like Dynamo and Riak keep concurrent writes as siblings.
- Hybrid logical clocks combine causal ordering with near-physical timestamps in 64 bits (CockroachDB, YugabyteDB).
- Spanner's TrueTime bounds clock error and waits it out (commit wait), buying external consistency for about 2ε of latency.
Common pitfalls
- Using last-writer-wins on wall-clock timestamps and losing writes that land within the clock skew of each other.
- Computing timeouts, lease expiry or elapsed time from the wall clock, so an NTP step breaks them.
- Assuming a smaller Lamport timestamp means one event caused the other.
- Letting vector clocks grow with every client ID ever seen instead of keying them by replica.
- Ignoring leap seconds and clock steps, then crashing on a negative duration.
Interview tips
- Draw two or three process timelines with message arrows and label the Lamport and vector timestamps; it makes concurrency obvious.
- When a design uses timestamps for conflict resolution, volunteer the skew problem and name the fix you'd use (version vectors, CRDTs, HLC or a single leader).
- Know the one-sentence versions: Lamport is consistent with causality, vectors characterize it, HLC stays close to real time, TrueTime bounds the error.
Real-world applications
- Dynamo-style stores (Riak, Voldemort) detecting conflicting replica versions with version vectors.
- CockroachDB and YugabyteDB assigning MVCC timestamps with hybrid logical clocks.
- Google Spanner providing externally consistent transactions with TrueTime.
- Collaborative editors and CRDT libraries ordering operations with Lamport-style IDs.
- Distributed tracing and debugging tools reconstructing causal order across services.
Test yourself
Event a has Lamport timestamp 5 and event b has Lamport timestamp 9. What can you conclude?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.