← Back to System Design, page 5

system-design-0083 · Medium fresher

What are vector clocks, and how do they tell whether two versions of data happened one after the other or concurrently?

A vector clock is a map from node to counter attached to each version. A node increments its own entry when it writes and merges clocks when it receives data. Version A happened before B if every entry in A is less than or equal to B's; if neither is less or equal, the versions are concurrent and must be merged or shown as a conflict. Physical timestamps cannot tell these cases apart reliably because clocks drift.

Full answer

Why not timestamps?

Servers' clocks differ by milliseconds or more. With "last write wins" by timestamp, a write that happened later can lose to an earlier write from a server with a fast clock, and true concurrent writes are silently dropped. We need to capture causality: did one write see the other?

Lamport clocks first

A Lamport clock is a single counter: increment on each event, and on receiving a message set the counter to max(local, received) + 1. If A caused B, A's counter is smaller. But the reverse does not hold: a smaller counter does not prove A caused B. Lamport clocks give an order, not concurrency detection.

Vector clocks

Each version carries {node: counter}:

  • When node N writes, it increments clock[N].
  • When data is merged, take the per-node maximum, then increment your own entry for the new write.
  • Compare two clocks entry by entry:
    • all entries of A <= B: A happened before B (B can replace A);
    • all entries of A >= B: A happened after B;
    • otherwise: concurrent; keep both versions (siblings) until something resolves them.
python
def merge(a, b):
    return {k: max(a.get(k, 0), b.get(k, 0)) for k in a.keys() | b.keys()}


def compare(a, b):
    """Return 'before', 'after', 'equal' or 'concurrent'."""
    keys = a.keys() | b.keys()
    le = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
    ge = all(a.get(k, 0) >= b.get(k, 0) for k in keys)
    if le and ge:
        return "equal"
    return "before" if le else "after" if ge else "concurrent"


def tick(clock, node):
    c = dict(clock)
    c[node] = c.get(node, 0) + 1
    return c


if __name__ == "__main__":
    v1 = tick({}, "A")                     # A writes:            {A:1}
    v2 = tick(v1, "B")                     # B updates after it:  {A:1, B:1}
    v3 = tick(v1, "C")                     # C updates v1 too:    {A:1, C:1}
    assert compare(v1, v2) == "before" and compare(v2, v1) == "after"
    assert compare(v2, v3) == "concurrent"         # a real conflict: keep both
    v4 = tick(merge(v2, v3), "A")                  # A resolves: {A:2, B:1, C:1}
    assert compare(v2, v4) == "before" and compare(v3, v4) == "before"
    print("ok:", sorted(v4.items()))

Save as vector_clock.py and run python3 vector_clock.py (Python 3.13.5).

Where they are used

Dynamo-style stores (Riak, the original Dynamo) attach vector clocks to values and return siblings to the client on a conflict; the shopping cart example merged sibling carts by union. Version vectors (one entry per replica rather than per client) are the same idea used for replica sync.

Costs

  • Clock size grows with the number of writers. Using replica IDs instead of client IDs bounds it; old entries can be pruned with care (pruning can create false conflicts).
  • The application must know how to merge concurrent versions; the clock only detects them.

Key point

Vector clocks answer "did one write know about the other?" Timestamps answer "which clock said a bigger number?" Only the first question is safe for conflict detection.

By level

Fresher: Explain that each server keeps a count of its own writes inside the data, and that comparing the counts shows which version is newer. A fresher should identify two concurrent versions in an example.

Mid: Explain Lamport clocks, vector clock rules, siblings and Dynamo-style use. Compare clearly with timestamp-based last-write-wins.

Senior: Discuss version vectors, pruning trade-offs, client versus replica IDs, and application-level merges. Expect precise reasoning about causality.

Key points

  • A vector clock maps each node to a counter
  • Increment your own entry on write; take per-node maximum on merge
  • All entries less or equal means happened before
  • Otherwise the versions are concurrent and need merging
  • Timestamps cannot detect concurrency because clocks drift

Common mistakes

  • Treating a larger Lamport counter as proof of causality
  • Using wall-clock last-write-wins and calling conflicts solved
  • Forgetting to merge before incrementing
  • Ignoring clock size growth with many writers

Follow-ups

  • How do version vectors differ from vector clocks?
  • What does a store do with sibling versions?
  • How could pruning cause false conflicts?

Tips

  • Walk through a three-step example with two writers
  • State the comparison rule exactly
  • Contrast with timestamps

Evaluation rubric

  • Correct update and merge rules
  • Correct comparison and concurrency detection
  • Knows practical uses
  • Mentions size and merge costs