ealeng

Episode 54 of 55 · Clocks and consensus

Clock skew and logical clocks: 47% of messages looked received before they were sent, and the counters never did

Three simulated machines with clocks 10 ms apart stamped 47% of their messages as received before they were sent, and 18% of the causally related pairs less than 200 ms apart were out of order. A Lamport clock, a counter that only moves forward on messages, and a hybrid logical clock never reversed a cause and its effect at any skew up to 100 ms. Only vector clocks flagged the 46% of pairs at 50 nodes that were independent, and at 50 nodes each message carried 357 bytes on average to do it.

Lab 22 · Time, Clocks and Ordering10 min read
Video transcript8:44

0:00Cold open

0:01

I simulated three computers sending each other messages, with clocks set a little apart: one ten milliseconds behind, one right, one ten ahead.

0:12

By their clocks, forty-seven percent of the messages arrived before they were sent.

0:19

Two kinds of counter-based clock got the order right every time, at any setting.

0:25

And with fifty computers, almost half of all pairs of events couldn’t have affected each other. One of those clocks still put an order on nearly every one.

0:36

So how do you tell which event came first, when every clock is a little wrong?

0:43Intro

0:44

Hands-on system design, part fifty-four.

0:48

Today: wall clocks, Lamport clocks, hybrid clocks and vector clocks, and what each can tell you about order.

0:56Meet Lucía

0:57

I’m Lucía, a platform engineer. Our logs come from many machines, and I wanted to know if their timestamps put events in the right order.

1:06

So I used a simulator, not a real network: three computers, or nodes, each doing fifty things a second for ten seconds. Half are messages, and receiving one counts as an event too.

1:20

Each message takes one to ten milliseconds to arrive. Nothing is lost.

1:26

And each node’s clock is set a little off, one behind, one right, one ahead. That gap is called the skew. Because it’s simulated, the simulator knows if B could have heard about A, directly or by a chain of messages. Then A could have caused B.

1:43

Think of letters between three towns. A postmark comes from each town’s own clock. A Lamport clock is a page number: always one more than any page you’ve read. And a vector clock is a list: the last letter you’ve seen from each town.

2:0001 · What you need

2:01

To run it yourself, you need Python and a few packages. The simulator is one short file, and each run takes about a minute or less.

2:11

The quick tests check each clock against its rules, in a couple of seconds. No servers, no cloud.

2:2002 · Wall clocks

2:21

First, the wall clocks: each node stamps every event with its own time of day. With no skew, every message is stamped as sent before it arrives.

2:32

With clocks a millisecond either side: nineteen messages, all between the two clocks two milliseconds apart.

2:41

At ten milliseconds either side: forty-seven percent.

2:46

At a hundred milliseconds: still forty-seven percent. It can’t get worse than that, and I’ll show why.

2:5503 · Why half

2:56

Take a node whose clock is ten milliseconds ahead. It sends a message at true time zero, and stamps it ten.

3:05

The message takes one to ten milliseconds. The receiver’s clock is right, so it stamps the arrival one to ten. Never later than the ten on the send.

3:16

When two clocks are further apart than the slowest message, every message from the fast one to the slow one looks early. That’s three of the six directions, which happened to carry forty-seven percent of messages. Once the skew reaches the longest delay, it’s every one of them, and more skew changes nothing.

3:3704 · Averages hide it

3:38

Now any two events where one could have caused the other. At a hundred milliseconds of skew, the wall clocks got under one percent of those pairs backwards. That sounds fine.

3:50

But only about one causal pair in thirty was under a fifth of a second apart. Among those, the ones you argue about, eighteen percent were backwards, and every reversal was one of them.

4:04

And the counters, Lamport’s and a hybrid one I’ll show next: zero, at every skew.

4:1105 · In code

4:13

Here’s why. A Lamport clock is one counter per node. Every event adds one.

4:19

When a message arrives, the counter jumps past the number the sender stamped on it: the larger of the two, plus one.

4:28

So anything that could have caused an event always has a smaller number. That’s true by design, so the zero is guaranteed, not lucky. The test just confirms the code follows the rule.

4:4206 · A hybrid clock

4:43

But a page number doesn’t tell you when something happened. A hybrid logical clock does both: it keeps the latest time it has seen, on its own clock or on any message, plus a counter for ties.

4:57

At a hundred milliseconds of skew, its time stayed within a hundred milliseconds of the truth. Never more than the skew itself.

5:06

And its counter never went past seventeen. So you can still read it as a time, and it still never puts an effect first.

5:1607 · A clock jumps back

5:17

One more. No skew this time, but halfway through, one node’s clock is set back fifty milliseconds, the way a time-sync service can correct it.

5:28

On that one node, three events got a timestamp earlier than an event before them. With the messages it receives, it does about seventy-seven things a second, so the fifty milliseconds after the jump held three events, and every one of them was stamped too early.

5:45

The counters only go up, so they had none. A wall clock that jumps back can’t even order one machine’s own events.

5:5508 · Independent?

5:56

But some pairs of events aren’t ordered at all: neither could have caused the other. They’re independent, or concurrent. With three nodes, about one pair in two hundred, half a percent.

6:08

I spread the same traffic, with ten milliseconds of skew, over ten and then fifty nodes. How many pairs do you think were independent then?

6:20

Forty-six percent. With fifty nodes, news of an event took a long time to reach most of them. And the Lamport clock gave ninety-eight percent of those pairs an order anyway.

6:32

A vector clock flagged every one of them as independent, and never got a caused pair wrong.

6:40

To be fair: the simulator’s own truth is kept as a vector clock, so this only shows the code is right. In a real system it can’t see causes that travel outside its messages, like two people talking.

6:5509 · In code

6:56

In code: compare the two lists node by node. If every entry of one is at most the other’s, it came first.

7:04

If one is ahead somewhere and behind somewhere else, neither saw the other: independent. That answer is the one a single counter can never give.

7:1510 · The cost

7:17

The price is the list. Every message carries it, as text: about thirty-two bytes with three nodes, three hundred sixty with fifty. One Lamport number fits in eight.

7:29

At fifty nodes the largest was five hundred forty bytes: one entry for every node it had heard from.

7:37

So real databases keep one entry per server holding the data, not one per user, and trim old entries.

7:47Back to Lucía

7:48

So, three lessons.

7:51

Timestamps from different clocks put effects before causes as soon as the skew beats some delays. And averages hide it.

8:00

A counter that moves past every message it reads never does. A hybrid clock does that and still reads as a time.

8:09

And only a vector clock can tell you two events were independent, at the price of a list on every message. In part forty-seven, that’s what last-write-wins was missing.

8:21

Next time: clocks that decide things. Last-write-wins on skewed clocks, and a lease that has to expire on time.

8:29

For today: count, don’t trust the clock.Lucía: Count, don’t trust the clock.

8:33Summary

8:35

Wall clocks misorder once skew beats the delay; counters never do; only vectors see independence.

Key takeaways

  • ✓With each machine's clock up to 10 ms off, 366 of 779 messages (47%) were stamped as received before they were sent, and raising the skew to 100 ms did not raise that share, because once the skew is larger than the 1–10 ms message delay, every message from a fast clock to a slow one already looks early.
  • ✓A Lamport clock, a counter that goes up by one on every event and jumps past the sender's number on every message received, reversed 0 of 148,886 causally ordered pairs at every skew from 0 to 100 ms, but it cannot say whether two events were independent.
  • ✓A vector clock, one counter per node, flagged all 91,458 independent pairs among the 199,911 sampled at 50 nodes (46%) and got none wrong, at a cost of 357 bytes on average per message at that size, against 8 bytes for a Lamport number.
  • ✓Averages hide wall-clock errors: at 100 ms of skew, 956 of 148,886 causal pairs (0.64%) were reversed, but among the 5,989 causal pairs less than 200 ms apart, 1,064 (18%) were reversed, and those are the pairs a system usually has to order.
  • ✓A hybrid logical clock (HLC), which keeps the largest wall time it has seen plus a counter, kept its time within 100 ms of true time at 100 ms of skew, its counter never passed 17, and it reversed 0 causal pairs.

Three machines stamped their messages with their own clocks, and by those clocks almost half the messages arrived before they were sent. This chapter takes apart why, then looks at the two counter-based clocks that never made that mistake, and at the one that could also say when two events had no causal link.

The examples come from Lab 22 (Time, Clocks and Ordering) of the system design labs. This chapter covers the first two scripts, 01_ordering.py and 02_vectors.py. The last-write-wins and lease scripts (03_lww.py and 04_lease.py) are in the next episode, 55. Everything runs in one Python process on a simulated network, so the simulator knows the true order of every event. That is the only reason the lab can say a timestamp was wrong.

Wall clocks and skew between machines

Every machine has a wall clock, the one that shows the time of day. Two wall clocks never agree exactly. The gap between them at a given moment is the skew. The rate at which the gap grows is the drift, and network time sync (NTP) corrects both, sometimes by setting the clock to a new value at once, even backwards.

A timestamp from a wall clock is therefore only as good as the skew. If two machines disagree by 10 ms, a timestamp from one of them can be 10 ms off compared with the other, and that is enough to change which of two close events looks first.

Why a message can appear to arrive before it was sent

Take one node whose clock is 10 ms ahead. It sends a message at true time zero and stamps it 10. The message takes 1 to 10 ms, and the receiver's clock is right, so it stamps the arrival at 1 to 10. That is never later than the 10 on the send, so the receive looks as early as or earlier than the send.

With three nodes there are six directions a message can travel. The skew was spread as one node behind, one right, one ahead. In the lab, the directions that run from a fast clock to a slow one were three of the six, and 47% of messages (366 of 779) were stamped early. Once the skew reaches the longest delay, every message on those directions looks early. More skew adds no more directions, so the share stays at 47%.

Try it · Three nodes, one skew at a timerecorded run, 01_ordering.py
Clock skew
Messages received before sent
366
Causal pairs reversed
51
Close pairs (<200 ms) reversed
45
Lamport or HLC reversed
0
Messages, of 779
47.0%
Close pairs, of 5,989
0.75%

Lamport and HLC timestamps never reversed a cause and its effect at any skew. The HLC time stayed within ±10 ms of true time, and its counter reached at most 5.

Simulated network with 1–10 ms message delays and no losses; the simulator knows the true order. The lab counts close pairs separately from all causal pairs, so the two counts are not subsets of each other. One run per skew.

The NTP step case (-50 ms on node n1, 768 events): wall clock stamped 3 events no later than an earlier one; Lamport and HLC stamped 0.

The table in the widget comes from the lab's first script. At 1 ms of skew only 19 messages (2.4%) looked early, because most of the arrivals were slower than the gap. At 10 ms it jumped to 366, and at 100 ms it was still 366.

Averages hide the errors

Looking at all causally related pairs of events hides most of the damage. Two events are causally related when one could have caused the other: an earlier event on the same machine, or a chain of messages leading from one to the other. In the lab's sample of 148,886 such pairs, most were seconds apart. At 100 ms of skew, only 956 of them (0.64%) were in the wrong order.

The pairs a system usually has to order are the close ones: a write and the read after it, a message and its reply. In the lab's 5,989 causal pairs less than 200 ms apart, 1,064 (18%) were in the wrong order at 100 ms of skew. The lab reports the two as separate counts. The close-pair count (1,064) is larger than the all-pairs count (956), so do not read one as a subset of the other.

Lamport clocks: a counter that only moves forward

A Lamport clock is one counter per node. It goes up by one on every event, and when a node receives a message it jumps to one more than the larger of its own counter and the number the message carries. Think of it as a page number in a set of letters: always one more than any page you have read.

The rule guarantees that a cause always has a smaller number than its effect, because every receive moves the counter past what was sent. It never reads the wall clock, so skew cannot break it. The lab found 0 reversed causal pairs at every skew from 0 to 100 ms. That is by design, not luck.

The price is what the counter cannot say. A Lamport number that is smaller for one event than another does not mean the first caused the second. Concurrent events, the ones with no causal link, also get an order, and that order is arbitrary.

Vector clocks: one counter per node

A vector clock keeps one counter per node, and each message carries the whole list. To compare two events, you look at the lists node by node. If every entry of one is no larger than the other's, the first could have caused the second. If one is larger in some entries and smaller in others, neither could have caused the other, so the two are concurrent. A single counter can never give that third answer.

The cost is the list itself. It grows with the number of nodes that have written, and it is carried on every message. The lab measured it at 3, 10 and 50 nodes.

Try it · Same traffic, more nodesrecorded run, 02_vectors.py
Nodes
Truly concurrent pairs
91,458
Vector clock flagged
91,458
Lamport gave an order
89,404
Vector size, mean
357 B
Concurrent, of 199,911 pairs
45.7%
Ordered by Lamport anyway
97.8%

Vector clocks got every pair right: 0 wrong directions and no causal pair flagged as concurrent. A Lamport timestamp is 8 bytes; the vector grew to a largest of 540 bytes on a message.

Simulated network at ±10 ms skew, 150 events a second across all nodes. The vector's "0 wrong" is by construction: the simulator's truth is kept as the same kind of vector. One run per node count. The "Ordered by Lamport" bar is a share of the concurrent pairs.

Hybrid logical clocks: a counter that still reads as a time

A Lamport number says nothing about when something happened. A hybrid logical clock (HLC) keeps the largest wall time it has seen, from its own clock or from any message, and adds a counter to break ties. Its time can therefore be read and compared with a real time, and it still never puts an effect before its cause.

At 100 ms of skew, the lab's HLC time stayed within 100 ms of true time, never further. Its counter reached 17 at most. It reversed 0 causal pairs, the same as the Lamport counter. This is the kind of timestamp that a database can use for transactions and still show a person as a time.

The workflow and the results

The lab's simulator, simnet.py, runs three nodes that exchange messages. Each node does 50 things a second for 10 seconds, half of them sends, and each message takes 1 to 10 ms. The nodes stamp every event with four kinds of timestamp: the wall clock, a Lamport counter, an HLC and a vector. clocks.py holds the three counter rules, and workload.py drives the chatting nodes.

Script 01, ordering. It runs the nodes at skews of 0, 1, 10 and 100 ms, with one wall clock per node spread as one behind, one right and one ahead. For 300,000 random pairs of events and every message, it asks whether each timestamp puts the cause first. Then it steps one node's wall clock back 50 ms and checks the events stamped after the step.

Skew Wall clock: all causal pairs reversed Close pairs (<200 ms) reversed Messages received before sent Lamport HLC
0 ms 0 of 148,886 0 of 5,989 0 of 779 0 0
±1 ms 0 3 (0.05%) 19 (2.4%) 0 0
±10 ms 51 (0.03%) 45 (0.75%) 366 (47%) 0 0
±100 ms 956 (0.64%) 1,064 (18%) 366 (47%) 0 0

With the wall clock of one node stepped back 50 ms at 5 seconds, 3 of that node's 768 events were stamped no later than an earlier event on the same node. Lamport and HLC had 0.

Script 02, vectors. It spreads the same traffic, 150 events a second across all nodes at ±10 ms of skew, over 3, 10 and 50 nodes. It samples 200,000 pairs of events for each count and compares each with the truth.

Nodes Truly independent pairs Vector clock flagged independent Wrong direction Lamport gave an order to Vector size, mean Largest vector A Lamport number
3 1,093 (0.5%) 1,093 0 975 32 bytes 33 bytes 8 bytes
10 9,997 (5.0%) 9,997 0 9,621 102 bytes 110 bytes 8 bytes
50 91,458 (46%) 91,458 0 89,404 357 bytes 540 bytes 8 bytes

Two things stand out. Independence grows with the node count: with the same traffic spread over more nodes, each node hears from each other node less often, so almost half the pairs were independent at 50 nodes. And the Lamport clock put an order on 98% of those pairs anyway, so a system that detected conflicts with Lamport numbers would see almost none.

Caveats

  • One run per setting. Each row is one recorded run. The simulator is deterministic, so the same seed gives the same numbers, and another seed is another run.
  • The simulator knows the truth. Causes in the lab are only the messages the simulator sends. In a real system, two people talking in a room, or an action outside the system, can make one event a cause of another without any message the clocks can see.
  • The vector clock's zero wrong is by construction. The simulator keeps its own hidden vector clock to decide what was truly causal, so script 02 shows the code follows the rule, not that vectors are perfect in the wild.
  • The skew values are set, not measured. The simulator is given offsets of 0, 1, 10 and 100 ms. The numbers show what skew of that size does; they do not measure how large skew is on real machines.
  • Three to 50 nodes. The lab does not test larger clusters or the cost of pruning a vector (dropping old entries), which real stores do to keep the list short.
  • Not covered here: last-write-wins and leases, which depend on these clocks and are the subject of episode 55, and Spanner's TrueTime, which gives a time interval with a bounded error and waits it out; the lab lists a TrueTime-style version as an exercise.

The checklist

  1. Assume wall clocks disagree by the skew. Once the skew is bigger than the shortest delay between two machines, a message can look as if it arrived before it was sent.
  2. Look at close pairs, not averages. A small share of all pairs can hide a large share of the pairs you care about.
  3. Use a Lamport or HLC number to keep causes before effects. Both kept 0 reversed causal pairs at every skew in the lab.
  4. Use a vector only when you need to know that two events were independent. It costs a list on every message, and the list grows with the nodes that write.
  5. Prefer an HLC when a person will read the time. It stays within the skew of real time and still never reverses a cause.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.Two machines' clocks are up to 10 ms apart and messages take 1 to 10 ms. In the lab, what share of messages were stamped as received before they were sent?

  2. 2.A node whose counter is 3 receives a message stamped 7. What should its Lamport counter become?

  3. 3.At 50 nodes, 91,458 pairs of events were independent. What did a Lamport clock do with them, and what did a vector clock do?

Check your understanding

Try each question before opening its answer.

Why did the lab's Lamport clock never reverse a cause and its effect, even at 100 ms of skew?

Because the Lamport rule never reads the wall clock. Each event adds one, and a receive jumps the counter to one more than the larger of its own value and the sender's stamp. So a cause always has a smaller number than its effect, whatever the wall clocks say.

At 100 ms of skew only 0.64% of causal pairs were reversed. Why is that figure misleading?

Most causal pairs in the sample were seconds apart, so a skew of 100 ms rarely crossed the gap between them. Among the 5,989 causal pairs less than 200 ms apart, 1,064 (18%) were reversed. Those close pairs are the ones a system usually has to order.

A vector clock flagged every independent pair correctly. Why not use vector clocks everywhere?

The vector is carried on every message and grows with the number of nodes that have written. The lab measured a mean of 32 bytes at 3 nodes and 357 bytes at 50, with a largest of 540, against 8 bytes for a Lamport number. You pay for the list only when you need to know two events were independent, for example to detect a conflicting write.

A hybrid logical clock and a Lamport clock both reversed 0 causal pairs. What does the HLC add?

It keeps its time within the clock skew of true time: at 100 ms of skew, the HLC time stayed within 100 ms of the real time, and its counter never passed 17. A Lamport number has no time in it at all, so the HLC is the one you can show to a person as a time while keeping the cause-before-effect guarantee.

Next up: Chapter 55, clocks that decide things: last-write-wins on skewed clocks, and a lease that has to expire on time.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.