TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About · Labs · Cheat sheets · Learning paths

All concepts · distributed systems · causality · consistency · conflicts

Vector clocks and ordering events

Wall clocks can't order events across machines, so distributed systems track causality instead. Lamport clocks give an order consistent with happened-before; vector clocks keep one counter per node and can also tell when two events are concurrent, which is how Dynamo-style stores detect conflicting writes.

14 min7 animations

📚 Builds on📚 Replication and read replicas

🖨️ Cheat sheet

Dates on letters can't be trusted

Ana, Ben and Cara are pen pals planning a picnic by post. Each writes the time on every letter, using the clock in their own kitchen. But kitchen clocks are never quite right. Ana's runs five minutes fast.

Ana writes "let's meet at the park" and her clock says 10:05. Ben reads it and replies "no, the café is better". His clock is right, and says 10:02. Cara gets both letters and puts them in order by the time written on them. Ben's letter looks older, so she goes to the park. Ben's letter was a reply to Ana's, but the times say the opposite.

Times on letters only tell you what each kitchen clock said. To know which letter came first, we need a different trick.

Why wall clocks can't order events

Every machine has its own clock, and no two agree exactly. Quartz clocks drift, and NTP only keeps them close, not equal: servers on a local network are typically within about a millisecond, over the internet tens of milliseconds, and much more after a network problem or a misconfigured NTP server. An NTP correction can also step a clock backwards, and VM pauses and leap seconds add more surprises. This difference between clocks is called clock skew.

So if node A stamps a write 10:00:05 and node B, which saw that write, stamps its own later write 10:00:02, sorting by timestamp puts them in the wrong order. Inside one JVM, System.nanoTime() is monotonic, but its value means nothing on another machine, and System.currentTimeMillis() can jump in either direction.

What we usually need isn't the real time at all. It's causality: could event a have influenced event b?

Timestamps put a reply before its question4 steps
👩Ana👨Ben👧Cara
Press play and watch it happen!

Counting instead of telling the time

The pen pals try something simpler. They stop writing times and write a number instead. The rule: your next letter gets a number one bigger than the biggest number you've seen so far, on your own letters or anyone else's.

Ana's park letter is number 1. Ben has seen 1, so his café reply is number 2. Now the reply always has the bigger number, whatever the kitchen clocks say. A letter written after reading another always gets a bigger number. This counting rule is called a Lamport clock.

But there's a catch. Cara had already written three letters to her cousin, so her next one, "I'll bring cake", is number 4. She never saw the park or café letters. Still, 2 is smaller than 4, so it looks as if her letter came after Ben's. A single number can put letters in a line, but it can't tell you that two letters were written without knowing about each other.

Happened-before and Lamport clocks

Leslie Lamport's 1978 paper defines happened-before (written a → b):

  • a and b happen on the same node and a comes first; or
  • a is sending a message and b is receiving that message; or
  • there's some c with a → c and c → b (it's transitive).

If neither a → b nor b → a, the events are concurrent (a ∥ b): neither could have known about the other.

A Lamport clock is one counter per node:

  • before each local event or send, increment the counter;
  • attach the counter to every message;
  • on receive, set the counter to max(local, received). Lamport's original rule then adds 1, so the receive is an event with its own timestamp; the simpler variant used here only takes the max and lets the next local event or send do the increment.

This guarantees if a → b then L(a) < L(b) for every timestamped event (with the max-only variant, that means local events and sends). The converse is false: L(a) < L(b) doesn't mean a → b, they might be concurrent. Break ties with the node id and you get a total order consistent with causality, which is enough for things like ordering lock requests, but not for spotting conflicts.

One number per letter4 steps
👩Ana👨Ben👧Cara🧑Cara's cousin
Press play and watch it happen!

A list of everyone's latest number

So the pen pals add more to each letter. Each friend numbers only their own letters: Ana 1, Ana 2, and so on. At the top of every letter they write a short list: the latest number they've seen from each friend. "A1 B0 C0" means "this is Ana's first letter, and I haven't heard from Ben or Cara yet". This list is a vector clock.

Two simple rules keep the lists right:

  • Before writing a letter, bump your own number by one.
  • When a letter arrives, look at its list, and for each friend keep whichever number is bigger, yours or the letter's.

Ana writes "park" with A1 B0 C0. Ben reads it, so his list becomes A1 B0 C0 too. He bumps his own number and replies "café" with A1 B1 C0. Anyone who reads Ben's letter can see he had read Ana's first letter.

Vector clocks

A vector clock (Fidge and Mattern, 1988) gives each of the N nodes a vector of N counters. Node i keeps V[i] as its own event count and V[j] as the latest event of node j it has heard about, directly or through others.

  • Local event or send on node i: V[i] += 1, and attach a copy of V to the message.
  • Receive with vector W: V[j] = max(V[j], W[j]) for every j. Fidge and Mattern also count the receive as an event and do V[i] += 1; Dynamo-style stores and the code below only merge, and the next local event or send increments.

After a merge, the node's vector summarises its whole causal past: everything it has seen, and everything those senders had seen. Nodes that haven't appeared yet are treated as 0, so in practice a vector is a map from node id to counter rather than a fixed array.

Each letter carries a list4 steps
👩Ana👨Ben👧Cara
Press play and watch it happen!

Before, after, or side by side

Now anyone can compare two letters by their lists, friend by friend:

  • If every number on letter X is the same or smaller than on letter Y, and at least one is smaller, then X was written before Y, and Y's writer knew about it. Park (A1 B0 C0) came before café (A1 B1 C0).
  • If each letter has at least one number bigger than the other's, neither writer knew about the other letter. They were written side by side. Cara's cake letter (A0 B0 C1), written before Ben's letter reached her, and Ben's café letter (A1 B1 C0) are like that: café knows more about Ana and Ben, cake knows more about Cara.

That's what the single number couldn't do. The list tells you when two letters were written without knowing about each other.

Comparing vectors

For vectors V and W (missing entries are 0):

RelationConditionMeaning
V = Wevery V[k] == W[k]same event
V < Wevery V[k] <= W[k] and at least one <V happened before W
V > Wevery V[k] >= W[k] and at least one >W happened before V
V ∥ Wsome V[k] < W[k] and some V[j] > W[j]concurrent

The key property, which Lamport clocks lack: a → b if and only if V(a) < V(b), for every event that gets its own vector (all events in the Fidge–Mattern rules; local events and sends in the merge-only variant). Vector clocks characterise causality exactly. A minimal Java version, with increment, merge and compare:

1import java.util.HashMap;2import java.util.HashSet;3import java.util.Map;4import java.util.Set;5 6public final class VectorClock {7    public enum Order { BEFORE, AFTER, EQUAL, CONCURRENT }8 9    private final Map<String, Long> counters = new HashMap<>();10 11    /** A local event or a send on this node. */12    public void increment(String nodeId) {13        counters.merge(nodeId, 1L, Long::sum);14    }15 16    /** On receive: element-wise max with the sender's clock. */17    public void merge(VectorClock other) {18        other.counters.forEach((node, n) -> counters.merge(node, n, Long::max));19    }20 21    /** How this clock relates to the other one. */22    public Order compare(VectorClock other) {23        boolean less = false, greater = false;24        Set<String> nodes = new HashSet<>(counters.keySet());25        nodes.addAll(other.counters.keySet());26        for (String node : nodes) {27            long a = counters.getOrDefault(node, 0L);28            long b = other.counters.getOrDefault(node, 0L);29            if (a < b) less = true;30            if (a > b) greater = true;31        }32        if (less && greater) return Order.CONCURRENT;33        if (less) return Order.BEFORE;34        if (greater) return Order.AFTER;35        return Order.EQUAL;36    }37 38    public VectorClock copy() {39        VectorClock c = new VectorClock();40        c.counters.putAll(counters);41        return c;42    }43}
1VectorClock ana = new VectorClock();2ana.increment("A");                 // A1: Ana writes "park"3VectorClock park = ana.copy();      // the clock travels with the letter4 5VectorClock ben = new VectorClock();6ben.merge(park);                    // Ben reads it: A17ben.increment("B");                 // A1 B1: Ben writes "café"8 9VectorClock cara = new VectorClock();10cara.increment("C");                // C1: Cara writes "cake", unaware of both11 12park.compare(ben);                  // BEFORE13ben.compare(cara);                  // CONCURRENT

Send a copy(), not the live object, so later increments don't change a clock already attached to a message. In a real system the map is serialised with each message or stored value.

Before, after or concurrent4 steps
Ana's letter box0123👨Ben👧Cara👩Ana
Press play and watch it happen!

Two plans written side by side

The friends keep the official picnic plan with two plan keepers, Dana and Eli, so it isn't lost if one of them is away. Each keeper numbers their own changes to the plan, and the plan carries a list like "D1 E1".

One afternoon Dana and Eli can't reach each other. Ana asks Dana to add cake (D2 E1). Ben asks Eli to add juice (D1 E2). When the keepers swap news, they compare the lists. Each plan has a number bigger than the other's, so neither was written knowing about the other.

Neither keeper picks one and throws the other away. They keep both versions of the plan, side by side, called siblings. The next friend who reads the plan gets both, puts them together into one plan, and sends it back. That new plan's list beats both old ones, so the two versions are replaced.

Detecting conflicts: siblings

Leaderless, Dynamo-style stores (the 2007 Amazon Dynamo paper, Riak, Voldemort) let any replica accept a write, so two clients can update the same key at once on different replicas, especially during a partition, as in the AP side of the CAP theorem. Each stored value carries a version vector keyed by replica id (the per-value form of a vector clock).

When versions meet, during a read or anti-entropy between replicas:

  • if one vector dominates, the older version is obsolete and is discarded;
  • if they're concurrent, the store keeps both, called siblings, and returns all of them on the next read.

The client reads the siblings together with their causal context (the merged vector), resolves them into one value, and writes it back with that context. The new version's vector dominates every sibling, so they're all replaced. Riak calls this allow_mult=true. The context matters: a client that writes without the context it read creates yet another sibling.

Two replicas, two concurrent versions4 steps
👩Ana👨Ben👩‍💼Dana, plan keeper🧑‍💼Eli, plan keeper👧Cara
Press play and watch it happen!

Choosing, or combining

How should two side-by-side plans become one? There are two common ways.

The quick way is called last write wins: keep the plan with the later time on it and throw the other away. It's simple, but someone's change quietly disappears. Ana's cake is gone, and nobody even notices. And remember, those times come from kitchen clocks that can be wrong.

The careful way is to combine them: the plan now says cake and juice. For some things, combining is easy and always gives the same answer, like a list where people only ever add names. If a plan is built that way, any two versions can be combined without asking anyone at all.

Resolving conflicts

  • Last-write-wins (LWW): keep the sibling with the highest timestamp, drop the rest. Simple and needs no client logic, but concurrent writes are silently lost, and with clock skew the "last" one may not even be the latest. Cassandra resolves every regular (non-counter) cell this way. LWW is only safe when values are immutable or a lost update is acceptable.
  • Application merge: the client merges siblings with domain logic: union of shopping-cart items (Dynamo's own example, which can bring back an item the user had removed), keep both and ask the user, and so on.
  • CRDTs (conflict-free replicated data types): data types whose merge is commutative, associative and idempotent, so replicas always converge without coordination: grow-only counters, PN-counters, OR-sets, LWW-registers. Riak offers CRDT data types; Redis Enterprise and Automerge use them too.

Vector clocks tell you that two writes conflict. Deciding what the result should be is always application semantics, made either by you or by the data type you chose.

Last write wins, or merge3 steps
The picnic plan0123👩Ana👨Ben👧Cara
Press play and watch it happen!

When the plan goes wrong

Even with lists on every plan, things still go wrong.

A change with no list. Ben wants to add juice to the plan. He doesn't look at the list on the plan he read, and just tells the keeper "add juice". The keeper can't tell what Ben had seen, so she keeps his version side by side with the other one. A needless extra copy appears. If it keeps happening, the pile of copies gets taller and every reader has more to combine. The fix is simple: always send back the list from the plan you read.

Lists that grow too long. With many keepers taking turns, especially when stand-in keepers fill in for absent ones, each plan's list becomes long. A keeper may cross off the oldest names to keep it short. Then a plan that really came after another can look as if it was written side by side with it, and the keepers make extra copies to be safe.

Combining badly. Cara combines two plans by putting everything from both onto one page. But Ben had crossed cake off one of them. Her combined plan has cake again, and nobody notices until the picnic. Combining needs a rule that remembers what was crossed off.

Last write wins can also quietly lose a change, as seen above. And a single number per letter can never show that two letters were written side by side.

What can go wrong

Clock skew, siblings and the cost of last-write-wins are covered above. These are the failures that remain once you run a store with causal versions.

  • Last-write-wins on a concurrent write. The store (Cassandra for regular cells, or Riak with last_write_wins set) picks the highest timestamp and discards the other write. Observed: no error at all; a user's update vanishes, or an older value reappears because a node with a fast clock stamped it later. Fix: give concurrent values causal metadata and keep siblings, use a CRDT, or restrict LWW to immutable or idempotent data. Where you must keep LWW, keep clocks tight with NTP and treat timestamps as a tiebreaker, not as truth.
  • Vectors grow, and get truncated. A vector has an entry per writer. Keyed by client id it grows without bound; keyed by replica id it is bounded by the nodes that coordinate writes, which can exceed N when failures hand writes to other nodes, so Dynamo prunes entries beyond a threshold, oldest first. Observed: larger values and metadata on every read and write, then siblings that "shouldn't" exist: a pruned entry makes an ordered pair look concurrent, and ancestry is lost. Fix: key by replica rather than client, keep pruning thresholds well above the number of writers (Riak's small_vclock/big_vclock), and monitor metadata size.
  • Sibling pile-up. Clients write without passing back the causal context they read, or two clients write through the same replica with stale contexts. Every blind write creates another sibling. Observed: sibling count per key rising, objects growing, slow reads, timeouts when a hot key holds many siblings. Fix: always return the context from the read with the write (see the scene below), resolve on read, and use dotted version vectors (defined below) so a stale write only adds one sibling.
  • Inconsistent or wrong resolution. Each client merges siblings its own way, or merges naively. A union of cart contents brings back an item the user removed (Dynamo's own example), and two services with different merge code leave the data depending on who read last. Observed: resurrected deletes, flip-flopping values, support tickets that do not reproduce. Fix: put one deterministic, commutative, associative and idempotent merge in a shared library or the server, record removals (tombstones or an OR-set) instead of just dropping items, and unit-test the merge on every order of its inputs.
  • Lamport clocks used to detect concurrency. L(a) < L(b) does not mean a happened before b, so code that flags a conflict only when timestamps are equal, or picks "the later one", misses real conflicts. Observed: concurrent writes handled as ordered, one silently overwriting the other. Fix: use a vector clock (or version vector) whenever you must know whether two events are concurrent.
1// Naive sibling merge: removals are lost, a deleted item comes back.2Set<String> merged = new HashSet<>();3for (Cart sibling : siblings) {4    merged.addAll(sibling.items());5}

Both siblings are valid, but one of them removed an item the other still lists. Without a record of the removal, a union cannot tell "never added" from "removed".

ChoiceYou gainYou pay
Last-write-winsOne value, no client logic, tiny metadataSilently lost concurrent writes, and clock skew can make the older one win
Siblings with vector clocksNo write is lost, conflicts are detected (false ones only after pruning or blind writes)Every client must merge, siblings can pile up, metadata grows
CRDTsReplicas converge with no coordination or client merge codeRestricted data types, tombstones and metadata, merge rules you cannot bend
Dotted version vectors over plain vector clocksDots track the exact write that made each sibling, so there is less pile-upA slightly more complex protocol and store
Hybrid logical clocks (defined below)Near wall-clock time, monotonic, a bounded small timestampOrder only: cannot detect concurrency, so a conflict policy is still needed

Siblings and their costs follow from the CAP theorem: vector clocks and siblings are the price of staying available on both sides of a partition. A store that chose consistency would refuse one side instead.

A write without context, then a merge4 steps
👩Ana👨Ben👩‍💼Dana, plan keeper👧Cara
Press play and watch it happen!
🔧 Going deeper

To fix the same-replica pile-up above, a dotted version vector adds a single "dot" (replica id, counter) naming exactly the write that created each sibling, so the store tracks concurrency precisely with only one entry per replica. Riak supports them from 2.0 and recommends them over plain vector clocks.

Hybrid logical clocks (Kulkarni et al., 2014) take a different trade-off: a timestamp made of the physical clock plus a small logical counter. It stays close to wall time (useful for snapshots and time-based queries), never goes backwards, and respects happened-before like a Lamport clock. Like a Lamport clock, it can't detect concurrency. CockroachDB timestamps transactions this way.

🧩 Quick quiz

Quick quiz! 5 questions about Vector clocks and ordering events, told the same way as the story.
  1. Ben replies to Ana's letter, but his reply has an earlier time written on it than hers. How can that happen?
  2. Ben's letter has the single number 2 and Cara's has 4. What can Ana be sure of?
  3. Ana's list says A3 B1 C0. A letter arrives with A1 B4 C2. What does her list say after reading it, before she writes anything?
  4. One version of the plan says D2 E1 and another says D1 E2. What should a plan keeper do?
  5. Two side-by-side plans are settled by last write wins. What's the risk?
Answer every question to check.Passing marks Vector clocks and ordering events as done.
Got the hang of Vector clocks and ordering events? Mark it as done, and your paths show how far you’ve got.

Saved in this browser.

📨 Event-driven systemsStep 5 of 5

← Previous on the path🧳 Sagas and distributed transactionsLast step 🎉Back to the path