Time, clocks and ordering
Why wall-clock timestamps from different machines cannot safely order events, how Lamport clocks order events by cause instead of by time and what they cannot tell you, how vector clocks detect concurrent updates and what they cost, and which clock to use for which job.
Contentsand lesson path
On this page
- Why it matters
- What a server's clock really tells you
- Why wall-clock timestamps cannot order events across nodes
- Lamport clocks: ordering by cause, not by time
- Vector clocks: detecting concurrency
- Hybrid clocks, and which clock for which job
- Check your understanding
- Apply it
- Review prompt
Lessons of Distributed Systems Fundamentals
- Partial failure and the fallacies of distributed computing Concept · 20 min
- Time, clocks and ordering Concept · 20 min
- Consistency models from linearizable to eventual Concept · 25 min
- CAP and PACELC applied to real databases Worked example · 20 min
- Quorums, Raft and leader leases, step by step Lab · 25 min
- Distributed reasoning check Knowledge check · 8 questions
What you will learn
- Explain event ordering with logical clocks and why wall-clock timestamps cannot safely order events across nodes.
01. Why it matters
Apache Cassandra resolves two writes to the same column by keeping the one with the larger timestamp, a rule called last-write-wins (LWW). The timestamp comes from the client or from the coordinating node, and the Cassandra documentation says plainly that its correctness depends on those clocks, so you should run a time synchronisation process such as NTP.
That raises the question this lesson answers: when can a timestamp taken on one machine be compared with a timestamp taken on another? You will see why the honest answer is "only roughly", how logical clocks order events by cause instead, and how to choose a clock for each job.
02. What a server's clock really tells you
A server keeps time with a quartz oscillator, and no two oscillators tick at exactly the same rate. The difference in rate is called drift; the resulting difference between two clocks at a given moment is called skew or offset. NTP, the Network Time Protocol, measures the offset to time servers by exchanging timestamped packets and corrects the local clock.
NTP narrows skew; it does not remove it. RFC 5905, the NTPv4 specification, describes typical precision of a few tens of microseconds for primary servers, a few hundred microseconds for clients on fast local networks, and a few tens of milliseconds with long polling intervals. Real error depends on the network path: NTP estimates the one-way delay as half the round trip, so a congested or asymmetric path skews the estimate.
Corrections also change the clock in ways your code can see. Small errors are slewed: the clock runs slightly faster or slower until it catches up. Larger ones are stepped: the clock jumps (in the NTP reference design, offsets above 125 ms; other implementations such as chrony have their own settings). The Python documentation warns that time.time() can return a lower value than an earlier call if the system clock was set back. time.monotonic() cannot go backwards and is not affected by system clock updates, but its starting point is undefined, so its values mean nothing on another machine. The Snowflake lab shows what a backward step does to an ID generator.
03. Why wall-clock timestamps cannot order events across nodes
Run clocks.py below and look at Part 1 first. Ana edits a document title on replica A. Ben's replica B receives the edit, Ben reads it and changes the title 40 ms later. In this scenario B's clock runs 90 ms behind true time. Parts 2 and 3 are used in the next sections.
"""Wall clocks, Lamport clocks and vector clocks on one small story.
Three replicas (A, B, C) hold the title of a shared document.
Times are simulated in milliseconds; nothing here reads the real clock.
"""
# Part 1: last-write-wins on wall-clock timestamps
SKEW_MS = {"A": 0, "B": -90} # B's clock runs 90 ms behind true time
TEN_AM = 10 * 3600 * 1000 # true time 0 ms is 10:00:00.000
def wall(node: str, true_ms: int) -> int:
return TEN_AM + true_ms + SKEW_MS[node]
def show(ms: int) -> str:
s, ms = divmod(ms, 1000)
return f"{s // 3600:02}:{s // 60 % 60:02}:{s % 60:02}.{ms:03}"
ana = ("Q3 plan", wall("A", 0)) # Ana writes on A at true time 0 ms
# A's write reaches B at 20 ms; Ben reads it, then edits it on B at 40 ms.
ben = ("Q3 plan v2", wall("B", 40))
winner = max([ana, ben], key=lambda w: w[1])
print("Part 1: last-write-wins on wall-clock timestamps")
print(f" Ana on A: {ana[0]!r:14} stamped {show(ana[1])}")
print(f" Ben on B: {ben[0]!r:14} stamped {show(ben[1])} (written 40 ms later)")
print(f" kept: {winner[0]!r} -> Ben's later edit is silently lost")
# Part 2: Lamport and vector clocks on the same kind of story
class Proc:
def __init__(self, name: str, names: list[str]):
self.name, self.lamport = name, 0
self.vector = {n: 0 for n in names}
def tick(self):
self.lamport += 1
self.vector[self.name] += 1
return self.lamport, dict(self.vector)
def receive(self, stamp):
lamport, vector = stamp
self.lamport = max(self.lamport, lamport)
for n, count in vector.items():
self.vector[n] = max(self.vector[n], count)
return self.tick() # the receive is an event too
def relation(v: dict, w: dict) -> str:
if v == w:
return "same event"
if all(v[n] <= w[n] for n in v):
return "happened before"
if all(w[n] <= v[n] for n in v):
return "happened after"
return "is concurrent with"
names = ["A", "B", "C"]
A, B, C = (Proc(n, names) for n in names)
events = {}
events["a1 A writes 'Q3 plan'"] = A.tick()
events["a2 A sends it to B"] = msg = A.tick()
events["c1 C edits another field"] = C.tick()
events["c2 C edits another field"] = C.tick()
events["c3 C writes 'Q3 roadmap'"] = C.tick()
events["b1 B receives A's message"] = B.receive(msg)
events["b2 B writes 'Q3 plan v2'"] = B.tick()
print("\nPart 2: Lamport timestamp L and vector clock V per event")
for label, (lam, vec) in events.items():
print(f" {label:27} L={lam} V={list(vec.values())}")
def compare(x: str, y: str):
(lx, vx), (ly, vy) = events[x], events[y]
sign = "<" if lx < ly else ">" if lx > ly else "="
print(f" {x[:2]} vs {y[:2]}: L is {lx} {sign} {ly}; V says {x[:2]} "
f"{relation(vx, vy)} {y[:2]}")
print("\nPart 3: what each clock can tell you")
compare("a1 A writes 'Q3 plan'", "b2 B writes 'Q3 plan v2'")
compare("c3 C writes 'Q3 roadmap'", "b2 B writes 'Q3 plan v2'")
compare("a2 A sends it to B", "c3 C writes 'Q3 roadmap'")Part 1: last-write-wins on wall-clock timestamps
Ana on A: 'Q3 plan' stamped 10:00:00.000
Ben on B: 'Q3 plan v2' stamped 09:59:59.950 (written 40 ms later)
kept: 'Q3 plan' -> Ben's later edit is silently lost
Part 2: Lamport timestamp L and vector clock V per event
a1 A writes 'Q3 plan' L=1 V=[1, 0, 0]
a2 A sends it to B L=2 V=[2, 0, 0]
c1 C edits another field L=1 V=[0, 0, 1]
c2 C edits another field L=2 V=[0, 0, 2]
c3 C writes 'Q3 roadmap' L=3 V=[0, 0, 3]
b1 B receives A's message L=3 V=[2, 1, 0]
b2 B writes 'Q3 plan v2' L=4 V=[2, 2, 0]
Part 3: what each clock can tell you
a1 vs b2: L is 1 < 4; V says a1 happened before b2
c3 vs b2: L is 3 < 4; V says c3 is concurrent with b2
a2 vs c3: L is 2 < 3; V says a2 is concurrent with c3Ben's write was caused by Ana's: he saw her title and changed it. Yet his timestamp is smaller, so last-write-wins keeps Ana's version and drops Ben's, and nobody gets an error. The general rule is simple: whenever the skew between two machines is larger than the gap between two related events, their timestamps can come out in the wrong order. Better NTP shrinks the window but cannot close it, and it cannot repair timestamps that were already written.
This does not make wall-clock LWW useless. It is a reasonable choice when losing one of two close updates is acceptable, for example a "last seen online" time or a cache entry, and when related writes are normally far further apart than any plausible skew. It is the wrong choice for anything a user expects to keep, such as an edited document or a balance.
04. Lamport clocks: ordering by cause, not by time
In 1978 Leslie Lamport proposed ordering events by what could have influenced what. Event a happened before event b (written a → b) if a came earlier in the same process, or a is the sending of a message and b its receipt, or there is a chain of such steps from a to b. If neither a → b nor b → a, the events are concurrent: neither could have affected the other, whatever the wall clocks say.
A Lamport clock is one integer counter per process, with three rules:
- Before each local event and each send, the process adds one to its counter and stamps the event with it.
- Every message carries the timestamp of its send event.
- On receipt, the process sets its counter to the larger of its own value and the message's stamp, then adds one for the receive event.
These rules guarantee what Lamport called the clock condition: if a → b, then L(a) < L(b). In Part 2, B receives A's message stamped 2 while B's counter is 0, so the receive gets max(0, 2) + 1 = 3, and Ben's edit after it gets 4. Ordering by Lamport timestamp, with the process name as a tie-breaker, gives a total order that every node computes the same way and that never puts an effect before its cause. Using it instead of wall time in the LWW rule would have kept Ben's edit.
The converse does not hold. In Part 3, C's edit c3 has L = 3 and Ben's b2 has L = 4, yet nothing connects them: they are concurrent. A smaller Lamport timestamp only tells you that the event did not happen after the other one. So a Lamport-ordered LWW rule still silently drops one of two concurrent writes, in an order that looks arbitrary to users.
05. Vector clocks: detecting concurrency
A vector clock keeps one counter per process instead of one in total. A process adds one to its own entry for each event, messages carry the whole vector, and a receiver takes the element-wise maximum of its vector and the message's before adding one to its own entry. Event a happened before b exactly when every entry of V(a) is less than or equal to the matching entry of V(b) and the two vectors differ. If each vector is ahead in some entry, the events are concurrent.
Part 3 shows the gain: V(c3) = [0, 0, 3] and V(b2) = [2, 2, 0] are each ahead somewhere, so the script reports them as concurrent instead of pretending one came first. A store that sees two concurrent versions of a key can keep both, often called siblings, and let the application or a merge rule combine them; Multi-leader and leaderless quorums covers those conflict rules.
The price is size. A vector needs an entry for every process that has written, so it grows with the number of writers and travels with every version and message. Systems therefore track replicas rather than clients, and some bound the size: the Dynamo paper describes dropping the oldest entry once a clock reaches about ten, accepting that a few relationships can no longer be decided.
06. Hybrid clocks, and which clock for which job
A hybrid logical clock (HLC), proposed by Kulkarni and colleagues in 2014, combines a physical timestamp with a small logical counter. Like a Lamport clock it respects happened-before; unlike one it stays close to NTP time and fits in a 64-bit timestamp, so a database can use it for questions such as "read the data as of 10:00". It does not detect concurrency the way vector clocks do, and its closeness to real time still depends on NTP keeping skew bounded. Treat it as a pointer for further reading after the next skill, consensus and transactions.
A practical guide:
- Measuring a duration on one machine (timeouts, leases, rate limits): a monotonic clock, never the wall clock.
- Showing people when something happened: the wall clock, knowing it may be off by milliseconds or more.
- Ordering updates to one key: let a single authority, such as the leader that owns the key, assign increasing version numbers. It is the simplest correct option when such an authority exists.
- Ordering by cause across nodes without an authority: Lamport clocks.
- Detecting concurrent edits so none is lost: vector clocks, kept per replica.
- Making every node agree on one order: consensus, the subject of lesson 5.
Do not reach for vector clocks when a single leader already orders every write, or when thousands of clients would each need an entry; a version number or a server-side vector is cheaper and easier to reason about.
07. Check your understanding
08. Apply it
Add a "time and order" line to your guarantee sheet for each of the three stores: how it orders two writes to the same key (leader-assigned version, client or server timestamp, vector clock, consensus log), and what a user sees when two writes conflict. Then change clocks.py so that C sends a message to B after c3, before B writes. Predict the new Lamport and vector timestamps of b1 and b2, run the script, and check whether c3 and b2 are still concurrent.
09. Review prompt
Without looking back:
- Define drift and skew, and give two reasons NTP cannot make skew zero.
- Explain how last-write-wins on wall-clock timestamps can drop a causally later write.
- State the three Lamport clock rules and what L(a) < L(b) does and does not tell you.
- How do you compare two vector clocks, and what do vector clocks cost?
- Which clock would you use to time out a request, and why?
References
- Time, Clocks, and the Ordering of Events in a Distributed System (Leslie Lamport, 1978)
- Distributed Systems lecture notes, sections 3-4 (Martin Kleppmann, University of Cambridge)
- RFC 5905: Network Time Protocol Version 4
- Python documentation: time.time() and time.monotonic()
- Apache Cassandra documentation: Dynamo (data versioning)
- Dynamo: Amazon's Highly Available Key-value Store (DeCandia et al., 2007), section 4.4
- Logical Physical Clocks and Consistent Snapshots (Kulkarni et al., 2014)
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.