Vector Clocks, Lamport Clocks & Distributed Causality
"In a distributed system, it is sometimes impossible to say that one of two events occurred first." — Leslie Lamport, Time, Clocks, and the Ordering of Events in a Distributed System, Communications of the ACM 21(7), July 1978
Summary: Machines do not share a clock, so "which write came first?" has no answer from timestamps alone. Distributed systems answer a smaller, sharper question instead, "could this event have seen that one?", and track the answer with logical clocks (Lamport, vector, version vectors with dots), hybrid clocks (HLC) or physical clocks with a known error bar (TrueTime). Focus: Wall vs monotonic clocks, NTP drift and skew, leap seconds and smearing, Go's monotonic reading; happens-before; Lamport clocks and the total order with tie-break; vector clocks (Fidge/Mattern), compare/merge/prune and actor ids; version vectors vs vector clocks, Dynamo and Riak dotted version vectors and siblings; hybrid logical clocks in CockroachDB and YugabyteDB; Spanner TrueTime and commit wait; causal consistency in COPS and MongoDB causal sessions; interval tree clocks and bloom clocks; causation and correlation ids; last-writer-wins dangers and conflict detection in multi-leader systems. Learning goal: Given any two events in a distributed system, say whether one caused the other or whether they are concurrent, pick the cheapest clock that answers the question your feature actually needs, and implement it (Go and Laravel) without trusting a wall clock you cannot bound.
This chapter sits in the Distributed Systems Primitives group, after Gossip Protocols and before Merkle Trees & Anti-Entropy and CRDTs. It owns clocks and causality tracking. The consistency models that use these clocks (linearizability, causal, session guarantees) live in Consistency Models; how replicas are wired and how conflicts are resolved at the topology level lives in Replication Topologies; consensus and 2PC internals in Distributed SQL, Consensus & 2PC; per-key ordering in brokers in Ordering & Partitioning; Go's time API itself in time.Time, Timers & Random Numbers.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why timestamps cannot order events | Why it exists |
| Lamport, Fidge, Mattern, Dynamo, HLC, Spanner, COPS | Where it comes from |
| Wall vs monotonic clocks, NTP, skew, leap seconds | Physical clocks |
| The happened-before relation | Happens-before |
| Lamport timestamps and total order | Lamport clocks |
| Vector clocks: compare, merge, prune | Vector clocks |
| Version vectors, dots, siblings, Riak | Version vectors and DVV |
| Hybrid logical clocks | HLC |
| TrueTime and commit wait | TrueTime |
| Causal consistency, COPS, MongoDB sessions | Causal consistency |
| Interval tree clocks, bloom clocks | Other clocks |
| Causation and correlation ids in messaging | Causality in messaging |
| Last-writer-wins and conflict detection | LWW and conflicts |
| Knobs, sizes, error messages | Mechanics |
| Code | Go, Laravel |
| Classic failures and their fixes | Solving the classic problems |
| Which clock for which job | Choosing |
| From one process to many regions | In architecture |
| Run it yourself | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The clocks.
| Clock | In plain words | Size | Tells you | Cannot tell you | Used by |
|---|---|---|---|---|---|
| Wall clock | The time of day the OS believes | 64 bits | Roughly when, for humans | Order across machines; it jumps | Logs, created_at, Cassandra cell timestamps |
| Monotonic clock | A stopwatch that never goes back | 64 bits | Elapsed time on one machine | Anything across machines | Timeouts, latency metrics, Go time.Since |
| Lamport clock | A counter bumped on every event and pushed past every received value | 1 integer | A total order that never contradicts causality | Whether two events were concurrent | Total-order broadcast, Lamport mutual exclusion |
| Vector clock | One counter per process, merged on receive | N integers | Before, after, equal or concurrent, exactly | Real time | Debuggers, causal delivery, Dynamo |
| Version vector (with dots) | One counter per replica per object, plus the event that made each value | Replicas, not clients | Which stored versions conflict | Real time | Riak (DVV), Dynamo, multi-device sync |
| Hybrid logical clock | Physical time plus a small counter, pushed forward on receive | 64 bits (48 + 16) | Causal order that stays close to real time | Concurrency; real-time order beyond the skew | CockroachDB, YugabyteDB |
| TrueTime | An interval guaranteed to contain true time | 2 timestamps | Real-time order once you wait out the interval | Nothing, if the bound holds | Google Spanner |
The three questions and the cheapest clock for each.
| Question | Cheapest correct answer | Wrong answer people use |
|---|---|---|
| "How long did this take?" | Monotonic clock on one machine | Subtracting two wall-clock readings |
| "Give me one order that respects causality" | Lamport clock with node-id tie-break, or a single sequencer | Sorting by created_at from many hosts |
| "Did these two writes see each other?" | Version vector or vector clock comparison | Comparing timestamps (last-writer-wins) |
| "Is this order also real-time order across regions?" | TrueTime + commit wait, or HLC + bounded max-offset | NTP and hope |
| "Which step caused which across services?" | Causation id + correlation id on every message | Matching log lines by time |
Comparing two vector clocks (or version vectors).
| Condition | Result | What to do |
|---|---|---|
| Every counter of A equal to B | Equal | Same state, nothing to do |
| Every counter of A <= B, at least one strictly less | A before B | B supersedes A; drop A |
| Every counter of B <= A, at least one strictly less | A after B | A supersedes B; drop B |
| Some counters larger on each side | Concurrent | Keep both (siblings), merge with a rule or a CRDT, or ask the user |
The picture is the run you will replay in the lab. Arrows inside a line are local order; arrows between lines are messages. a1 reaches c2 through b1 and b2, so a1 happened before c2. a2 and c2 are concurrent: neither could have seen the other, yet Lamport time says 2 < 4. That gap is the reason vector clocks exist.
Why it exists
On one machine, "which happened first" is answered by the CPU: one thread, one memory, one clock. Across machines there is no shared memory and no shared clock. Messages take an unknown time to arrive, clocks drift apart, and a clock can be stepped backwards by NTP. Lamport's paper starts from exactly this: "The relation 'happened before' is therefore only a partial ordering of the events in the system. We have found that problems often arise because people are not fully aware of this fact and its implications."
So the field changes the question. Instead of "what time did this happen?" it asks "what could this event have known about?" Information travels only along messages; if no chain of messages connects two events, neither could have influenced the other, and their order is meaningless. Every clock on this page is a different trade between how much of that causal structure it captures and how much it costs.
| Cheap and lossy | Rich and expensive |
|---|---|
| Wall-clock timestamp: 8 bytes, no coordination | Vector clock: one counter per participant |
| Lamport clock: total order, cannot detect concurrency | Vector clock: exact causality, grows with N |
| Last-writer-wins: always one value, silently loses writes | Siblings: never lose a write, application must merge |
| HLC: causality plus near-real time, needs a skew bound | TrueTime: real-time order, needs GPS and atomic clocks |
| Server-assigned sequence: trivial, one writer bottleneck | Dotted version vectors: many writers, more metadata |
The analogy we reuse on this page: letters between three friends who keep diaries. Each friend numbers their own diary entries (a Lamport clock is "the highest entry number I have ever heard of, plus one"). When Alice writes to Bob, she copies her diary numbers into the letter; Bob updates his knowledge of everyone's latest entry (a vector clock is that list of "latest entry I know of, per friend"). If Bob's entry 2 knows about Alice's entry 1, it came after it. If Alice's entry 2 and Carol's entry 2 know nothing of each other, no one can say which came first, and asking their watches does not help, because their watches are set differently. A version vector is the same list attached to a shared document instead of a diary; siblings are two copies of the document that each friend edited without seeing the other's.
Three common misunderstandings, up front
- "NTP keeps our clocks within a millisecond, so
ORDER BY created_atis the real order." NTP gives a typical offset, not a guarantee. A VM pause, a step correction, a leap second or a bad upstream can move a clock by seconds, and two events a millisecond apart on two hosts can be in either order. Lamport's Clock Condition goes one way only; physical clocks honour neither direction without a bound you monitor. - "A Lamport timestamp tells me which event happened first." It tells you that if A caused B then L(A) < L(B). The converse is false: Lamport himself notes "we cannot expect the converse condition to hold as well, since that would imply that any two concurrent events must occur at the same time." L(A) < L(B) is compatible with A before B and with A concurrent with B.
- "Vector clocks resolve conflicts." They detect them. When two versions are concurrent, the clock only says "neither saw the other". Someone still has to merge: the application, a user, or a data type built to merge (CRDTs).
Where it comes from
1978, happened-before and logical clocks. Lamport defined "happened before" as the smallest relation that contains local order and send-before-receive and is transitive, and gave two rules (IR1: increment between events; IR2: put the timestamp on the message, and on receipt set the clock "greater than or equal to its present value and greater than Tm"). The total order adds a tie-break: "To break ties, we use any arbitrary total ordering < of the processes." The same paper also synchronises physical clocks and bounds how far they drift, which is the seed of HLC and TrueTime.
1983, version vectors. Parker et al. used per-site counters to detect files modified independently in separate network partitions. Mattern's 1989 paper summarises it: each copy has a "version vector whose ith component counts the number of updates made to the file at site i", and incomparable vectors signal a conflict. (We read this through Mattern's summary, not the 1983 paper.)
1988 and 1989, vector clocks. Colin Fidge (Timestamps in Message-Passing Systems That Preserve the Partial Ordering, Australian Computer Science Communications 10(1), February 1988) and Friedemann Mattern (Virtual Time and Global States of Distributed Systems, 1989) independently gave each process a vector of clocks. Mattern describes them as "partially ordered and form a lattice", representing causality "in an isomorphic way": comparing vectors is exactly comparing causal histories. (Fidge's paper could not be retrieved from a working mirror for this chapter; it is cited, not quoted.)
2007, Dynamo. Amazon's Dynamo paper put vector clocks on every object version: "A vector clock is effectively a list of (node, counter) pairs." Concurrent versions are returned to the client for "semantic reconciliation", and clocks are truncated to bound their size.
2010 to 2014, Riak and dotted version vectors. Preguiça, Baquero, Almeida, Fonte and Gonçalves proposed dotted version vectors that capture causality while keeping metadata that "grows linearly only with the number of servers that register updates for a given data element, bounded by the degree of replication." Riak 2.0 added them as an option (dvv_enabled) and recommends them over plain vector clocks.
2011, COPS and causal+. Lloyd, Freedman, Kaminsky and Andersen built COPS, a geo-replicated key-value store with "causal consistency with convergent conflict handling, which we refer to as causal+ consistency", tracking explicit dependencies per write.
2012, Spanner and TrueTime. Google exposed clock uncertainty as an API: TT.now() returns [earliest, latest], and commits wait out the uncertainty to give external consistency at global scale.
2014, hybrid logical clocks. Kulkarni, Demirbas and co-authors: "we propose a hybrid logical clock, HLC, that combines the best of logical clocks and physical clocks." CockroachDB and YugabyteDB adopted it.
2008 and 2019, ITC and bloom clocks. Interval tree clocks (Almeida, Baquero, Fonte, OPODIS 2008) handle a changing set of participants by forking and joining identities; the bloom clock (Ramabaja, 2019) trades exactness for a size that "does not depend on the number of nodes in a system".
Year Idea What changed in practice
1 1978 Happened-before, Lamport clocks Order without synchronised clocks
2 1983 Version vectors (Parker et al.) Detect conflicting file copies after partitions
3 1988 Vector clocks (Fidge; Mattern 1989) Exact causality, concurrency detection
4 2007 Dynamo: vector clocks per object version Siblings and client-side reconciliation in production
5 2008 Interval tree clocks Causality with dynamic membership
6 2010 Dotted version vectors Bounded metadata, no false siblings (Riak 2.0)
7 2011 COPS: causal+ with explicit dependencies Scalable causal consistency across datacenters
8 2012 Spanner TrueTime and commit wait Real-time order with bounded clock uncertainty
9 2014 Hybrid logical clocks Causal timestamps that look like wall time (CockroachDB)
10 2016 Leap smear standardised by Google 24-hour linear smear instead of a repeated secondThe concept catalogue
Each block: plain words, the usual wrong belief, a definition, a step-by-step run, real scenarios, what products do, and the fix.
Physical clocks: wall, monotonic, NTP, drift, skew, leap seconds Must-know
In plain words: every machine has a quartz-driven clock that runs a little fast or slow; NTP nudges it towards a reference. The wall clock tells you the date; the monotonic clock is a stopwatch that only goes forward.
Common misunderstanding: "Time only moves forward." The wall clock moves backwards whenever NTP steps it, an operator fixes it, or a leap second is inserted. Cloudflare's 2017 New Year outage: "The root cause of the bug that affected our DNS service was the belief that time cannot go backwards." Their Go code computed time.Now().Sub(start), got a negative duration across the leap second, and rand.Int63n panicked on it.
Definition:
- Wall clock (physical clock, real-time clock): an estimate of UTC. Subject to synchronisation adjustments.
- Monotonic clock: a counter of elapsed time since an arbitrary point (boot), never adjusted backwards. Meaningless across machines.
- Clock drift: the rate error of one oscillator (parts per million). Spanner's paper budgets "200 microseconds/second" as the applied worst-case drift rate.
- Clock skew (offset): the difference between two clocks at one instant. Drift accumulates into skew between synchronisations.
- NTP (Network Time Protocol): synchronises to upstream servers by slewing (speeding or slowing the clock) or stepping (jumping).
chronyandntpdare the common Linux daemons; PTP (Precision Time Protocol, IEEE 1588) uses hardware timestamping for sub-microsecond accuracy where the network supports it. - Leap second: a second added to (or removed from) UTC to track the Earth's rotation; 23:59:60 is a real time of day.
- Leap smear: spreading the leap second over many hours so clocks never step. Google: "We encourage anyone smearing leap seconds to use a 24-hour linear smear from noon to noon UTC"; the frequency change "is about 11.6 ppm", "well under NTP's 500 ppm maximum slew rate". During the smear, smeared and unsmeared clocks differ by up to half a second, so do not mix sources.
Go merges the two clocks in one value. The time package docs: "the wall clock is for telling time and the monotonic clock is for measuring time." time.Now() returns both readings; Sub, Before, After, Equal and Compare use the monotonic reading when both values have one, and "The canonical way to strip a monotonic clock reading is to use t = t.Round(0)." Go 1.9 added this ("The time package now transparently tracks monotonic time in each Time value, making computing durations between two Time values a safe operation in the presence of wall clock adjustments"); Cloudflare's January 2017 bug predated it: "Go currently doesn't offer a monotonic time source".
Host A (clock +40 ms) Host B (clock correct) Log sorted by wall time
1 10:00:00.040 user pays (event 1)
2 sends "paid" to B ---------->
3 10:00:00.010 receives "paid" 10:00:00.010 B: ship order
4 10:00:00.012 ships order 10:00:00.012 B: shipped
5 10:00:00.040 A: user pays
6 the audit log says the order shipped 28 ms before it was paid forReal scenario: an audit trail sorted by created_at from several app servers shows effects before causes; a rate limiter or lease uses wall time and grants twice after an NTP step; a token's exp check fails on a phone with a wrong clock; a Kubernetes node with a stale clock rejects TLS certificates as "not yet valid"; metrics computed by subtracting wall timestamps go negative during a leap second.
What provides it:
| Product / API | Wall reading | Monotonic reading | Note |
|---|---|---|---|
Go time.Now() | Yes | Yes, until Round(0), UTC(), In(), marshalling | Use time.Since / Sub for durations |
Linux clock_gettime | CLOCK_REALTIME | CLOCK_MONOTONIC | Monotonic excludes suspend unless CLOCK_BOOTTIME |
| PHP | microtime(true), time() | hrtime(true) (nanoseconds) | Laravel's now() is wall time (Carbon) |
| Google Public NTP | Smeared UTC | n/a | 24-hour linear smear, noon to noon |
| PostgreSQL | now(), clock_timestamp() | n/a | now() is the transaction start time |
Fix / how to use it: measure durations with a monotonic clock; never subtract wall times without checking for negative results; alert on NTP offset (chrony tracking); for ordering across machines use one of the logical or hybrid clocks below; treat wall timestamps as labels for humans.
Happens-before and concurrent events Must-know
In plain words: event A happened before B if information from A could have reached B: same process and earlier, or A sent a message that B received, or a chain of those. If neither could reach the other, they are concurrent.
Common misunderstanding: "Concurrent means at the same moment." In distributed systems concurrent means causally unrelated. Two events an hour apart are concurrent if no message chain connects them; two events a microsecond apart are ordered if one sent a message the other received.
Definition (Lamport 1978): the relation → is the smallest relation such that (1) if a and b are in the same process and a comes before b, a → b; (2) if a is the sending of a message and b its receipt, a → b; (3) if a → b and b → c then a → c. "Two distinct events a and b are said to be concurrent if" neither a → b nor b → a. It is an irreflexive partial order. The causal history of an event is the set of all events that happened before it; a → b exactly when the history of a is a strict subset of the history of b. A consistent cut is a set of events closed under happened-before (if it contains b and a → b, it contains a): a global state that could actually have existed.
A B C
1 a1 (send m1) ------>
2 b1 (receive m1)
3 b2 (send m2) ------->
4 a2 (local)
5 c1 (local, before m2 arrives)
6 c2 (receive m2)
a1 -> b1 -> b2 -> c2 a1 -> c2 by transitivity
a2 || b1, a2 || b2, a2 || c2, c1 || a1, c1 || b2 (|| = concurrent)Real scenario: "reply shown before the question" in a chat (the reply happened after the question; showing it first breaks causality); a comment on a deleted post; an OrderShipped event processed before OrderPaid on another consumer; debugging a distributed trace where spans from different hosts overlap in wall time; deciding whether two edits of a profile conflict.
What provides it: nothing gives it to you for free. Messages and shared state are the only carriers of causality; clocks below are encodings of it. Distributed tracing (OpenTelemetry parent span ids) records an explicit happened-before tree for one request.
Fix / how to use it: decide which relation your feature needs: none (independent data), causal (replies after questions, effects after causes), or total (one agreed sequence). Then pick the clock in Choosing.
Lamport clocks, total order and tie-break Must-know
In plain words: each process keeps a counter. Bump it on every event. Stamp outgoing messages with it. On receive, jump to one more than the larger of your counter and the message's. Sort by (counter, process id) and you get one order everybody agrees on that never puts an effect before its cause.
Common misunderstanding: "A higher Lamport number means it happened later." Only if the two events are causally related. In the lab run, L(a2) = 2 and L(c2) = 4, but a2 and c2 are concurrent. Lamport order is one valid linearisation of the partial order, chosen arbitrarily for concurrent events.
Definition: the Clock Condition "For any events a, b: if a → b then C(a) < C(b)" is guaranteed by IR1 (increment between events) and IR2 (send the timestamp; on receipt set the clock greater than both). The total order ⇒ orders by C, and breaks ties by "any arbitrary total ordering < of the processes" (usually the node id). The result is a logical clock: it has nothing to do with physical time.
Process A (id "a") Process B (id "b")
1 a1 L=1 send m(1) ------>
2 b1 L=1 local
3 b2 L=max(1,1)+1 = 2 receive m
4 a2 L=2 local
total order: (1,a) a1 < (1,b) b1 < (2,a) a2 < (2,b) b2
a2 and b2 both have L=2; the tie-break by id puts a2 first, by convention onlyReal scenario: Lamport's own example is distributed mutual exclusion: every process queues requests ordered by (timestamp, id), so all agree who goes next. Totally ordered broadcast and replicated state machines use the same idea; Raft terms and log indexes and Kafka partition offsets are "Lamport in spirit": a monotonically increasing number assigned along the causal path, here by one leader. Event-sourced aggregates use a per-aggregate version that is a Lamport clock with one writer.
What provides it:
| Product | Lamport-style counter | Scope |
|---|---|---|
| Raft (etcd, Consul) | Term + log index | Whole replicated log, one leader at a time |
| Kafka | Offset | One partition (Ordering & Partitioning) |
| PostgreSQL logical replication | LSN | One primary's WAL |
| Event store / aggregate version | version column | One aggregate |
Go snippet lamport | Tick, Receive, Compare | Any processes exchanging messages |
Fix / how to use it: use a Lamport clock when you need a deterministic total order consistent with causality (for example, to replay merged logs) and you do not need to know about concurrency. Put the node id in the timestamp so ties are deterministic. The Go lamport package is 60 lines.
Vector clocks: compare, merge, prune, actor ids Must-know
In plain words: each process keeps a list "the latest event I know of from every process". Bump your own slot on every event, send the whole list on messages, and on receive take the element-wise maximum, then bump your own slot. Two lists compare like this: if every entry of A is less than or equal to B's, A happened before B; if each side is bigger somewhere, they are concurrent.
Common misunderstanding: "Vector clocks are fine at any scale." Their size is one entry per actor id that ever wrote. With one actor per client or per short-lived container, the vector grows without bound. Dynamo uses server ids, not client ids, and still truncates; pruning then makes some descendants look concurrent.
Definition (Fidge 1988, Mattern 1989): for N processes, VC is a vector of N counters. Local or send event at i: VC[i]++. Receive with vector V: VC = max(VC, V) element-wise, then VC[i]++. Compare: A ≤ B iff A[k] ≤ B[k] for all k; A < B iff A ≤ B and A ≠ B; otherwise, if neither A ≤ B nor B ≤ A, A and B are concurrent. Merge is the element-wise max, which is commutative, associative and idempotent (a join-semilattice: Mattern's "form a lattice"). Vector order is isomorphic to happened-before: A < B exactly when event A is in the causal history of B. Prune drops entries (usually the least recently updated) to bound size, at the cost of false concurrency.
A B C
1 a1 [A:1] send ------->
2 b1 max([B:0],[A:1]) +B -> [A:1 B:1]
3 b2 [A:1 B:2] send ------->
4 a2 [A:2]
5 c1 [C:1]
6 c2 max([C:1],[A:1 B:2]) +C -> [A:1 B:2 C:2]
compare a1 [A:1] vs c2 [A:1 B:2 C:2]: every slot <= -> before
compare a2 [A:2] vs c2 [A:1 B:2 C:2]: A bigger left, B,C right -> concurrentReal scenario: detecting that two replicas of a shopping cart were updated independently during a partition (Dynamo); causal delivery in group chat (deliver a message only when its vector says all its causes have arrived); race detection (Go's race detector is built on ThreadSanitizer, which uses vector clocks between goroutines); distributed debugging and consistent snapshots (Mattern's paper computes a consistent global snapshot with them).
What provides it:
| Product / tool | Vector entries are | Size control |
|---|---|---|
| Amazon Dynamo (2007 paper) | (node, counter) per coordinating node | "When the number of (node, counter) pairs in the vector clock reaches a threshold (say 10), the oldest pair is removed" |
| Riak KV (vector clock mode) | Per vnode actor | small_vclock 50, big_vclock 50, young_vclock 20, old_vclock 86400 (documented as one day) |
| Go race detector (ThreadSanitizer) | Per goroutine / thread | Runtime-managed |
Go snippet vclock | Actor id string | Prune(PrunePolicy, now) mirrors Riak's four knobs |
Fix / how to use it: choose actor ids that are few and stable (servers or devices, not requests); merge on every receive; compare before overwriting; budget for pruning, and when pruning, prefer false conflicts (siblings) over silent overwrites. The Go vclock package has a property test that checks vector order against causal histories on random runs.
Version vectors vs vector clocks; dotted version vectors and siblings Must-know
In plain words: a vector clock stamps events in processes; a version vector stamps versions of a piece of data, with one entry per replica that accepted a write. When a client writes, it sends back the version vector it read (the causal context). Every stored version the context covers is replaced; every other stored version is concurrent and is kept as a sibling.
Common misunderstanding: "A version vector with one entry per server is enough." If two clients read the same version and both write through the same server, a plain per-server counter stamps the second write {A:2}, which dominates {A:1}, and the first write is silently lost. Adding client ids fixes it but makes vectors grow with clients. Dots fix it without growth.
Definition:
- Version vector: per data item, a map replica id → number of updates coordinated by that replica that this version includes. Compared and merged like vector clocks.
- Causal context: the (opaque) version vector a read returns and the next write must carry. Riak: "pass that opaque context object back to Riak when you update the object"; on HTTP it is the
X-Riak-Vclockheader even in DVV mode. - Dot: one event, a pair (replica, counter). A dotted version vector tags each stored value with the dot of the write that created it, plus the context it was based on. Riak's docs: "DVVs, on the other hand, identify each value with the update that created it."
- Sibling: one of several concurrent values stored for a key. Riak creates them when
allow_multistrue(the default for bucket types in Riak 2.0+). - Sibling explosion: duplicates of the same concurrent values accumulating because plain vector clocks cannot tell which value belongs to which update; DVVs bound the number of siblings to the number of truly concurrent updates.
Client 1 Client 2 Replica A (dotted version vectors)
1 GET k -> [], ctx {}
2 GET k -> [], ctx {}
3 PUT k "phone" ctx {} new dot (A,1); keeps nothing; siblings: (A,1) phone
4 PUT k "laptop" ctx {} ctx {} does not cover (A,1) -> keep it
5 new dot (A,2); siblings: (A,1) phone, (A,2) laptop
6 GET k -> [phone, laptop], ctx {A:2}
7 PUT k "phone+laptop" ctx {A:2} covers both dots -> drop both; new dot (A,3)
plain per-server counter at step 5: {A:2} > {A:1} -> "phone" silently lostReal scenario: the Amazon shopping cart (Dynamo's motivating case: "add to cart" must never be lost, so concurrent carts are merged); notes or contacts edited offline on a laptop and a phone (multi-device sync); Riak buckets for user profiles; mobile offline-first apps (each device is a replica); configuration edited in two regions of a multi-leader system.
What provides it:
| Product | Mechanism | Default | Knob |
|---|---|---|---|
| Riak KV 2.0+ | Vector clocks or DVV as causal context; siblings | Vector clocks; allow_mult=true for new bucket types | dvv_enabled, allow_mult, last_write_wins |
| Amazon Dynamo (paper) | Vector clock per version; client reconciles | Truncation at about 10 entries | Application merge (cart union) |
| Amazon DynamoDB | Not exposed; conditional writes instead | n/a | ConditionExpression on a version attribute |
| Apache Cassandra | No vectors; per-cell timestamps, LWW | Client or coordinator timestamp | USING TIMESTAMP; see Cassandra & ScyllaDB |
| CouchDB / PouchDB | Revision trees, conflicts kept | Deterministic winner + _conflicts | Application resolves |
| Laravel snippet | Version vector in a JSON column, siblings array | n/a | NoteSyncController |
Riak's warning about the alternative: "The problem with LWW is that it will necessarily drop some writes in the case of concurrent updates in the name of preventing sibling creation."
Fix / how to use it: store a version vector with every replicated object; require writes to carry the context from their read; keep siblings on concurrency; resolve with a domain rule (union of cart items, field-level merge, ask the user) or a CRDT. The Go versionvector package and the Laravel NoteSyncController implement the dotted rule.
Hybrid logical clocks (HLC) Must-know
In plain words: take the physical clock, but never let your timestamp go backwards and never let it fall behind a timestamp you have received. When the physical part does not move (clock stalled, stepped back, or behind a sender), bump a small counter instead.
Common misunderstanding: "HLC gives real-time order." It gives causal order (if a → b then HLC(a) < HLC(b)) and stays within the clock skew ε of physical time. Two causally unrelated events on hosts with skewed clocks can still be ordered against real time. Databases that use HLC add a max-offset rule and an uncertainty window to get stronger guarantees.
Definition (Kulkarni et al. 2014, Figure 5): state (l, c). Send or local event: l' = l; l = max(l', pt); c = (l == l') ? c + 1 : 0. Receive of (l.m, c.m): l = max(l', l.m, pt), and c is max(c, c.m) + 1 if all three are equal, c + 1 if only l' matches, c.m + 1 if only l.m matches, otherwise 0. Theorems: e → f implies (l.e, c.e) < (l.f, c.f); l.f ≥ pt.f; |l.f − pt.f| ≤ ε (bounded drift); c stays small. "HLC fits in to 64 bits NTP timestamp format": the paper uses 48 bits of physical time and 16 bits of counter.
Node A (physical .103) Node B (physical .101, 2 ms behind)
1 write x: l=max(0,.103)=.103 c=0 -> (.103,0) send ------>
2 receive: l=max(0,.103,.101)=.103, l==l.m -> c=0+1 -> (.103,1)
3 write y: pt .101 < l -> l stays .103, c=2 -> (.103,2)
4 ... pt reaches .104: next event (.104,0), counter resets
wall-clock LWW: x(.103) beats y(.101) -> y lost; HLC: (.103,0) < (.103,2) -> y winsReal scenario: MVCC timestamps in a distributed SQL database; ordering an audit log written by many app servers; snapshot reads "as of" a time across shards; causal ordering of events across microservices that pass a timestamp header; replacing created_at as a sort key in a multi-region outbox.
What provides it:
| Product | HLC use | Skew rule | Error / behaviour |
|---|---|---|---|
| CockroachDB | Every transaction and MVCC version; "HLC time is always greater than or equal to the wall time" | --max-offset, "Default: 500ms"; a node out of sync with at least half the cluster "by 80% of the maximum offset allowed, it crashes immediately" | ReadWithinUncertaintyIntervalError (SQLSTATE 40001, retry) |
| YugabyteDB | "YugabyteDB uses hybrid logical clocks (HLC) based on the hybrid time algorithm" | A maximum clock skew; "the conflict resolution depends on the maximum clock skew in the cluster" | More conflicts or latency when skew is large |
| MongoDB | Cluster time: a logical timestamp gossiped by every node and driver | Signed $clusterTime | Causal sessions use afterClusterTime |
Go snippet hlc | Now, Update, Compare | maxOffset | ErrClockOffset |
| Laravel snippet | HybridLogicalClock in a locked row | maxOffsetMs 500 | RuntimeException |
Fix / how to use it: use HLC when you want sortable timestamps that look like time, respect causality and survive clock steps; pass the HLC on every inter-service message and call Update on receipt; reject (or alert on) remote timestamps further ahead than your max offset so one bad clock cannot drag the fleet into the future.
TrueTime, uncertainty intervals, commit wait and external consistency Important
In plain words: instead of pretending the clock is right, Spanner's clock says "true time is somewhere between earliest and latest". A transaction picks a commit timestamp at latest and then simply waits until earliest has passed it before telling anyone it committed. After that wait, no later transaction anywhere can get a smaller timestamp.
Common misunderstanding: "Spanner has perfectly synchronised clocks." It has bounded uncertainty (GPS and atomic-clock time masters), typically a few milliseconds, and pays for it on every read-write commit by waiting. If the bound is violated, the guarantee is gone; the design makes violation very unlikely, not impossible.
Definition (Spanner, OSDI 2012): TT.now() returns a TTinterval [earliest, latest] guaranteed to contain the absolute time of the call; TT.after(t) and TT.before(t) test against it. The uncertainty ε "is typically a sawtooth function of time, varying from about 1 to 7 ms over each poll interval" (poll interval 30 s, drift budget 200 µs/s). Commit wait: the coordinator leader ensures "clients cannot see any data committed by Ti until TT.after(si) is true." The resulting external consistency (equivalent to linearizability for transactions): "if a transaction T1 commits before another transaction T2 starts, then T1's commit timestamp is smaller than T2's."
Spanner leader for T1 Any node, later
1 acquire locks; s1 = TT.now().latest
2 replicate commit record via Paxos
3 commit wait: loop until TT.after(s1) (about 2 x epsilon, typically under 10 ms)
4 release locks; reply "committed" to client
5 T2 starts after 4: TT.now().earliest > s1
6 so s2 = TT.now().latest > s1: real-time order keptReal scenario: a global bank ledger where a transfer in Europe must be visible to an audit in the US that starts after the transfer's acknowledgement; consistent snapshot reads across continents without locking (read at a timestamp); schema changes at a future timestamp.
What provides it:
| Product | Clock | Real-time guarantee | Cost |
|---|---|---|---|
| Google Spanner / Cloud Spanner | TrueTime | External consistency | Commit wait per read-write transaction |
| CockroachDB | HLC + max offset | Serializable; single-key linearizability only within the offset bound | Uncertainty restarts |
| YugabyteDB | HLC (hybrid time) + max skew | Snapshot / serializable within the bound | Read restarts |
| Your own service on an error-bounded time source | The source's reported interval | Only if you implement commit wait yourself | A wait per critical write |
Fix / how to use it: you rarely implement TrueTime; you choose a database that has it or emulate it: if your time source reports an error bound, you can implement commit wait yourself for a small number of critical writes. The deeper consistency discussion is in Consistency Models.
Causal consistency in practice: COPS dependencies and MongoDB causal sessions Important
In plain words: a causally consistent store promises that if you saw (or wrote) X before writing Y, nobody will ever see Y without X. To keep that promise the store tracks what each write depended on, as explicit dependencies (COPS) or as a timestamp the client carries (MongoDB cluster time).
Common misunderstanding: "Causal consistency is automatic when I read from the primary." It is a property of a session across replicas. In MongoDB it holds only inside a causally consistent session and only with "majority" read and write concerns: "Only read operations with "majority" read concern and write operations with "majority" write concern guarantee causal consistency."
Definition: causal consistency: every process observes causally related writes in their causal order; concurrent writes may be seen in different orders. Causal+ (COPS) adds convergent conflict handling so replicas agree eventually. Dependency tracking: each write carries the versions it depends on. COPS's example: a photo upload followed by adding it to an album; "The reference 'depends on' the picture being saved", so a remote datacenter applies the album write only after the photo. COPS keeps only nearest dependencies to stay small. Cluster time (MongoDB): a logical timestamp propagated by servers and drivers; a causal session records the operationTime and clusterTime of each operation, and the next read in the session asks the replica to wait until it has applied that point (afterClusterTime).
Client (MongoDB causal session) Primary P Secondary S2
1 insert {sku: "A1"} w:"majority" ------> applies at T=100
2 <- operationTime 100, $clusterTime 100
3 find {sku: "A1"} rc:"majority" readPreference secondary, afterClusterTime 100 -->
4 has applied only T=95: waits
5 applies T=100, answers
6 <- the document: read-your-writes held even on a lagging secondaryReal scenario: a user posts then immediately reads their timeline from a replica; a photo and its album entry replicated to another datacenter; "reply before message" in chat; a profile change followed by a permission check served by another region; a second client that must see what the first one did (MongoDB lets you advance one session's cluster time from another: "A client can advance the cluster time and the operation time of one client session to be consistent with the operations of another client session").
What provides it:
| Product | Mechanism | How you turn it on |
|---|---|---|
| MongoDB 3.6+ | Causal sessions, cluster time | startSession({causalConsistency: true}); Go driver options.Session().SetCausalConsistency(true), AdvanceClusterTime, AdvanceOperationTime |
| COPS / COPS-GT (research) | Explicit nearest dependencies | Client library context |
| Session-token pattern (any store) | Client carries the last written version or LSN | See Consistency Models |
Fix / how to use it: for read-your-writes and "effects after causes" across replicas, carry a token (cluster time, LSN, HLC) from the write to the next read and make the replica wait or redirect. The client-centric guarantees are taught in depth in Consistency Models.
Interval tree clocks and bloom clocks Good to know
In plain words: both fix the "one slot per participant" problem of vector clocks. Interval tree clocks let participants split (fork) and merge (join) their identity, so you never need a global list of ids. Bloom clocks hash events into a fixed-size counter array and answer "probably before" with a known false-positive rate.
Common misunderstanding: "These are drop-in replacements." ITC needs a fork/join discipline for identities; bloom clocks can say "comparable" when events are actually concurrent (false positives), although "If two clocks are not comparable, the bloom clock can always deduce it, i.e. false negatives are not possible."
Definition: Interval tree clock (Almeida, Baquero, Fonte, Interval Tree Clocks: A Logical Clock for Dynamic Systems, OPODIS 2008): a stamp is a pair (id, event) where the id is a share of the interval [0, 1) and the event is a tree of counters over that interval; operations are fork, event and join. It generalises both version vectors and vector clocks for a changing set of entities. Bloom clock (Ramabaja 2019): a counting Bloom filter of events; comparison is element-wise like a vector clock; "Unlike the vector clock, the space complexity of the bloom clock does not depend on the number of nodes in a system."
ITC: seed (1, 0)
1 fork -> A gets [0, 0.5), B gets [0.5, 1)
2 A event -> A's half of the event tree incremented
3 B fork -> B1 [0.5, 0.75), B2 [0.75, 1) (a new replica appears, no global registry)
4 B2 retires: join(B1, B2) -> B1 owns [0.5, 1) again, history keptReal scenario: peer-to-peer replication with devices joining and leaving (ITC); very large clusters or IoT fleets where an exact vector is too big and a probabilistic answer is acceptable for monitoring (bloom clock).
What provides it:
| Clock | Size depends on | Exact? | Implementations |
|---|---|---|---|
| Vector clock | Number of actors | Yes | Everywhere |
| Dotted version vector | Replicas that wrote the key | Yes | Riak (riak_dt, dvvset) |
| Interval tree clock | Fork/join history (adaptive) | Yes | Erlang itc, Haskell interval-tree-clock |
| Bloom clock | Chosen filter size and hash count | Probabilistic (no false negatives on "not comparable") | Research code |
Fix / how to use it: reach for ITC only when membership is genuinely dynamic and you cannot bound actor ids; reach for a bloom clock only for analysis or monitoring, never to decide whether to discard data.
Causality in messaging: causation id, correlation id, per-key ordering Must-know
In plain words: in a message-driven system the cheapest way to record causality is to write it down: every message carries the id of the message that caused it (causation id) and the id of the business flow it belongs to (correlation id). Brokers add ordering only per partition or per queue.
Common misunderstanding: "Kafka keeps my events in order." Kafka orders records within one partition; records for different keys on different partitions, or from different producers, have no order. A consumer that handles OrderPaid and OrderShipped from two topics can see them in either order. See Ordering & Partitioning.
Definition: Correlation id: an id shared by every message and log line of one business flow (one checkout). Causation id: on each message, the message id of its direct cause. Together they reconstruct the happened-before tree of a flow exactly, without clocks. Per-key ordering: partitioning by a key (order id) so all events of one entity travel through one ordered channel; it gives a Lamport-like total order per key and nothing across keys.
message id type correlation causation partition key
1 m1 PlaceOrder c-77 (none) order-9
2 m2 OrderPlaced c-77 m1 order-9
3 m3 ChargeCard c-77 m2 order-9
4 m4 ReserveStock c-77 m2 sku-123 <- other partition
5 m5 PaymentSucceeded c-77 m3 order-9
m3 || m4 (both caused by m2): no consumer may assume an order between themReal scenario: reconstructing an incident timeline across 12 services; detecting that a compensation ran before the step it compensates; deduplicating a retried command (same message id) versus a new one; a saga that must not ship before payment even though the two events arrive on different topics.
What provides it:
| Product | Ordering unit | Causality metadata |
|---|---|---|
| Kafka | Partition (key hash) | Record headers you add (correlation_id, causation_id, traceparent) |
| RabbitMQ | Single queue, single consumer | correlation_id and message_id AMQP properties |
| Redis Streams | One stream | Entry fields you add; entry id is a per-stream sequence |
| OpenTelemetry | Trace / span tree | traceparent parent span id = causation for spans |
| Laravel queues | Per queue, not guaranteed with many workers | Context values propagated into jobs |
Fix / how to use it: stamp every message with message id, correlation id and causation id at creation (outbox row); partition by the entity whose order matters; make consumers check preconditions (state machine) instead of assuming arrival order; trace propagation details are in Messaging Observability.
Last-writer-wins, conflict detection and multi-leader replication Must-know
In plain words: last-writer-wins (LWW) keeps the version with the largest timestamp and throws the rest away. It always converges and never asks anyone, which is why it is popular, and it silently loses every concurrent write and every write from a host whose clock is behind.
Common misunderstanding: "LWW keeps the newest data." It keeps the data with the largest timestamp. With skew, the causally newer write can carry the smaller timestamp (see the HLC diagram); with true concurrency, there is no "newest" at all, and half the writes vanish. LWW is safe for immutable or insert-only data, caches and sessions; Riak's docs list exactly those cases.
Definition: Last-writer-wins: a conflict resolution rule choosing the version with the maximum (timestamp, tie-break). Conflict detection: deciding, before resolution, that two versions are concurrent; requires version vectors (or a CRDT's own metadata), not timestamps. Multi-leader replication: several replicas accept writes for the same data (multi-region, offline clients); conflicts are inevitable and must be detected and resolved. Topology and resolution strategies are owned by Replication Topologies.
Region EU (clock +2 s) Region US (clock correct)
1 10:00:02 set title="Draft" ----> applied
2 10:00:00.5 user reads "Draft", sets title="Final"
3 receives "Final" @10:00:00.5 LWW: 10:00:02 > 10:00:00.5 -> keep "Draft"
4 anti-entropy sends "Draft" to US US also switches to "Draft"
both regions converge on the older value; "Final" is lost with no error (Go test: before/lww_test.go)
with version vectors: "Final" has ctx {EU:1} covering "Draft" -> "Final" wins everywhereReal scenario: a multi-region user profile in a database that resolves by timestamp; Cassandra counters and cells written by app servers with skewed clocks; offline mobile edits synced later; DNS or config written from two control planes; collaborative editing (where CRDTs or OT replace LWW).
What provides it:
| Product | Default conflict rule | Detection available |
|---|---|---|
| Apache Cassandra / ScyllaDB | LWW per cell by write timestamp | No (use LWT for compare-and-set) |
| Riak KV 2.0+ | Siblings (allow_mult=true) | Yes: vector clocks or DVV |
| CouchDB | Deterministic winning revision, conflicts kept | Yes: _conflicts |
| Amazon DynamoDB | Last write to an item wins unless the write is conditional | ConditionExpression on a version attribute |
| PostgreSQL logical replication (multi-writer setups) | Depends on extension (for example pglogical / BDR); often last update wins | Extension-specific |
| Automerge / Yjs | CRDT merge | Built in (see CRDTs) |
Fix / how to use it: use LWW only where losing a concurrent write is acceptable, and then use an HLC rather than raw wall time; for everything else detect with version vectors and resolve with a domain merge or a CRDT; record discarded siblings in an audit table if you must resolve automatically.
Mechanics
Sizes and costs
| Clock | Bytes per timestamp | Grows with | Comparison cost | Merge cost |
|---|---|---|---|---|
| Wall / monotonic | 8 | Nothing | O(1) | n/a |
| Lamport (time, node) | 8 + id | Nothing | O(1) | O(1) |
| HLC (48 + 16 bits) | 8 | Nothing | O(1) | O(1) |
| Vector clock | about 8 + id per actor | Every actor that ever wrote | O(N) | O(N) |
| Version vector + dots | 8 + id per replica, plus one dot per sibling | Replicas that wrote the key (bounded by replication factor) | O(R) | O(R + siblings) |
| TrueTime interval | 16 | Nothing | O(1) | n/a, plus wait about 2ε |
| COPS dependencies | One (key, version) per nearest dependency | Dependencies since the last write | O(deps) at apply time | n/a |
Knobs
| Product | Knob | Default | Effect |
|---|---|---|---|
| CockroachDB | --max-offset | 500ms | Upper bound on clock offset; exceeding 80% of it against half the cluster crashes the node; larger values mean more uncertainty restarts |
| Riak KV | allow_mult | true for new bucket types (2.0+) | Keep siblings on concurrency |
| Riak KV | last_write_wins | false | Skip causality, keep the newest timestamp ("Setting both allow_mult and last_write_wins to true necessarily leads to unpredictable behavior") |
| Riak KV | dvv_enabled | false | Use dotted version vectors as causal context |
| Riak KV | small_vclock / big_vclock / young_vclock / old_vclock | 50 / 50 / 20 / 86400 | Vector clock pruning thresholds |
| MongoDB | causalConsistency session option | Driver-specific; set it explicitly | Track operation and cluster time |
| MongoDB | readConcern / writeConcern | Per deployment | Causal guarantees need "majority" / "majority" |
| Google NTP | Leap smear | 24-hour linear, noon to noon UTC | About 11.6 ppm frequency change |
| chrony | makestep, maxslewrate | Distribution-specific | When to step instead of slew; slew limit |
Go snippet hlc | maxOffset | caller-chosen | Reject remote timestamps too far ahead |
Error messages you will actually see
| Source | Message (verbatim or shape) | Meaning | Action |
|---|---|---|---|
| CockroachDB | TransactionRetryWithProtoRefreshError: ReadWithinUncertaintyIntervalError: read at time ... encountered previous write with future timestamp ... within uncertainty interval | A value written inside your read's uncertainty window | Retry the transaction (SQLSTATE 40001); keep clocks tight |
| CockroachDB | Node log: clock offset exceeded, node shuts down | Its clock left the max-offset bound | Fix NTP/chrony, restart |
| Go | A panic from rand.Int63n fed a negative duration ("rand.Int63n promptly panics if its argument is negative") | Wall clock went backwards (Cloudflare 2017) | Use monotonic readings; check for negative durations |
| Riak KV HTTP | 300 Multiple Choices with sibling list | Key has siblings | Fetch all, resolve, write with X-Riak-Vclock |
| Go snippet | hlc: remote wall time exceeds max clock offset | Sender's clock too far ahead | Drop or quarantine the message, alert |
| Laravel snippet | HTTP 409 with siblings | Concurrent device edits | Show a merge UI, push with merged context |
Go
The Go module academy/vector-clocks-causality is standard library only. Every package has tests, several of them property-style: they generate random executions and check the clock against an independent oracle.
Before
A last-writer-wins register stamped with each replica's wall clock. It works on one machine; the test shows a replica with a fast clock winning against a causally newer write, and both replicas converging on the lost value.
// Package before shows the design most teams start with: a replicated
// register that resolves conflicts by wall-clock timestamp (last writer wins).
// It compiles and works on one machine; across machines it silently drops
// writes whenever clocks disagree or two writes are concurrent.
package before
import (
"sync"
"time"
)
// Clock returns the replica's wall-clock time. In production it is time.Now.
type Clock func() time.Time
// Version is what a replica stores and ships to its peers.
type Version struct {
Value string
WallAt time.Time // taken from the writing replica's wall clock
Replica string
}
// Register is one replica of a last-writer-wins register.
type Register struct {
mu sync.Mutex
name string
clock Clock
current Version
}
// NewRegister creates a replica with its own (possibly skewed) clock.
func NewRegister(name string, clock Clock) *Register {
return &Register{name: name, clock: clock}
}
// Put stamps the value with the local wall clock.
func (r *Register) Put(v string) Version {
r.mu.Lock()
defer r.mu.Unlock()
r.current = Version{Value: v, WallAt: r.clock().Round(0), Replica: r.name}
return r.current
}
// Apply merges a version received from a peer: the larger timestamp wins,
// ties broken by replica name. The loser is discarded without a trace.
func (r *Register) Apply(in Version) {
r.mu.Lock()
defer r.mu.Unlock()
if in.WallAt.After(r.current.WallAt) ||
(in.WallAt.Equal(r.current.WallAt) && in.Replica > r.current.Replica) {
r.current = in
}
}
// Get returns the surviving value.
func (r *Register) Get() string {
r.mu.Lock()
defer r.mu.Unlock()
return r.current.Value
}package before
import (
"testing"
"time"
)
// A replica whose clock runs 2 s fast wins against a write that really
// happened later and was based on its value: the causally newer write is lost.
func TestSkewedClockLosesCausallyNewerWrite(t *testing.T) {
base := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
fast := NewRegister("eu", func() time.Time { return base.Add(2 * time.Second) })
slow := NewRegister("us", func() time.Time { return base.Add(500 * time.Millisecond) })
v1 := fast.Put("draft") // stamped 10:00:02.000 by a fast clock
slow.Apply(v1) // us sees "draft"
v2 := slow.Put("final") // a later edit, made after reading "draft"
fast.Apply(v2) // stamped 10:00:00.500: older on paper
if got := fast.Get(); got != "draft" {
t.Fatalf("expected LWW to keep the skewed write, got %q", got)
}
slow.Apply(v1) // anti-entropy re-sends v1: both replicas converge...
if got := slow.Get(); got != "draft" {
t.Fatalf("replicas should converge on the skewed write, got %q", got)
}
// ...and "final" is gone everywhere, with no error and no sibling.
}After
Lamport clock with Tick, Receive and a total-order Compare (time, then node id). The test checks the Clock Condition on 200 random runs and shows that independent events still come out "ordered".
// Package lamport implements Lamport's 1978 logical clock (rules IR1 and IR2)
// and the total order obtained by breaking ties with the process id.
package lamport
import (
"cmp"
"sync"
)
// Timestamp is a Lamport time plus the id of the process that produced it.
type Timestamp struct {
Time uint64
Node string
}
// Compare orders timestamps totally: by Time, then by Node (the tie-break).
// If a happened-before b then Compare(a, b) < 0; the converse does not hold.
func Compare(a, b Timestamp) int {
if c := cmp.Compare(a.Time, b.Time); c != 0 {
return c
}
return cmp.Compare(a.Node, b.Node)
}
// Clock is one process's logical clock. Safe for concurrent use.
type Clock struct {
mu sync.Mutex
node string
t uint64
}
// New returns a clock for the named process.
func New(node string) *Clock { return &Clock{node: node} }
// Tick records a local or send event (IR1) and returns its timestamp.
// The returned value is what a sender puts on the message (IR2a).
func (c *Clock) Tick() Timestamp {
c.mu.Lock()
defer c.mu.Unlock()
c.t++
return Timestamp{Time: c.t, Node: c.node}
}
// Receive records the receipt of a message stamped remote (IR2b): the clock
// moves past both its own value and the message's.
func (c *Clock) Receive(remote Timestamp) Timestamp {
c.mu.Lock()
defer c.mu.Unlock()
c.t = max(c.t, remote.Time) + 1
return Timestamp{Time: c.t, Node: c.node}
}
// Now reads the clock without creating an event.
func (c *Clock) Now() uint64 {
c.mu.Lock()
defer c.mu.Unlock()
return c.t
}package lamport
import (
"math/rand/v2"
"slices"
"testing"
)
// Clock Condition: if a -> b then C(a) < C(b), checked on random executions.
func TestClockConditionOnRandomRuns(t *testing.T) {
r := rand.New(rand.NewPCG(1, 2))
for run := 0; run < 200; run++ {
nodes := []*Clock{New("a"), New("b"), New("c")}
last := make([]Timestamp, 3)
for step := 0; step < 50; step++ {
i := r.IntN(3)
if r.IntN(2) == 0 {
prev := last[i]
last[i] = nodes[i].Tick()
if Compare(prev, last[i]) >= 0 {
t.Fatalf("local order violated: %v then %v", prev, last[i])
}
continue
}
j := (i + 1 + r.IntN(2)) % 3
sent := nodes[i].Tick()
last[i] = sent
got := nodes[j].Receive(sent)
if Compare(sent, got) >= 0 {
t.Fatalf("send %v not before receive %v", sent, got)
}
last[j] = got
}
}
}
// Lamport order cannot reveal concurrency: two independent events still
// compare as ordered, decided only by the tie-break or by chance.
func TestConcurrentEventsLookOrdered(t *testing.T) {
a, b := New("a"), New("b")
ea := a.Tick() // {1 a}
eb := b.Tick() // {1 b}, never communicated with a
if Compare(ea, eb) >= 0 {
t.Fatalf("tie-break should order a before b")
}
evs := []Timestamp{eb, ea, b.Tick(), a.Receive(eb)}
slices.SortFunc(evs, Compare)
want := []Timestamp{{1, "a"}, {1, "b"}, {2, "a"}, {2, "b"}}
if !slices.Equal(evs, want) {
t.Fatalf("total order = %v, want %v", evs, want)
}
}Vector clock with Tick, Merge, Compare (equal, before, after, concurrent), Descends and a Riak-style Prune. The property test builds causal histories (sets of event ids) next to the clocks on random runs and asserts that vector order equals history inclusion; another checks that merge is commutative, associative and idempotent; the pruning test shows a true descendant turning "concurrent" after its oldest entry is dropped.
// Package vclock implements vector clocks (Fidge 1988, Mattern 1989):
// one counter per actor id, element-wise max on merge, and a comparison that
// tells before, after, equal and concurrent apart. Entries carry the wall
// time of their last update so the clock can be pruned the way Dynamo and
// Riak do; pruning trades exactness for size.
package vclock
import (
"fmt"
"maps"
"slices"
"strings"
"time"
)
// Order is the result of comparing two clocks.
type Order int
const (
Equal Order = iota // same causal history
Before // a happened-before b
After // b happened-before a
Concurrent // neither saw the other
)
func (o Order) String() string {
return [...]string{"equal", "before", "after", "concurrent"}[o]
}
// Entry is one actor's counter plus when it last moved (for pruning only).
type Entry struct {
Counter uint64
Updated time.Time
}
// Clock maps actor id -> entry. A missing actor means counter 0.
type Clock map[string]Entry
// Copy returns an independent clock; clocks travel on messages, so never
// share the map between sender and receiver.
func (c Clock) Copy() Clock { return maps.Clone(c) }
// Tick records a local or send event by actor at wall time now.
func (c Clock) Tick(actor string, now time.Time) {
e := c[actor]
e.Counter++
e.Updated = now
c[actor] = e
}
// Merge folds other into c: element-wise max. Call it on receive, then Tick.
func (c Clock) Merge(other Clock) {
for id, e := range other {
cur, ok := c[id]
if !ok || e.Counter > cur.Counter {
c[id] = e
} else if e.Counter == cur.Counter && e.Updated.After(cur.Updated) {
cur.Updated = e.Updated
c[id] = cur
}
}
}
// Compare reports how a relates to b.
// a <= b iff every counter of a is <= the matching counter of b.
func Compare(a, b Clock) Order {
aLE, bLE := true, true
for id, e := range a {
if e.Counter > b[id].Counter {
aLE = false
}
}
for id, e := range b {
if e.Counter > a[id].Counter {
bLE = false
}
}
switch {
case aLE && bLE:
return Equal
case aLE:
return Before
case bLE:
return After
default:
return Concurrent
}
}
// Descends reports whether a has seen everything b has (a >= b).
func Descends(a, b Clock) bool {
o := Compare(a, b)
return o == After || o == Equal
}
// PrunePolicy mirrors Riak's four bucket properties: small_vclock,
// big_vclock, young_vclock and old_vclock.
type PrunePolicy struct {
Small int // never prune a clock with at most this many entries
Big int // always prune down to this many entries
Young time.Duration // never drop an entry updated more recently than this
Old time.Duration // drop entries not updated for longer than this
}
// Prune removes the least recently updated entries according to p and
// returns the dropped actor ids. A pruned clock can make a descendant look
// concurrent (a false conflict, resolved as siblings) but never the reverse
// for entries that were kept.
func (c Clock) Prune(p PrunePolicy, now time.Time) []string {
if len(c) <= p.Small {
return nil
}
ids := slices.Collect(maps.Keys(c))
slices.SortFunc(ids, func(x, y string) int {
if d := c[x].Updated.Compare(c[y].Updated); d != 0 {
return d
}
return strings.Compare(x, y)
})
var dropped []string
for _, id := range ids { // oldest first
age := now.Sub(c[id].Updated)
if age < p.Young || len(c) <= p.Small {
break
}
if len(c) > p.Big || age > p.Old {
delete(c, id)
dropped = append(dropped, id)
}
}
return dropped
}
// String prints the clock in a stable order, e.g. [a:2 b:1].
func (c Clock) String() string {
ids := slices.Sorted(maps.Keys(c))
parts := make([]string, len(ids))
for i, id := range ids {
parts[i] = fmt.Sprintf("%s:%d", id, c[id].Counter)
}
return "[" + strings.Join(parts, " ") + "]"
}package vclock
import (
"fmt"
"maps"
"math/rand/v2"
"testing"
"time"
)
var t0 = time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
func TestCompareBasics(t *testing.T) {
a := Clock{}
a.Tick("a", t0)
b := a.Copy()
b.Tick("b", t0)
c := a.Copy()
c.Tick("c", t0)
cases := []struct {
x, y Clock
want Order
}{
{a, a, Equal}, {a, b, Before}, {b, a, After}, {b, c, Concurrent},
}
for _, tc := range cases {
if got := Compare(tc.x, tc.y); got != tc.want {
t.Errorf("Compare(%v,%v)=%v want %v", tc.x, tc.y, got, tc.want)
}
}
m := b.Copy()
m.Merge(c)
if Compare(b, m) != Before || Compare(c, m) != Before {
t.Fatalf("merge must dominate both inputs: %v", m)
}
}
// Property: on random executions, vector-clock order equals the true
// happened-before relation, computed independently from causal histories
// (the set of all events each event has seen).
func TestVectorOrderMatchesCausalHistory(t *testing.T) {
r := rand.New(rand.NewPCG(7, 11))
type event struct {
vc Clock
hist map[string]bool
}
for run := 0; run < 100; run++ {
actors := []string{"a", "b", "c"}
clocks := map[string]Clock{"a": {}, "b": {}, "c": {}}
hists := map[string]map[string]bool{"a": {}, "b": {}, "c": {}}
var evs []event
record := func(actor string) {
clocks[actor].Tick(actor, t0)
id := fmt.Sprintf("%s%d", actor, clocks[actor][actor].Counter)
hists[actor][id] = true
evs = append(evs, event{clocks[actor].Copy(), maps.Clone(hists[actor])})
}
for step := 0; step < 30; step++ {
from := actors[r.IntN(3)]
record(from)
if r.IntN(2) == 0 {
continue
}
to := actors[r.IntN(3)]
if to == from {
continue
}
msg := evs[len(evs)-1]
clocks[to].Merge(msg.vc)
maps.Copy(hists[to], msg.hist)
record(to)
}
for i, x := range evs {
for j, y := range evs {
if i == j {
continue
}
subset := true
for id := range x.hist {
if !y.hist[id] {
subset = false
}
}
want := subset && len(x.hist) < len(y.hist)
got := Compare(x.vc, y.vc) == Before
if got != want {
t.Fatalf("run %d: %v vs %v: vc before=%v, history before=%v", run, x.vc, y.vc, got, want)
}
}
}
}
}
func TestMergeIsCommutativeAssociativeIdempotent(t *testing.T) {
r := rand.New(rand.NewPCG(3, 5))
rnd := func() Clock {
c := Clock{}
for _, id := range []string{"a", "b", "c", "d"} {
if n := r.IntN(4); n > 0 {
c[id] = Entry{Counter: uint64(n), Updated: t0}
}
}
return c
}
for i := 0; i < 500; i++ {
x, y, z := rnd(), rnd(), rnd()
xy := x.Copy()
xy.Merge(y)
yx := y.Copy()
yx.Merge(x)
if Compare(xy, yx) != Equal {
t.Fatal("merge not commutative")
}
l := xy.Copy()
l.Merge(z)
rr := y.Copy()
rr.Merge(z)
rx := x.Copy()
rx.Merge(rr)
if Compare(l, rx) != Equal {
t.Fatal("merge not associative")
}
xx := x.Copy()
xx.Merge(x)
if Compare(xx, x) != Equal {
t.Fatal("merge not idempotent")
}
}
}
func TestPruneDropsOldestAndCanFakeConcurrency(t *testing.T) {
c := Clock{}
for i, id := range []string{"n1", "n2", "n3", "n4"} {
c.Tick(id, t0.Add(time.Duration(i)*time.Hour))
}
desc := c.Copy()
desc.Tick("n4", t0.Add(5*time.Hour))
now := t0.Add(48 * time.Hour)
dropped := desc.Prune(PrunePolicy{Small: 2, Big: 3, Young: time.Second, Old: 72 * time.Hour}, now)
if len(dropped) != 1 || dropped[0] != "n1" {
t.Fatalf("dropped %v, want [n1]", dropped)
}
if got := Compare(c, desc); got != Concurrent {
t.Fatalf("after pruning, a true descendant should look concurrent, got %v", got)
}
}Version vectors with dots (the dotted-version-vector rule): Get returns siblings and a context, Put drops covered siblings and adds a new dot, Sync merges replicas. The property test runs random reads, writes (some blind) and syncs across three replicas, then checks that the surviving siblings are exactly the writes no later context covered: nothing acknowledged is lost, nothing obsolete survives.
// Package versionvector implements per-replica version vectors with dots,
// the scheme Riak calls dotted version vectors (Preguica et al. 2010).
//
// A version vector has one entry per *replica* (server), not per client or
// event, so its size is bounded by the replication factor. Each stored value
// (sibling) is tagged with the single event that created it, its dot. A write
// carries the causal context the client read; every sibling whose dot is
// covered by that context is obsolete, every other sibling is concurrent and
// is kept.
package versionvector
import (
"cmp"
"maps"
"slices"
"sync"
)
// VV is a version vector: replica id -> highest event counter seen.
type VV map[string]uint64
// Covers reports whether the vector already includes dot d.
func (v VV) Covers(d Dot) bool { return v[d.Replica] >= d.Counter }
// Merge returns the element-wise maximum of a and b.
func Merge(a, b VV) VV {
out := maps.Clone(a)
if out == nil {
out = VV{}
}
for id, n := range b {
out[id] = max(out[id], n)
}
return out
}
// Dot names one write event: the n-th write coordinated by Replica.
type Dot struct {
Replica string
Counter uint64
}
// Sibling is one concurrent value of a key.
type Sibling struct {
Dot Dot
Value string
}
// Object is what a replica stores for a key: the concurrent siblings plus
// the causal context (everything this replica has seen for the key).
type Object struct {
Siblings []Sibling
Context VV
}
func (o Object) clone() Object {
return Object{Siblings: slices.Clone(o.Siblings), Context: maps.Clone(o.Context)}
}
// Replica is one server holding copies of keys.
type Replica struct {
mu sync.Mutex
id string
data map[string]Object
}
// NewReplica returns an empty replica with the given id (its actor id).
func NewReplica(id string) *Replica { return &Replica{id: id, data: map[string]Object{}} }
// Get returns all siblings and the opaque context the client must send back
// on its next write (Riak: X-Riak-Vclock / vclock).
func (r *Replica) Get(key string) ([]string, VV) {
r.mu.Lock()
defer r.mu.Unlock()
o := r.data[key]
vals := make([]string, len(o.Siblings))
for i, s := range o.Siblings {
vals[i] = s.Value
}
ctx := maps.Clone(o.Context)
if ctx == nil {
ctx = VV{}
}
return vals, ctx
}
// Put coordinates a client write. ctx is the context from the client's last
// Get (empty for a blind write). It returns the dot of the new sibling.
func (r *Replica) Put(key string, ctx VV, value string) Dot {
r.mu.Lock()
defer r.mu.Unlock()
o := r.data[key].clone()
if o.Context == nil {
o.Context = VV{}
}
kept := o.Siblings[:0]
for _, s := range o.Siblings {
if !ctx.Covers(s.Dot) { // the client never saw it: concurrent, keep
kept = append(kept, s)
}
}
o.Context = Merge(o.Context, ctx)
o.Context[r.id]++
d := Dot{Replica: r.id, Counter: o.Context[r.id]}
o.Siblings = append(kept, Sibling{Dot: d, Value: value})
r.data[key] = o
return d
}
// Export returns a copy of the stored object for replication.
func (r *Replica) Export(key string) Object {
r.mu.Lock()
defer r.mu.Unlock()
return r.data[key].clone()
}
// Sync merges a peer's copy of key (anti-entropy or read repair).
// A sibling survives if both sides have it, or if the other side's context
// does not cover its dot (the other side simply has not seen it yet).
func (r *Replica) Sync(key string, in Object) {
r.mu.Lock()
defer r.mu.Unlock()
local := r.data[key]
has := func(list []Sibling, d Dot) bool {
return slices.ContainsFunc(list, func(s Sibling) bool { return s.Dot == d })
}
var out []Sibling
for _, s := range local.Siblings {
if has(in.Siblings, s.Dot) || !VV(in.Context).Covers(s.Dot) {
out = append(out, s)
}
}
for _, s := range in.Siblings {
if !has(out, s.Dot) && !VV(local.Context).Covers(s.Dot) {
out = append(out, s)
}
}
slices.SortFunc(out, func(a, b Sibling) int {
if c := cmp.Compare(a.Dot.Replica, b.Dot.Replica); c != 0 {
return c
}
return cmp.Compare(a.Dot.Counter, b.Dot.Counter)
})
r.data[key] = Object{Siblings: out, Context: Merge(local.Context, in.Context)}
}package versionvector
import (
"fmt"
"math/rand/v2"
"slices"
"testing"
)
// Two clients read the same (empty) context and write through the SAME
// replica. A plain per-replica version vector would stamp them {A:1} and
// {A:2}; the second would dominate and silently replace the first. Dots
// keep both as siblings until a client resolves them.
func TestConcurrentWritesThroughOneReplicaBecomeSiblings(t *testing.T) {
a := NewReplica("A")
_, ctx := a.Get("cart:42")
a.Put("cart:42", ctx, "phone") // client 1
a.Put("cart:42", ctx, "laptop") // client 2, same stale context
vals, merged := a.Get("cart:42")
if !slices.Equal(vals, []string{"phone", "laptop"}) {
t.Fatalf("siblings = %v", vals)
}
a.Put("cart:42", merged, "phone+laptop") // client 3 resolves
if vals, _ := a.Get("cart:42"); !slices.Equal(vals, []string{"phone+laptop"}) {
t.Fatalf("after resolve = %v", vals)
}
}
func TestSyncKeepsConcurrentAndDropsObsolete(t *testing.T) {
a, b := NewReplica("A"), NewReplica("B")
a.Put("k", VV{}, "v1")
b.Sync("k", a.Export("k"))
_, ctx := b.Get("k")
b.Put("k", ctx, "v2") // descends v1
a.Put("k", VV{}, "x") // blind write: concurrent with everything
a.Sync("k", b.Export("k"))
b.Sync("k", a.Export("k"))
va, _ := a.Get("k")
vb, _ := b.Get("k")
slices.Sort(va)
slices.Sort(vb)
if !slices.Equal(va, []string{"v2", "x"}) || !slices.Equal(va, vb) {
t.Fatalf("a=%v b=%v", va, vb)
}
}
// Property: after full anti-entropy, the surviving siblings are exactly the
// writes that no later write's context covered. Nothing acknowledged is lost
// and nothing obsolete survives, whatever the interleaving.
func TestNoLostUpdatesProperty(t *testing.T) {
r := rand.New(rand.NewPCG(21, 42))
for run := 0; run < 300; run++ {
reps := []*Replica{NewReplica("A"), NewReplica("B"), NewReplica("C")}
type write struct {
dot Dot
val string
}
var writes []write
var contexts []VV
for step := 0; step < 25; step++ {
switch r.IntN(3) {
case 0, 1: // a client reads from one replica and writes via another
_, ctx := reps[r.IntN(3)].Get("k")
if r.IntN(4) == 0 {
ctx = VV{} // blind write
}
val := fmt.Sprintf("w%d", step)
d := reps[r.IntN(3)].Put("k", ctx, val)
writes = append(writes, write{d, val})
contexts = append(contexts, ctx)
case 2:
x, y := reps[r.IntN(3)], reps[r.IntN(3)]
y.Sync("k", x.Export("k"))
}
}
for round := 0; round < 2; round++ {
for _, x := range reps {
for _, y := range reps {
y.Sync("k", x.Export("k"))
}
}
}
var want []string
for _, w := range writes {
obsolete := false
for _, c := range contexts {
if c.Covers(w.dot) {
obsolete = true
}
}
if !obsolete {
want = append(want, w.val)
}
}
slices.Sort(want)
for _, rep := range reps {
got, _ := rep.Get("k")
slices.Sort(got)
if !slices.Equal(got, want) {
t.Fatalf("run %d replica %s: got %v want %v", run, rep.id, got, want)
}
}
}
}Hybrid logical clock following Figure 5 of the HLC paper, plus a CockroachDB-style max-offset check. Tests: monotonic when the physical clock steps back, receive after send across skew, rejection of far-future timestamps, and a property test for happened-before and bounded drift.
// Package hlc implements the hybrid logical clock of Kulkarni et al. (2014):
// a timestamp (l, c) where l tracks the largest physical time heard so far
// and c is a small logical counter that orders events sharing the same l.
// If e happened-before f then (l.e, c.e) < (l.f, c.f), and l never drifts
// from physical time by more than the clock-synchronisation error.
//
// Like CockroachDB, this clock refuses remote timestamps that are further in
// the future than MaxOffset, instead of letting one bad clock drag every
// node forward.
package hlc
import (
"cmp"
"errors"
"fmt"
"sync"
"time"
)
// Timestamp is an HLC reading. Wall is Unix nanoseconds (wall clock, never
// the monotonic reading: it must be comparable across machines).
type Timestamp struct {
Wall int64
Logical uint32
}
// Compare orders timestamps lexicographically by (Wall, Logical).
func Compare(a, b Timestamp) int {
if c := cmp.Compare(a.Wall, b.Wall); c != 0 {
return c
}
return cmp.Compare(a.Logical, b.Logical)
}
func (t Timestamp) String() string {
return fmt.Sprintf("%d.%010d", t.Wall, t.Logical)
}
// ErrClockOffset is returned when a remote timestamp is too far ahead.
var ErrClockOffset = errors.New("hlc: remote wall time exceeds max clock offset")
// Clock is one node's HLC. Safe for concurrent use.
type Clock struct {
mu sync.Mutex
physical func() int64
maxOffset time.Duration
last Timestamp
}
// New returns a clock. physical is usually func() int64 { return time.Now().UnixNano() }.
// maxOffset <= 0 disables the offset check.
func New(physical func() int64, maxOffset time.Duration) *Clock {
return &Clock{physical: physical, maxOffset: maxOffset}
}
// Now timestamps a local or send event (Figure 5, "Send or local event").
func (c *Clock) Now() Timestamp {
c.mu.Lock()
defer c.mu.Unlock()
pt := c.physical()
if pt > c.last.Wall {
c.last = Timestamp{Wall: pt}
} else {
c.last.Logical++ // physical clock stalled or went backwards
}
return c.last
}
// Update timestamps the receipt of a message stamped remote
// (Figure 5, "Receive event of message m").
func (c *Clock) Update(remote Timestamp) (Timestamp, error) {
c.mu.Lock()
defer c.mu.Unlock()
pt := c.physical()
if c.maxOffset > 0 && remote.Wall-pt > c.maxOffset.Nanoseconds() {
return c.last, fmt.Errorf("%w: remote %d, local %d, max %s",
ErrClockOffset, remote.Wall, pt, c.maxOffset)
}
l := max(c.last.Wall, remote.Wall, pt)
switch {
case l == c.last.Wall && l == remote.Wall:
c.last.Logical = max(c.last.Logical, remote.Logical) + 1
case l == c.last.Wall:
c.last.Logical++
case l == remote.Wall:
c.last.Logical = remote.Logical + 1
default:
c.last.Logical = 0
}
c.last.Wall = l
return c.last, nil
}package hlc
import (
"errors"
"math/rand/v2"
"testing"
"time"
)
// manual is a settable physical clock for tests.
type manual struct{ t int64 }
func (m *manual) now() int64 { return m.t }
func TestMonotonicWhenPhysicalClockGoesBackwards(t *testing.T) {
pc := &manual{t: 1_000}
c := New(pc.now, 0)
a := c.Now()
pc.t = 400 // NTP step backwards
b := c.Now()
if Compare(a, b) >= 0 || b.Wall != 1_000 || b.Logical != 1 {
t.Fatalf("a=%v b=%v", a, b)
}
pc.t = 1_500
if d := c.Now(); d.Wall != 1_500 || d.Logical != 0 {
t.Fatalf("logical must reset once physical time catches up: %v", d)
}
}
func TestReceiveOrdersAfterSend(t *testing.T) {
fast, slow := &manual{t: 5_000}, &manual{t: 2_000}
a, b := New(fast.now, 0), New(slow.now, 0)
sent := a.Now()
got, err := b.Update(sent)
if err != nil || Compare(sent, got) >= 0 {
t.Fatalf("sent=%v got=%v err=%v", sent, got, err)
}
if got.Wall != 5_000 || got.Logical != 1 {
t.Fatalf("receiver adopts the sender's wall and bumps logical: %v", got)
}
}
func TestMaxOffsetRejectsFutureTimestamps(t *testing.T) {
pc := &manual{t: int64(10 * time.Second)}
c := New(pc.now, 500*time.Millisecond)
_, err := c.Update(Timestamp{Wall: int64(11 * time.Second)})
if !errors.Is(err, ErrClockOffset) {
t.Fatalf("want ErrClockOffset, got %v", err)
}
if _, err := c.Update(Timestamp{Wall: int64(10*time.Second + 400*time.Millisecond)}); err != nil {
t.Fatalf("400ms ahead is inside the bound: %v", err)
}
}
// Property: on random message exchanges between nodes with skewed, jumping
// physical clocks, every send is before its receive, every node's sequence is
// strictly increasing, and l - pt stays within the maximum skew.
func TestHappenedBeforeAndBoundedDrift(t *testing.T) {
r := rand.New(rand.NewPCG(9, 9))
const skew = int64(50 * time.Millisecond)
for run := 0; run < 100; run++ {
var now int64 = 1_700_000_000_000_000_000
offsets := []int64{0, r.Int64N(skew), -r.Int64N(skew)}
pcs := make([]func() int64, 3)
clocks := make([]*Clock, 3)
last := make([]Timestamp, 3)
for i := range clocks {
pcs[i] = func() int64 { return now + offsets[i] }
clocks[i] = New(pcs[i], 0)
}
for step := 0; step < 200; step++ {
now += r.Int64N(int64(time.Millisecond))
i := r.IntN(3)
ts := clocks[i].Now()
if Compare(last[i], ts) >= 0 {
t.Fatalf("node %d not monotonic: %v then %v", i, last[i], ts)
}
last[i] = ts
j := r.IntN(3)
if j == i {
continue
}
got, err := clocks[j].Update(ts)
if err != nil || Compare(ts, got) >= 0 {
t.Fatalf("send %v receive %v err %v", ts, got, err)
}
last[j] = got
if drift := got.Wall - pcs[j](); drift > 2*skew {
t.Fatalf("drift %d exceeds bound", drift)
}
}
}
}The lab program replays the page's three-process run:
// Command lab replays the chapter's three-process run and prints, for every
// event, its Lamport timestamp and vector clock, then classifies two pairs.
package main
import (
"fmt"
"time"
"academy/vector-clocks-causality/hlc"
"academy/vector-clocks-causality/lamport"
"academy/vector-clocks-causality/vclock"
)
type proc struct {
name string
lc *lamport.Clock
vc vclock.Clock
}
func main() {
t0 := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
p := map[string]*proc{}
for _, n := range []string{"A", "B", "C"} {
p[n] = &proc{name: n, lc: lamport.New(n), vc: vclock.Clock{}}
}
type msg struct {
lt lamport.Timestamp
vc vclock.Clock
}
events := map[string]vclock.Clock{}
local := func(n, label string) msg {
x := p[n]
lt := x.lc.Tick()
x.vc.Tick(n, t0)
events[label] = x.vc.Copy()
fmt.Printf("%-3s %-14s L=%d V=%v\n", label, n+" local/send", lt.Time, x.vc)
return msg{lt, x.vc.Copy()}
}
recv := func(n, label string, m msg) {
x := p[n]
lt := x.lc.Receive(m.lt)
x.vc.Merge(m.vc)
x.vc.Tick(n, t0)
events[label] = x.vc.Copy()
fmt.Printf("%-3s %-14s L=%d V=%v\n", label, n+" receive", lt.Time, x.vc)
}
a1 := local("A", "a1")
local("C", "c1")
recv("B", "b1", a1)
b2 := local("B", "b2")
local("A", "a2")
recv("C", "c2", b2)
fmt.Println("a1 vs c2:", vclock.Compare(events["a1"], events["c2"]))
fmt.Println("a2 vs c2:", vclock.Compare(events["a2"], events["c2"]))
fmt.Println("c1 vs b1:", vclock.Compare(events["c1"], events["b1"]))
// HLC: node B's clock is 3 ms behind A's, yet B's receive orders after A's send.
base := t0.UnixNano()
ha := hlc.New(func() int64 { return base + int64(3*time.Millisecond) }, 500*time.Millisecond)
hb := hlc.New(func() int64 { return base }, 500*time.Millisecond)
sent := ha.Now()
got, _ := hb.Update(sent)
fmt.Printf("HLC send=%v receive=%v ordered=%v\n", sent, got, hlc.Compare(sent, got) < 0)
}The Go angle
| Go feature | Use here | Note |
|---|---|---|
time.Now() | Wall + monotonic reading | Monotonic part used by Sub, Since, Before, After, Equal, Compare |
t.Round(0) | Strip the monotonic reading | Before storing, comparing across processes, or using as a map key |
t.UnixNano() | Wall time for HLC and LWW | Comparable across machines, subject to skew |
time.Since(start) | Durations | Safe across NTP steps (Go 1.9+) |
maps.Clone, maps.Keys, slices.Sorted | Copying and printing vectors | A vector shared between sender and receiver is a data race |
cmp.Compare | Lexicographic (time, node) and (wall, logical) | Deterministic tie-break |
math/rand/v2 with rand.NewPCG(seed) | Reproducible property tests | Fixed seeds make failures replayable |
sync.Mutex | Clock state | A clock is shared by every goroutine of the process |
go test -race | Race detector | Itself built on vector clocks (ThreadSanitizer) |
| MongoDB Go driver v2 | options.Session().SetCausalConsistency(true), sess.AdvanceClusterTime, sess.AdvanceOperationTime | Causal sessions across clients |
Laravel
Before
Multi-device sync where the device's edited_at decides. A phone with a fast clock wins every conflict and offline edits disappear.
<?php
namespace App\Http\Controllers\Before;
use App\Models\Note;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
/**
* Multi-device sync, first version: every device sends the note with the
* wall-clock time it was edited, and the newest timestamp wins.
*
* Problems: a phone whose clock is five minutes fast wins every conflict;
* two offline edits made on a laptop and a tablet are both "newest" on their
* own device and one is dropped without anyone being told.
*
* (Assumes an older Note model with an edited_at datetime cast.)
*/
class NoteController
{
public function update(Request $request, Note $note): JsonResponse
{
$data = $request->validate([
'body' => ['required', 'string'],
'edited_at' => ['required', 'date'],
]);
if ($note->edited_at === null || $note->edited_at->lt($data['edited_at'])) {
$note->forceFill([
'body' => $data['body'],
'edited_at' => $data['edited_at'],
])->save();
}
return response()->json($note);
}
}After
Schema: notes with a JSON version vector and a JSON siblings array, a per-node HLC state row, and an append-only audit log ordered by HLC:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('notes', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->index();
$table->text('body');
$table->json('version_vector'); // {"laptop-7f": 3, "phone-a2": 5}
$table->json('siblings'); // concurrent versions, 1 when clean
$table->timestamps();
});
Schema::create('hlc_clocks', function (Blueprint $table) {
$table->string('node_id', 64)->primary();
$table->unsignedBigInteger('wall_ms');
$table->unsignedInteger('logical');
});
Schema::create('audit_events', function (Blueprint $table) {
$table->uuid('event_id')->primary();
$table->uuid('correlation_id');
$table->uuid('causation_id')->nullable();
$table->string('action', 100);
$table->json('payload');
$table->unsignedBigInteger('hlc_wall');
$table->unsignedInteger('hlc_logical');
$table->string('node_id', 64);
$table->timestamp('recorded_at');
$table->index(['correlation_id', 'hlc_wall', 'hlc_logical', 'node_id']);
$table->index(['hlc_wall', 'hlc_logical', 'node_id']);
});
}
public function down(): void
{
Schema::dropIfExists('audit_events');
Schema::dropIfExists('hlc_clocks');
Schema::dropIfExists('notes');
}
};The same schema in SQL (PostgreSQL), with the query that reads one flow in causal-compatible order:
CREATE TABLE notes (
id bigserial PRIMARY KEY,
user_id bigint NOT NULL,
body text NOT NULL,
version_vector jsonb NOT NULL DEFAULT '{}', -- {"laptop-7f": 3, "phone-a2": 5}
siblings jsonb NOT NULL DEFAULT '[]',
created_at timestamptz, updated_at timestamptz
);
CREATE TABLE hlc_clocks (
node_id varchar(64) PRIMARY KEY,
wall_ms bigint NOT NULL,
logical integer NOT NULL
);
CREATE TABLE audit_events (
event_id uuid PRIMARY KEY,
correlation_id uuid NOT NULL,
causation_id uuid,
action varchar(100) NOT NULL,
payload jsonb NOT NULL,
hlc_wall bigint NOT NULL,
hlc_logical integer NOT NULL,
node_id varchar(64) NOT NULL,
recorded_at timestamptz NOT NULL -- for humans, never for ordering
);
CREATE INDEX audit_flow ON audit_events (correlation_id, hlc_wall, hlc_logical, node_id);
-- One flow, causes before effects (HLC order is a linear extension of happened-before)
SELECT event_id, causation_id, action, hlc_wall, hlc_logical, node_id
FROM audit_events
WHERE correlation_id = '0193f1e2-7c1a-7cc0-9a51-2f6b0d0e4a11'
ORDER BY hlc_wall, hlc_logical, node_id;
-- Concurrency check without the app: does device A's vector descend B's? (PostgreSQL)
SELECT bool_and(COALESCE((a.v ->> k)::int, 0) >= COALESCE((b.v ->> k)::int, 0)) AS a_descends_b
FROM (SELECT '{"laptop":3,"phone":5}'::jsonb AS v) a,
(SELECT '{"laptop":2,"phone":6}'::jsonb AS v) b,
LATERAL (SELECT jsonb_object_keys(a.v || b.v) AS k) keys; -- false: concurrentVersion vector helpers (compare, merge, increment, descends) on plain arrays so they round-trip through the 'array' cast:
<?php
namespace App\Support;
/**
* Version vector helpers for multi-device sync. Keys are actor ids (one per
* device that edits offline), values are that device's edit counters.
* Vectors are plain PHP arrays so they round-trip through Eloquent's
* 'array' cast and a JSON column unchanged.
*/
final class VersionVector
{
public const EQUAL = 'equal';
public const BEFORE = 'before';
public const AFTER = 'after';
public const CONCURRENT = 'concurrent';
/** @param array<string,int> $a @param array<string,int> $b */
public static function compare(array $a, array $b): string
{
$aLe = true;
$bLe = true;
foreach (array_keys($a + $b) as $actor) {
$x = (int) ($a[$actor] ?? 0);
$y = (int) ($b[$actor] ?? 0);
if ($x > $y) {
$aLe = false;
}
if ($y > $x) {
$bLe = false;
}
}
return match (true) {
$aLe && $bLe => self::EQUAL,
$aLe => self::BEFORE,
$bLe => self::AFTER,
default => self::CONCURRENT,
};
}
/**
* Element-wise maximum.
*
* @param array<string,int> $a @param array<string,int> $b
* @return array<string,int>
*/
public static function merge(array $a, array $b): array
{
$out = $a;
foreach ($b as $actor => $n) {
$out[$actor] = max((int) ($out[$actor] ?? 0), (int) $n);
}
ksort($out);
return $out;
}
/**
* @param array<string,int> $v
* @return array<string,int>
*/
public static function increment(array $v, string $actor): array
{
$v[$actor] = (int) ($v[$actor] ?? 0) + 1;
ksort($v);
return $v;
}
/** True when $a has seen everything $b has. */
public static function descends(array $a, array $b): bool
{
return in_array(self::compare($a, $b), [self::AFTER, self::EQUAL], true);
}
}<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* A note synced across a user's devices.
*
* @property array<string,int> $version_vector causal context of the stored state
* @property array<int,array{device:string,vv:array<string,int>,body:string}> $siblings
*/
class Note extends Model
{
protected $fillable = ['user_id', 'body', 'version_vector', 'siblings'];
protected function casts(): array
{
return [
'version_vector' => 'array',
'siblings' => 'array',
];
}
public function hasConflict(): bool
{
return count($this->siblings ?? []) > 1;
}
}The sync endpoint. Inside DB::transaction with lockForUpdate() (the query builder docs: "A "for update" lock prevents the selected records from being modified or from being selected with another shared lock"), the server drops siblings the device's context covers, adds the new version with a fresh dot for the device, and answers 200 or 409 with all siblings:
<?php
namespace App\Http\Controllers;
use App\Models\Note;
use App\Services\AuditLog;
use App\Support\VersionVector;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* Multi-device sync with version vectors instead of timestamps.
*
* The device sends the vector it last pulled ("context") and its device id.
* The server never trusts the device's wall clock. Every stored sibling the
* context already covers is obsolete; every other sibling is concurrent with
* this edit and is kept (dotted-version-vector rule):
* - one survivor -> 200, fast-forward
* - several -> 409 with all siblings; the next push whose context
* covers them (the user's merge) resolves the conflict
*/
class NoteSyncController
{
public function __construct(private AuditLog $audit)
{
}
public function push(Request $request, int $noteId): JsonResponse
{
$data = $request->validate([
'device_id' => ['required', 'string', 'max:64'],
'body' => ['required', 'string'],
'context' => ['present', 'array'],
'context.*' => ['integer', 'min:0'],
]);
$device = $data['device_id'];
$context = array_map('intval', $data['context']);
[$status, $note] = DB::transaction(function () use ($noteId, $device, $context, $data) {
/** @var Note $note */
$note = Note::query()->whereKey($noteId)->lockForUpdate()->firstOrFail();
$stored = $note->version_vector ?? [];
// Siblings the device has seen are obsolete; the others are concurrent.
$survivors = array_values(array_filter(
$note->siblings ?? [],
fn (array $s) => ! VersionVector::descends($context, $s['vv']),
));
// The new sibling's vector is what the device saw plus one fresh
// event (a dot) for this device, unique even if the device lost state.
$dot = max($context[$device] ?? 0, $stored[$device] ?? 0) + 1;
$siblingVv = $context;
$siblingVv[$device] = $dot;
ksort($siblingVv);
$survivors[] = ['device' => $device, 'vv' => $siblingVv, 'body' => $data['body']];
$note->forceFill([
'version_vector' => VersionVector::merge($stored, $siblingVv),
'siblings' => $survivors,
'body' => count($survivors) === 1 ? $data['body'] : $note->body,
])->save();
return [count($survivors) === 1 ? 'ok' : 'conflict', $note];
});
$this->audit->record('note.pushed', [
'note_id' => $noteId,
'device_id' => $device,
'outcome' => $status,
'version_vector' => $note->version_vector,
], correlationId: $request->header('X-Correlation-Id'), causationId: $request->header('X-Causation-Id'));
return response()->json([
'status' => $status,
'context' => $note->version_vector,
'siblings' => $note->siblings,
], $status === 'ok' ? 200 : 409);
}
}Server-side HLC for PHP-FPM workers that share no memory: the state of each node lives in one row updated under FOR UPDATE; receive() merges a timestamp sent by another service:
<?php
namespace App\Support;
use Illuminate\Support\Facades\DB;
use RuntimeException;
/**
* Server-side hybrid logical clock (Kulkarni et al. 2014) for PHP-FPM or
* Octane workers. PHP processes share no memory, so the clock state of this
* node lives in one row of `hlc_clocks`, updated under SELECT ... FOR UPDATE.
* Wall time is milliseconds since the Unix epoch.
*
* Call now() for local events, receive() when another service sends its
* timestamp (for example in an X-HLC header or a message envelope).
*/
final class HybridLogicalClock
{
public function __construct(
private string $nodeId,
private int $maxOffsetMs = 500,
) {
}
/** @return array{wall:int, logical:int} */
public function now(): array
{
return $this->advance(null);
}
/** @return array{wall:int, logical:int} */
public function receive(int $remoteWall, int $remoteLogical): array
{
return $this->advance(['wall' => $remoteWall, 'logical' => $remoteLogical]);
}
/** Parse "wall.logical" as sent in the X-HLC header. */
public static function parse(?string $header): ?array
{
if ($header === null || ! preg_match('/^(\d{1,15})\.(\d{1,10})$/', $header, $m)) {
return null;
}
return ['wall' => (int) $m[1], 'logical' => (int) $m[2]];
}
public static function format(array $ts): string
{
return $ts['wall'].'.'.$ts['logical'];
}
/** @param array{wall:int, logical:int}|null $remote */
private function advance(?array $remote): array
{
return DB::transaction(function () use ($remote) {
DB::table('hlc_clocks')->insertOrIgnore([
'node_id' => $this->nodeId, 'wall_ms' => 0, 'logical' => 0,
]);
$row = DB::table('hlc_clocks')
->where('node_id', $this->nodeId)
->lockForUpdate()
->first();
$pt = (int) floor(microtime(true) * 1000); // wall clock, not hrtime()
$l = (int) $row->wall_ms;
$c = (int) $row->logical;
if ($remote === null) {
[$newL, $newC] = $pt > $l ? [$pt, 0] : [$l, $c + 1];
} else {
if ($remote['wall'] - $pt > $this->maxOffsetMs) {
throw new RuntimeException(sprintf(
'Remote HLC %d is %d ms ahead of local clock (max %d ms)',
$remote['wall'], $remote['wall'] - $pt, $this->maxOffsetMs,
));
}
$newL = max($l, $remote['wall'], $pt);
$newC = match (true) {
$newL === $l && $newL === $remote['wall'] => max($c, $remote['logical']) + 1,
$newL === $l => $c + 1,
$newL === $remote['wall'] => $remote['logical'] + 1,
default => 0,
};
}
DB::table('hlc_clocks')->where('node_id', $this->nodeId)
->update(['wall_ms' => $newL, 'logical' => $newC]);
return ['wall' => $newL, 'logical' => $newC];
});
}
}The audit log stamps every entry with HLC, a UUIDv7 event id, a correlation id and a causation id, and reads a flow in HLC order:
<?php
namespace App\Services;
use App\Support\HybridLogicalClock;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/**
* Append-only audit log ordered by HLC timestamps instead of created_at.
*
* Every entry carries:
* - event_id unique id of this entry (UUIDv7, roughly time-ordered)
* - correlation_id the business flow it belongs to (same for every step)
* - causation_id the event_id of the entry or message that caused it
* - hlc_wall/hlc_logical/node_id a total order consistent with causality
*
* Register in a service provider:
* $this->app->singleton(HybridLogicalClock::class,
* fn () => new HybridLogicalClock(config('app.node_id', gethostname())));
*/
class AuditLog
{
public function __construct(private HybridLogicalClock $clock)
{
}
/**
* @param array<string,mixed> $payload
* @param string|null $remoteHlc "wall.logical" received from the caller
*/
public function record(
string $action,
array $payload,
?string $correlationId = null,
?string $causationId = null,
?string $remoteHlc = null,
): string {
$remote = HybridLogicalClock::parse($remoteHlc);
$ts = $remote === null
? $this->clock->now()
: $this->clock->receive($remote['wall'], $remote['logical']);
$eventId = (string) Str::uuid7();
DB::table('audit_events')->insert([
'event_id' => $eventId,
'correlation_id' => $correlationId ?? $eventId,
'causation_id' => $causationId,
'action' => $action,
'payload' => json_encode($payload, JSON_THROW_ON_ERROR),
'hlc_wall' => $ts['wall'],
'hlc_logical' => $ts['logical'],
'node_id' => config('app.node_id', gethostname()),
'recorded_at' => now(), // for humans only; never sort by it
]);
return $eventId;
}
/** Entries of one flow in causal-compatible order. */
public function flow(string $correlationId): array
{
return DB::table('audit_events')
->where('correlation_id', $correlationId)
->orderBy('hlc_wall')->orderBy('hlc_logical')->orderBy('node_id')
->get()->all();
}
}The Laravel angle
| Laravel 13 feature | Use | Note |
|---|---|---|
protected function casts(): array with 'array' | Version vector and siblings in JSON columns | AsArrayObject if you mutate offsets in place |
$table->json() | Schema for vectors and siblings | jsonb on PostgreSQL |
DB::transaction() + lockForUpdate() | Compare-and-merge without lost updates | One row lock per note / per HLC node |
DB::table()->insertOrIgnore() | Create the HLC row once | Avoids a race on first use |
Str::uuid7() | Event ids that sort roughly by time | Still not a causal order across hosts |
now() (Carbon) | Human-readable recorded_at | Wall clock: never the sort key |
hrtime(true) (PHP) | Durations | Monotonic, nanoseconds |
Request headers X-Correlation-Id, X-Causation-Id, X-HLC | Propagating causality between services | Laravel Context can carry them into queued jobs |
| Octane | Long-lived workers | You could hold HLC state in memory per worker, but each worker is then its own node id |
Solving the classic problems
"The audit log shows the effect before the cause"
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| HLC timestamps | Every service stamps with HLC and merges received HLC | Sortable, close to wall time, causal | Needs a header on every call and message |
| Causation ids | Store the parent event id | Exact tree, no clocks | Order of siblings (concurrent steps) undefined |
| Single sequencer | One database sequence or Kafka partition per flow | Simple total order | Bottleneck; not across flows |
| Wall time + NTP | Status quo | Free | Wrong under skew, steps, leap seconds |
Recommended: HLC for the sort key, causation id for the tree, correlation id for the flow. Code: AuditLog, hlc.
"Two devices edited the same note and one edit disappeared"
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Version vector per note, siblings on concurrency | Device sends its context; server keeps concurrent versions | No lost edits | Merge UI or merge rule |
| CRDT document (Automerge, Yjs) | Merge by construction | No conflicts shown | Bigger payloads, library lock-in |
Server-side optimistic lock (single version integer) | Reject writes based on an old version | Simple | Offline devices always lose; works only when server is reachable |
| LWW by device clock | edited_at | Trivial | Silent loss, skewed devices win |
Recommended: version vector with dots (Laravel NoteSyncController) for documents users edit offline; a CRDT for real-time collaborative text. Single-integer optimistic locking is taught in Optimistic vs Pessimistic Locking.
"Our vector clocks keep growing"
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Server actor ids instead of client ids | Coordinator's id goes in the vector | Bounded by cluster size | Needs dots to avoid lost updates |
| Dotted version vectors | Riak dvv_enabled=true | Bounded by replication factor | Library support |
| Pruning (Dynamo, Riak) | Drop oldest entries over a threshold | Bounded size | False conflicts after pruning |
| Interval tree clocks | Fork/join identities | Adapts to churn | Complex, few libraries |
"Clock skew broke last-writer-wins"
| Solution | How | Advantage | Cost |
|---|---|---|---|
| HLC instead of wall time | Merge received timestamps | Causally newer write gets larger stamp | Concurrency still resolved arbitrarily |
| Detect concurrency, keep siblings | Version vectors | Nothing lost | Merge logic |
| Bounded skew + refuse/crash | CockroachDB --max-offset | Guarantees hold within the bound | Nodes stop under bad NTP |
| Server-assigned timestamps | Coordinator stamps, not clients | Removes client skew | Server skew remains |
"A consumer processed OrderShipped before OrderPaid"
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Same partition key | Partition both events by order_id | Broker order per order | No order across orders; hot keys |
| State machine in consumer | Reject or park events whose preconditions are missing | Robust to any reorder | More code |
| Causation id check | Process only when the causing event is known | Exact | Storage of processed ids |
| Resequencer | Buffer until the gap is filled | Restores order | Latency, buffer limits (Advanced Routing) |
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Measure latency, timeouts, leases on one host | Monotonic clock | time.Since, hrtime | Immune to NTP steps |
| One writer orders everything (single leader, one partition) | Its sequence / offset / LSN | Partition by entity | Lamport order for free |
| Replay or merge logs from several nodes deterministically | Lamport (time, node) | Persist the clock across restarts | Causal total order, 8 bytes |
| Detect concurrent updates of replicated objects | Version vectors with dots | Siblings, domain merge | No silent loss, bounded size |
| Multi-device offline editing | Version vector per document (devices are actors) | Merge UI, or a CRDT | Devices are the replicas |
| Collaborative text or counters | CRDT | Its own causal metadata | Merge without asking |
| Sortable timestamps across services that respect causality | HLC | Max-offset check, header propagation | Close to wall time, 64 bits |
| Global transactions with real-time order | Spanner TrueTime, or CockroachDB within its bound | Commit wait / uncertainty restarts | External consistency or close to it |
| Read-your-writes across replicas | Session token (MongoDB cluster time, LSN, HLC) | Wait or route on read | Causal session |
| Debugging distributed executions | Vector clocks or tracing parent ids | Visualise the space-time diagram | Exact concurrency |
| Very large, churning membership | Interval tree clocks or server-side dots | Fork/join ids | Avoid unbounded vectors |
| Caches, sessions, insert-only data | LWW is fine | HLC stamps | Concurrent overwrites are harmless |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One database is a sequencer: its transaction order (and bigserial ids, WAL LSN) is a total order consistent with causality for everything that goes through it. The only clock mistakes left are local: subtracting wall times for durations, and trusting the browser's edited_at. Example: a Laravel app with one PostgreSQL primary orders audit rows by id (a sequence), measures job durations with hrtime, and uses a version integer for optimistic locking. No vector clocks needed.
Modular monolith: boundaries without the network
Modules still share one database and one clock domain, but they start emitting domain events. Introduce correlation and causation ids now, while it is cheap: every event records the event that caused it. Example: the Billing module handles OrderPlaced from Ordering in the same transaction; both rows share correlation_id and the billing row's causation_id points to the order event. When modules later split, the audit trail already reconstructs flows without clocks.
Microservices: causality must travel on the wire
Each service has its own database and its own clock. Nothing orders events across them unless you send the ordering information. Example flow for checkout:
Orders (node o-1) Payments (node p-3, clock 40 ms behind) Audit
1 HLC (1000.040, 0) OrderPlaced {msg m1, corr c-9, hlc 1000.040.0} -----------> row m1
2 receive: HLC -> (1000.040, 1)
3 PaymentCaptured {m2, corr c-9, cause m1, hlc 1000.040.2} -> row m2
4 receive: HLC (1000.041, 0)
5 OrderConfirmed {m3, corr c-9, cause m2, hlc 1000.041.0} --------------------> row m3
ORDER BY hlc gives m1 < m2 < m3 although Payments' wall clock said m2 happened at 1000.000Put message id, correlation id, causation id and HLC in the outbox row (Transactional Outbox); partition by the entity whose order matters (Ordering & Partitioning); make consumers idempotent (Inbox) and precondition-checking rather than order-assuming.
Distributed data: replicas, caches, multi-leader, multi-region
Here clocks decide correctness. Leader-follower replicas need session tokens for read-your-writes (MongoDB cluster time, PostgreSQL LSN; see Replication, Read Replicas & Failover). Multi-leader and leaderless stores need conflict detection: version vectors with dots (Riak), or CRDTs; LWW only for data where losing a concurrent write is fine (Cassandra by default). Distributed SQL uses HLC with a skew bound (CockroachDB, YugabyteDB) or TrueTime (Spanner). Caches are LWW by nature: an invalidation racing a refill can resurrect old data unless entries carry versions. Example: a multi-region user-settings service writes in both regions; each settings document carries a version vector {eu: 4, us: 7}; concurrent edits produce siblings merged field by field, with a rule "most restrictive privacy setting wins".
Scaling path: 1x, 10x, 100x
| Scale | Ordering source | Conflict handling | What changes |
|---|---|---|---|
| 1x: one region, one primary | Database sequence, transaction order | Optimistic version integer | Nothing to add but monotonic durations |
| 10x: read replicas, a few services, a broker | Per-partition offsets; HLC across services | Session tokens for read-your-writes; causation ids | Headers on every call; NTP/chrony monitoring with alerts |
| 100x: multi-region, multi-leader or offline clients | HLC with max-offset, or TrueTime-class database | Version vectors with dots or CRDTs; siblings with merge | Clock-offset SLOs, PTP / provider time services, pruning and DVV to bound metadata |
Lab: watch Lamport miss concurrency, vectors catch it, HLC survive skew
Everything here is a single-process Go program and Go tests; it runs on a laptop. The Go commands were run while writing this page; the output below is what they printed. The Laravel part is expected, not run.
1. Run the tests (they include the property tests).
1 cd docs/snippets/system-design/vector-clocks-causality/go
2 go test ./...
3 ok academy/vector-clocks-causality/before
4 ok academy/vector-clocks-causality/hlc
5 ok academy/vector-clocks-causality/lamport
6 ok academy/vector-clocks-causality/vclock
7 ok academy/vector-clocks-causality/versionvector2. Replay the three-process run from the diagram.
1 go run ./cmd/lab
2 a1 A local/send L=1 V=[A:1]
3 c1 C local/send L=1 V=[C:1]
4 b1 B receive L=2 V=[A:1 B:1]
5 b2 B local/send L=3 V=[A:1 B:2]
6 a2 A local/send L=2 V=[A:2]
7 c2 C receive L=4 V=[A:1 B:2 C:2]
8 a1 vs c2: before
9 a2 vs c2: concurrent <- L(a2)=2 < L(c2)=4, yet concurrent
10 c1 vs b1: concurrent
11 HLC send=1795687200003000000.0000000000 receive=1795687200003000000.0000000001 ordered=trueLine 11: node A's clock is 3 ms ahead; B adopts A's wall value and bumps the logical counter, so the receive still sorts after the send.
3. Break last-writer-wins. Read before/lww_test.go, then change the fast clock's offset from +2s to -2s and rerun go test ./before/: the test fails because now the newer write survives. Which write survives depends only on the skew, not on causality.
4. Make pruning lie. In vclock_test.go, TestPruneDropsOldestAndCanFakeConcurrency drops n1 from a descendant; Compare then reports concurrent for a pair that is really before. Change Big: 3 to Big: 4 and the test fails because nothing is pruned.
5. Laravel multi-device sync (expected, not run). After php artisan migrate and a note with id 1:
1 POST /notes/1/push {device_id: "laptop", body: "A", context: {}} -> 200 context {"laptop":1}
2 POST /notes/1/push {device_id: "phone", body: "B", context: {}} -> 409 siblings A (laptop:1), B (phone:1)
3 POST /notes/1/push {device_id: "phone", body: "A+B", context: {"laptop":1,"phone":1}} -> 200 context {"laptop":1,"phone":2}
4 SELECT action, hlc_wall, hlc_logical FROM audit_events ORDER BY hlc_wall, hlc_logical;
5 note.pushed 1795687200101 0
6 note.pushed 1795687200101 1 <- same millisecond: logical counter orders them
7 note.pushed 1795687200230 0Common misconceptions
| Belief | Reality |
|---|---|
| NTP makes wall-clock order trustworthy | NTP gives a typical offset, no bound; steps, pauses and leap seconds reorder events |
| Time never goes backwards | The wall clock does; Cloudflare's 2017 DNS outage came from that belief |
| Lamport timestamps show which event was first | Only for causally related events; concurrent events get an arbitrary order |
| Vector clocks resolve conflicts | They detect concurrency; merging is someone else's job |
| Vector clocks scale with any number of clients | One entry per actor; use server ids plus dots, or prune and accept false conflicts |
| Version vectors and vector clocks are the same thing | Same math, different subject: versions of data per replica vs events per process |
| LWW keeps the newest write | It keeps the largest timestamp and drops concurrent writes silently |
| HLC is a real-time clock | It is causal and close to real time within the skew; real-time guarantees need a bound and waits |
| Spanner has perfect clocks | It has bounded uncertainty (typically 1 to 7 ms) and waits it out on commit |
| Kafka gives global ordering | Only per partition; across partitions and topics there is none |
| UUIDv7 or Snowflake ids give causal order | They sort by the generating host's clock; skew breaks causality |
| Leap seconds are rare, so ignore them | Smeared and unsmeared clocks differ by up to 0.5 s for a day; do not mix sources |
| MongoDB reads on the primary are always causal | Causal guarantees need a causal session and "majority" read and write concerns |
Cheat sheet
| Topic | Remember |
|---|---|
| Wall vs monotonic | Wall tells time, monotonic measures it; Go time.Now() has both, Round(0) strips monotonic |
| Drift vs skew | Drift is a rate (ppm), skew is a difference (ms) |
| Leap smear | Google: 24-hour linear, noon to noon, about 11.6 ppm |
| Happens-before | Local order + send-before-receive + transitivity; anything else is concurrent |
| Lamport rules | Tick on every event; on receive max(local, msg) + 1; tie-break by node id |
| Lamport limit | a → b ⇒ L(a) < L(b), never the converse |
| Vector compare | All ≤ and one <: before; mixed: concurrent |
| Vector merge | Element-wise max, then tick own entry |
| Version vector | Per data item, per replica; client sends context back on write |
| Dots | Each sibling tagged with the write event; bounded siblings, no lost updates through one server |
| Pruning | Bounds size, creates false conflicts; Dynamo threshold about 10, Riak 50 |
| HLC | (l, c): l = max seen physical time, c breaks ties; 48 + 16 bits; bounded drift |
| CockroachDB | HLC, --max-offset 500ms, crash at 80% vs half the cluster, ReadWithinUncertaintyIntervalError |
| TrueTime | [earliest, latest], ε 1 to 7 ms, commit wait until TT.after(s) |
| Causal session | MongoDB: cluster time + operation time, "majority" read and write concerns |
| Messaging | Message id, correlation id, causation id on every message; order only per partition |
| LWW | Only for immutable, insert-only, cache or session data |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Two events on two hosts are 5 ms apart by their wall clocks. Can you say which happened first? Must-know
Answer
Answer: Not from the timestamps. With unknown skew (NTP gives no bound) either order is possible in real time, and unless a chain of messages connects them they are concurrent in the happened-before sense, so "first" has no meaning for the system.
2 — State Lamport's two implementation rules and the Clock Condition. Why does the converse not hold? Important
Answer
Answer: IR1: increment the clock between any two events. IR2: send the clock value on each message; on receipt set the clock greater than both its own value and the message's. Clock Condition: if a → b then C(a) < C(b). The converse would force concurrent events to happen "at the same time", which contradicts the condition itself (Lamport's argument with p2, p3 and q3).
3 — In the lab run, L(a2) = 2 and L(c2) = 4. Did a2 happen before c2? Important
Answer
Answer: No. Their vectors are [A:2] and [A:1 B:2 C:2]: A is larger on the left, B and C on the right, so they are concurrent. Lamport order is only one linearisation.
4 — Compare [A:3 B:1] with [A:3 B:2 C:1] and with [A:2 B:4]. Important
Answer
Answer: [A:3 B:1] is before [A:3 B:2 C:1] (every entry ≤, B and C strictly less). [A:3 B:1] vs [A:2 B:4] is concurrent (A larger on the left, B larger on the right).
5 — Why does a version vector with one entry per server lose updates when two clients write through the same server, and how do dots fix it? Good to know
Answer
Answer: Both clients read the same context; the server stamps the second write {S:2}, which dominates {S:1}, so the first value is discarded although the clients never saw each other. A dot tags each value with its own write event; a new write drops only the values whose dots are covered by the context it carries, so the first value survives as a sibling.
6 — What does pruning a vector clock cost, and why is that the safe direction? Good to know
Answer
Answer: A descendant can look concurrent with its ancestor (a false conflict), producing an unnecessary sibling. That is safe: a merge is wasted work, whereas the opposite error (a concurrent version looking like an ancestor) would silently lose data.
7 — Node A's clock is 3 ms ahead of B's. A writes x and sends it; B writes y after receiving x. What do wall-clock LWW and HLC decide? Important
Answer
Answer: LWW stamps x with the larger wall time and keeps x, losing y although y causally followed x. HLC on B adopts A's l on receipt and increments c, so y gets (l_x, 2) > (l_x, 0) and is ordered after x.
8 — What exactly does Spanner's commit wait guarantee, and what does it cost? Good to know
Answer
Answer: It ensures no client sees T's data until TT.after(s) is true, so s is less than the real commit time and any transaction starting later gets a larger timestamp: external consistency. The cost is waiting roughly twice the uncertainty ε (typically single-digit milliseconds) on every read-write commit.
9 — What happens to a CockroachDB node whose clock drifts, and what error do clients see near the bound? Good to know
Answer
Answer: If its clock is out of sync with at least half the other nodes by 80% of --max-offset (default 500ms), it crashes. Reads that meet a value inside their uncertainty window get ReadWithinUncertaintyIntervalError (a retryable 40001) unless the timestamp can be pushed and reads refreshed.
10 — A MongoDB client writes with w:1 and reads from a secondary in a causal session. Is read-your-writes guaranteed? Important
Answer
Answer: Not under all failures. MongoDB documents that only "majority" read concern and "majority" write concern guarantee all causal consistency guarantees; with w:1 a write on a deposed primary can be rolled back.
11 — Which two ids let you rebuild the causal tree of a business flow from messages without any clock? Important
Answer
Answer: The correlation id (which flow) and the causation id (which message directly caused this one), together with each message's own id.
12 — When is last-writer-wins an acceptable conflict rule? Must-know
Answer
Answer: When concurrent overwrites cannot lose meaningful information: immutable or insert-only data with unique keys, caches, sessions, bulk loads. Riak's docs give the same list. Even then, prefer HLC to raw wall time for the timestamp.
Glossary
| Term | Meaning |
|---|---|
| Physical clock | A hardware-driven clock estimating real time |
| Wall clock | The system's estimate of UTC; can jump backwards |
| Monotonic clock | Elapsed-time counter that never goes backwards; per machine |
| NTP | Network Time Protocol; slews or steps clocks towards upstream servers |
| PTP | Precision Time Protocol (IEEE 1588); hardware-timestamped sync |
| chrony | Common Linux NTP implementation |
| Clock drift | Rate error of a clock, in ppm |
| Clock skew | Offset between two clocks at one instant |
| Leap second | Extra (or removed) second in UTC |
| Smearing | Spreading a leap second over hours so clocks never step |
| Logical clock | A clock that counts events, not time |
| Happens-before | Lamport's partial order: local order, send before receive, transitive |
| Concurrent events | Events with no happens-before relation either way |
| Causal history | The set of events that happened before an event |
| Consistent cut | A set of events closed under happens-before; a possible global state |
| Clock Condition | If a → b then C(a) < C(b) |
| Lamport clock | Counter with IR1/IR2 rules satisfying the Clock Condition |
| Total order | An order in which every pair is comparable |
| Tie-break | Ordering by process id when Lamport times are equal |
| Vector clock | One counter per process; exact happens-before (Fidge, Mattern) |
| Fidge | Colin Fidge, vector timestamps, 1988 |
| Mattern | Friedemann Mattern, vector time, 1989 |
| Compare | Element-wise test giving equal, before, after or concurrent |
| Merge | Element-wise maximum of two vectors |
| Prune | Removing vector entries to bound size; may create false conflicts |
| Actor id | The identity that owns one vector entry (process, replica, device) |
| Version vector | Per-data-item vector of per-replica update counters |
| Causal context | The version vector a read returns and a write must carry back |
| Dot | One write event: (replica, counter) |
| Dotted version vector (DVV) | Version vector plus a dot per sibling (Preguiça et al.; Riak 2.0+) |
| Sibling | One of several concurrent values stored for a key |
| Sibling explosion | Accumulating duplicate siblings without dots |
| Hybrid logical clock (HLC) | (l, c): max physical time seen plus a logical counter |
| Bounded drift | HLC's l stays within the clock-sync error ε of physical time |
| Max offset | CockroachDB's bound on clock skew (--max-offset, 500ms) |
| Uncertainty interval | Window in which a value's order against a read is unknown |
| TrueTime | Spanner's interval clock [earliest, latest] |
| Commit wait | Waiting until TT.after(s) before making a commit visible |
| External consistency | If T1 commits before T2 starts, T1's timestamp is smaller |
| Causal consistency | Causally related writes seen in causal order by everyone |
| Causal+ | Causal consistency with convergent conflict handling (COPS) |
| COPS | Geo-replicated causal+ key-value store (SOSP 2011) |
| Dependency tracking | Recording which versions a write depends on |
| Cluster time | MongoDB's logical timestamp gossiped by nodes and drivers |
| Causal session | MongoDB session tracking operation and cluster time |
| Interval tree clock | Fork/event/join clock for dynamic membership (OPODIS 2008) |
| Bloom clock | Probabilistic, fixed-size causality clock (2019) |
| Correlation id | Id shared by all messages of one business flow |
| Causation id | Id of the message that directly caused this one |
| Per-key ordering | Order guaranteed only among messages with the same partition key |
| Last-writer-wins (LWW) | Keep the version with the largest timestamp, drop the rest |
| Conflict detection | Deciding two versions are concurrent before resolving |
| Multi-leader | Several replicas accept writes for the same data |
| CRDT | Data type whose replicas merge without conflicts (CRDTs) |
| Audit log ordering | Sorting audit entries in an order consistent with causality (HLC, not wall time) |
| Multi-device sync | Devices as replicas of user data, reconciled with version vectors |
References
- Leslie Lamport, "Time, Clocks, and the Ordering of Events in a Distributed System", Communications of the ACM 21(7), July 1978
- Friedemann Mattern, "Virtual Time and Global States of Distributed Systems", Parallel and Distributed Algorithms, 1989
- Colin J. Fidge, "Timestamps in Message-Passing Systems That Preserve the Partial Ordering", Australian Computer Science Communications 10(1), pp. 56–66, February 1988 (cited, not quoted; no working public copy was retrieved)
- Sandeep Kulkarni, Murat Demirbas, Deepak Madeppa, Bharadwaj Avva, Marcelo Leone, "Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases", University at Buffalo technical report, 2014
- James C. Corbett et al., "Spanner: Google's Globally-Distributed Database", OSDI 2012
- Giuseppe DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007
- Nuno Preguiça, Carlos Baquero, Paulo Sérgio Almeida, Victor Fonte, Ricardo Gonçalves, "Dotted Version Vectors: Logical Clocks for Optimistic Replication", arXiv:1011.5808, 2010
- Wyatt Lloyd, Michael J. Freedman, Michael Kaminsky, David G. Andersen, "Don't Settle for Eventual: Scalable Causal Consistency for Wide-Area Storage with COPS", SOSP 2011
- Paulo Sérgio Almeida, Carlos Baquero, Victor Fonte, "Interval Tree Clocks: A Logical Clock for Dynamic Systems", OPODIS 2008, LNCS 5401; presentation slides (University of Waterloo CS755); Haskell implementation
- Lum Ramabaja, "The Bloom Clock", arXiv:1905.13064, 2019
- Riak KV docs: Causal Context, Conflict Resolution, Clusters
- MongoDB docs: Causal Consistency and Read and Write Concerns, Read Isolation, Consistency, and Recency, Server Sessions; Go driver v2
mongoandoptions - CockroachDB docs: Transaction Layer (Time and hybrid logical clocks, Max clock offset enforcement),
cockroach start(--max-offset), Transaction Retry Error Reference; Cockroach Labs blog, "Living Without Atomic Clocks" - YugabyteDB docs: Transactions overview (hybrid logical clocks)
- Go:
timepackage (Monotonic Clocks), Go 1.9 release notes - Google Public NTP: Leap Smear
- John Graham-Cumming, "How and why the leap second affected Cloudflare DNS", Cloudflare blog, 1 January 2017
- Laravel 13: Eloquent, Eloquent: Mutators & Casting, Database, Query Builder (pessimistic locking), Migrations, Strings (
Str::uuid7)