Video in progress
Why can't you determine the order of events in a distributed system with a plain timestamp, and what do a Lamport clock or a vector clock give you?
The clocks of different servers differ by milliseconds, sometimes seconds, and can even go backward, so a timestamp doesn't reliably tell you "what happened first". A Lamport clock gives a number consistent with causal order, and a vector clock can also tell whether two events are related or concurrent.
📖 Answer
An example: server A's clock is 3 ms ahead. A user changed their profile through A (t=1000), then changed it again through B (t=998). If last-write-wins decides by timestamp, the newer change is lost. NTP brings clocks closer together, but it gives no guarantee.
Lamport clock. Each process has a counter:
- on every event,
c = c + 1; - when sending a message,
cis attached to the message; - when receiving a message,
c = max(c, received) + 1.
The guarantee: if event A caused event B, then L(A) < L(B). The reverse isn't true — L(A) < L(B) doesn't mean A happened before B, they may be concurrent. But it's enough for a total order (ties are broken by node ID).
Vector clock. A separate counter for each node, as a vector: {A:3, B:1, C:0}. Comparing two vectors gives one of three answers:
- one is less than or equal to the other everywhere — it came first;
- the reverse;
- each is larger than the other somewhere — concurrent (a conflict).
Detecting exactly this "concurrent" case is the point: Dynamo-style databases keep both versions and hand the merge to the application (or to the next read). The cost is that the vector grows with the number of nodes.
In practice, at the application level simpler solutions are often enough: a single leader for each record and a monotonic version column. But with multi-leader setups or offline clients, you can't merge correctly without these concepts.
Sign up to mark studied questions and save your progress.