Implementing Consistency with Vector Clocks
What you'll learn: How to use vector clocks to track causal relationships between events and enforce causal consistency in distributed systems.
The Core Problem
In the last lesson, you learned that causal consistency preserves the "happens-before" relationship between operations. But how do replicas actually track causality? Enter vector clocks—a practical mechanism to record which events have been observed by which nodes.
What Is a Vector Clock?
A vector clock is a data structure that assigns a logical timestamp to each event in a distributed system. Instead of a single counter, it's an array where each position represents one node.
Analogy: Think of it like a scorecard where each player (node) tracks how many moves they've seen from every other player. When you see someone's scorecard, you instantly know what they've witnessed.
How It Works
Each node maintains a vector of counters:
- When node A performs a write, it increments
vectorClock[A] - When node B receives data from A, it merges the vectors:
vectorClock[B] = max(vectorClock[B], received_vector)for each position, then increments its own counter
This creates a causal dependency graph. Before applying a write, a replica checks: "Have I seen all the events this write depends on?" If not, it must wait or fetch missing updates first.
Why This Guarantees Causal Consistency
Vector clocks let you compare any two events and determine:
- If one causally precedes the other (all counters ≤, at least one <)
- If they're concurrent (neither dominates)
By enforcing that writes are only visible after their causal dependencies, you maintain the happens-before order users expect.
Key Takeaway: Vector clocks provide the metadata needed to detect causal dependencies between events, enabling replicas to apply updates in a causally consistent order without coordination.