Lesson 2 · Unit 01
Clocks lie
Order events without trusting the time
What you practise
- Clock skew and drift, why timestamps can't order events across machines, happened-before, Lamport clocks traced by hand, a first look at vector clocks
Try a question from this lesson
Pick one
Server A stamps a write 10:00:00.120. Server B stamps another 10:00:00.100, but B's clock runs 50 ms slow. Which write really happened first?
Correct answer
A's, although its timestamp is larger
Why
B's true time was .100 + .050 = .150, after A's .120. Sorting by timestamp puts them in the wrong order. Across machines, a timestamp is one machine's opinion, not a fact.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Clocks drift
Every computer keeps time with its own quartz crystal, and no two crystals tick at quite the same rate. Left alone, clocks drift apart. The gap between two clocks is called skew.
Syncing over the network (NTP) pulls clocks back toward the true time, but never exactly, and a correction can make a clock jump, even backwards.
Concept
Lamport clocks
If time cannot be trusted, keep order instead. Each node holds a counter.
Before any event of its own, a node adds 1. Every message carries the sender's counter. On receiving one, a node jumps to the larger of its own counter and the message's, then adds 1.
Now a cause always has a smaller number than its effect.
def tick(clock):
return clock + 1
def receive(clock, stamp):
return max(clock, stamp) + 1
a = tick(0) # A sends at 1
b = receive(0, a) # B receives
print(a, b)Concept
Vector clocks
A Lamport number cannot tell "before" from "unrelated". A vector clock can: each node keeps one counter per node.
A node bumps its own slot on every event. On receiving a message it first takes the larger value in every slot.
X happened before Y only if no slot of X is larger than Y's and the two differ. If each is ahead somewhere, they are concurrent.
def merge(mine, theirs, me):
out = [max(a, b) for a, b
in zip(mine, theirs)]
out[me] += 1
return out
print(merge([2, 0, 0], [1, 3, 0], 0))9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 2× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.