SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Clock Synchronization Problem
  • NTP: Network Time Protocol
  • Logical Clocks
  • Lamport Timestamps
  • Vector Clocks
  • Hybrid Logical Clocks (HLC)
  • TrueTime (Google Spanner)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Time and Ordering

Vector Clocks

One counter per machine, so you can tell if two events were related or happened at the same time.

โฑ 14 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A vector clock is a small list of counters, one for each machine. It lets a distributed system tell whether one event happened before another, or whether the two were concurrent (they happened independently).

  • Each machine keeps a list like [2, 0, 1]: how many events it knows about from machine A, B and C.
  • When a machine does something, it adds 1 to its own slot. When it receives a message, it merges the lists first.
  • Comparing two lists tells you: before, after or concurrent. A simple Lamport number cannot detect concurrent events.

02Concept: What is it?

In a distributed system we cannot trust wall clocks, because every machine's clock is a little different. So we ask a better question: could event A have influenced event B? If A happened, then a message chain carried the news to B, then A "happened before" B. If there is no such chain, the two events are concurrent.

A Lamport timestamp is a single number. If A happened before B, A's number is smaller. But the reverse is not true: a smaller number does not prove that A happened before B. The two might simply be unrelated. That is the gap vector clocks close.

A vector clock keeps one counter per process. Process B's vector [1, 3, 0] means: "I have seen 1 event from A, 3 events from myself, and 0 from C." The rules are short:

  1. Local event or send: add 1 to your own slot. (A send also puts the vector into the message.)
  2. Receive: take the slot-by-slot maximum of your vector and the message vector, then add 1 to your own slot.
  3. Compare: V1 is before V2 if every slot of V1 is โ‰ค the same slot of V2, and at least one is smaller. If neither is before the other, they are concurrent.
Three processes, two messages
๐Ÿ…ฐ๏ธA[1,0,0] write
โ†“
send m1[2,0,0]
get m1[2,1,0]
โ†“
send m2[2,2,0]
๐Ÿ…ฒC write[0,0,1]
โ†“
get m2[2,2,2]
A B C, concurrent with A
C writes x=2 without hearing from A, so the two writes are concurrent, even though one has a bigger Lamport number.
๐Ÿง What the vector adds
A Lamport number says "if A โ†’ B then L(A) < L(B)". A vector clock says "A โ†’ B if and only if V(A) < V(B)". The "if and only if" is what lets us spot conflicts.

03Real-Life Example

๐ŸตThree Friends Planning a Dinner by Text
Ann, Ben and Cara plan dinner in a group where messages arrive late. Ann says "Pizza?" and sends it to Ben. Ben replies "Yes, 7pm". Cara, who has seen nothing yet, writes "Let's do sushi". Is Cara's message before or after Ann's? Neither: Cara never saw Ann's message, so her message is concurrent. If each person counts "what I have seen from everyone", the lists show that clearly. Ben's reply happened after Ann's, because he had seen it. Now the group knows: pizza and sushi are a real conflict, and someone must pick.
Dinner chat
Vector clock
Each friend
A process (machine, replica)
What I have seen from each friend
The vector, one slot per process
Sending a text
Add 1 to my slot and attach the vector
Reading a friend's text
Merge: slot-by-slot maximum, then add 1
Ben replied after reading Ann
Ann's vector is smaller than Ben's: happened before
Cara wrote without seeing Ann
Neither vector is smaller: concurrent
Group must pick pizza or sushi
Conflict that needs a merge rule or a user choice

04Why Do We Need It?

๐Ÿ”Detect conflicts
Two writes with no link between them are concurrent. Vector clocks are the tool that finds them.
๐ŸงญCapture cause and effect
A reply always has a bigger vector than the message it answers, so the order of cause and effect is kept.
โฑ๏ธNo wall clocks
Vectors only count events, so clock drift between machines does not matter.
๐Ÿ”€Safe multi-writer systems
Databases that accept writes on many nodes need to know which version is newer, or whether both survive.
๐ŸงฉBetter than last-write-wins
Last-write-wins silently drops one of two concurrent writes. Vectors show the problem so you can merge instead.
๐ŸžDebugging
Tracing tools use the same idea to rebuild what happened before what across many services.
Vector clocks answer one question a single number cannot: "did these two events know about each other?"

05Where Do We Use It?

๐ŸงบDynamo-style stores
Amazon's original Dynamo paper used vector clocks to detect conflicting versions of a shopping cart. Riak used the idea too.
๐Ÿ“Collaborative editing
Version vectors track what each editor has seen, so merges know what is new.
๐Ÿ”Multi-leader replication
When two leaders accept writes, vectors tell which one is newer or whether both must be kept.
๐Ÿ“ฒOffline-first apps
A phone edits offline and syncs later. Vectors reveal whether the server changed in the meantime.
๐Ÿ•ธ๏ธDistributed tracing
Related ideas help order events from many services in a trace.
๐ŸงชTesting tools
Checkers for distributed systems use vector clocks to find out which operations could have affected each other.

06Types / Parts / How It Works

Comparing two vectors

Three possible answers
Before
[1,0,0]vs [2,1,0]
every slot โ‰ค, one smaller
After
[2,1,0]vs [1,0,0]
every slot โ‰ฅ, one bigger
Concurrent
[2,0,0]vs [0,0,1]
bigger in one slot, smaller in another
Check every slot. The pattern of smaller and bigger slots tells the story.

Lamport vs vector clock

Lamport timestampVector clock
SizeOne numberOne number per process
If A happened before BL(A) < L(B)V(A) < V(B)
If L(A) < L(B) or V(A) < V(B)Cannot say that A happened before BA did happen before B
Detects concurrent eventsNoYes
CostTinyGrows with the number of processes
Good forA simple total order, such as a logConflict detection, version tracking

Close relatives

๐ŸงพVersion vectorsone per data item
๐ŸŒณDotted version vectorsfix growth in clients
โŒ›Hybrid logical clockswall time + counter
VisualizerCompare any two events with Lamport and vector clocksPick event X and event Y. Try c1 and a2: the Lamport numbers look ordered, but the vector clock shows they are concurrent. Switch the display between the two clocks.
Show on every event
Process A
a1
[1,0,0]
A writes x=1
a2
[2,0,0]
A sends m1
a3
[3,0,0]
A writes x=3
Process B
b1
[2,1,0]
B gets m1
b2
[2,2,0]
B sends m2
Process C
c1
[0,0,1]
C writes x=2
c2
[2,2,2]
C gets m2
Time moves left to right. Messages: m1 goes a2 โ†’ b1, m2 goes b2 โ†’ c2. Cyan = event X, amber = event Y.
Event X
Event Y
c1: C writes x=2
[0,0,1]
Lamport would say 1
a2: A sends m1
[2,0,0]
Lamport would say 2
Vector clock says
concurrent
c1 and a2 are concurrent (neither knew about the other)
Lamport clock says
ordered
says c1 is before a2
The Lamport clock says c1 is before a2, but the two events never heard about each other. The smaller number is just a coincidence. Only the vector clock tells the truth: they are concurrent, so they may be a conflict.

Rules used: before every event a process adds 1 to its own slot. When a message arrives, the receiver first takes the slot-by-slot maximum of its own vector and the one in the message. Try c1 and a2: Lamport gives 1 and 2, so it looks ordered, but the vectors show they are concurrent.

07How to Use It / Steps / Implementation

Using vector clocks in a data store

  1. 1
    Give each replica an id
    Every node that can accept writes gets one slot in the vector.
  2. 2
    Stamp every write
    A node that writes a value adds 1 to its own slot, and stores the vector with the value.
  3. 3
    Send the vector with replication
    When replicas share data, the vector travels with it.
  4. 4
    Compare on read and on sync
    If one vector is smaller, drop the older value. If they are concurrent, keep both as siblings.
  5. 5
    Resolve the conflict
    Merge the siblings (for example, union two carts), or ask the user, or use a rule such as a CRDT merge.
  6. 6
    Write the merged value with a merged vector
    Take the slot-by-slot maximum of the siblings and add 1 to your own slot, so the merge is newer than both.
  7. 7
    Keep the vectors small
    Prune old entries or use version vectors per key, so the list does not grow forever.
๐Ÿ’กA tiny code idea
merge(a, b) = [max(a0,b0), max(a1,b1), max(a2,b2)] and then add 1 to your own slot. That one line is the whole receive rule.
โš ๏ธDo not use it when you do not need it
If one leader orders all writes, there are no concurrent writes, and a plain version number is enough.

08Key Terms to Know

TermMeaning in easy words
Vector clockA list of counters, one per process, used to order events and spot concurrent ones
Happened-before (โ†’)A is before B if A could have influenced B through a chain of messages or the same process order
ConcurrentNeither event could have influenced the other
CausalityThe link between a cause and its effect, as carried by messages
Lamport timestampA single logical counter that respects happened-before in one direction only
Merge (max)Slot-by-slot maximum of two vectors, done when a message is received
SiblingOne of several concurrent versions of the same value that a store keeps
Version vectorA vector clock attached to a data item to track its versions across replicas
Last-write-winsA simple rule where the newest wall-clock time wins. It can lose data
Conflict resolutionDeciding what to do with concurrent writes: merge, pick one or ask the user
Hybrid logical clockA clock that mixes physical time and a counter, with a fixed size

09Pros, Cons and Trade-offs

โœ… Pros
  • Exact: detects before, after and concurrent
  • Works without synchronized clocks
  • Keeps cause and effect intact
  • Prevents silent data loss from last-write-wins
  • Simple rules, easy to prove correct
โš ๏ธ Cons
  • Size grows with the number of processes
  • Does not decide how to merge, only that a conflict exists
  • Clients must handle sibling values
  • Needs pruning in long-lived systems
  • Cannot say anything about real time

Trade-offs

ChoiceWe gainWe lose
Vector clocksConflicts are visible and no write is lostBigger metadata and siblings to resolve
Lamport timestampsOne small number, a total orderCannot tell concurrent from ordered
Last-write-wins (wall clock)Simplest to build, no siblingsSilently drops one of two concurrent writes
Single leader + version numberNo concurrency to worry aboutThe leader is a bottleneck and a single point of failure
Hybrid logical clocksFixed size and close to real timeCannot detect concurrent writes by themselves

10Common Problems and Mistakes

Common mistakes

  1. Forgetting the +1 on receive. A receive is an event too. Skip it and two different events can share a vector.
  2. Comparing only one slot. You must check all slots before saying "before" or "concurrent".
  3. Mixing up Lamport and vector. A smaller Lamport number does not prove "before".
  4. Letting vectors grow without limit. One slot per client in a huge system makes metadata huge.
  5. Ignoring siblings. If the app picks one at random, you have rebuilt last-write-wins, with extra steps.
  6. Using wall time inside the vector. The counters should be plain counts of events.

Things to watch

๐Ÿ“ˆSize explosion
Many writers means a long vector. Use version vectors per key, or per server not per client.
โœ‚๏ธPruning risk
Cutting old entries can make an old version look concurrent with a new one.
๐ŸงฏSibling storms
Heavy concurrent writes to one key create many siblings. Resolve them on write.
๐Ÿ†•Membership changes
Adding or removing nodes changes the slots. Plan how new ids start.

11Real-World Examples

๐Ÿ“ฆAmazon Dynamo
The 2007 Dynamo paper used vector clocks so the shopping cart could keep two versions and merge them later.
๐ŸงฐRiak
An open-source Dynamo-style database that used vector clocks and later dotted version vectors.
๐ŸงชJepsen-style checking
Tools that test databases use happened-before ideas to analyse histories of operations.
๐Ÿ“ฑSync engines
Many offline-first apps keep version vectors per device to know what each device has seen.
โณCassandra and others
Many stores chose last-write-wins with timestamps instead, trading conflict detection for simplicity.
๐ŸงฎCRDT libraries
Several CRDT designs use vectors inside, to know which updates a replica has already applied.
๐Ÿ“Note
Products change over time. Check each database's current documentation to see which conflict method it uses today.
Mini case: two phones edit the same note
๐Ÿ“ฑPhone 1[1,0] edit
โ†’โ†“sync
โ˜๏ธServerkeeps both
โ†sync
๐Ÿ“ฑPhone 2[0,1] edit
The server sees two vectors that are not ordered, so it keeps both and asks for a merge.

12Related Topics to Read Next

Logical Clocksโ†’

The idea of counting events instead of reading a clock.

Lamport Timestampsโ†’

The one-number version, simpler and smaller.

Clock Synchronization Problemโ†’

Why wall clocks cannot be trusted in the first place.

CRDTsโ†’

Data types that merge concurrent changes by design.

Consistency Modelsโ†’

Where causal consistency fits among the options.

Replicationโ†’

Multi-leader setups are where concurrent writes appear.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a list of counters, one per process, used to order events.
  • โœ”Local or send: add 1 to your own slot.
  • โœ”Receive: slot-by-slot max with the message vector, then add 1 to yours.
  • โœ”Before: every slot โ‰ค and at least one smaller.
  • โœ”Concurrent: neither vector is before the other. This is a conflict.
  • โœ”Vs Lamport: Lamport has one number and cannot detect concurrency.
  • โœ”Cost: grows with the number of processes. Prune or use per-server slots.
  • โœ”One line: โ€œCount what I have seen from everyone, and compare the lists.โ€
โ† Previous
Lamport Timestamps
Next โ†’
Hybrid Logical Clocks (HLC)