ealeng

Episode 55 of 55 · Clocks and consensus

Skewed clocks lost 39% of updates; a hybrid clock lost none to older writes; a lease broke past its bound

Three replicas, with clocks 100 ms apart, took 925 updates under last-write-wins. With wall clocks, 359 of them (39%) vanished, though every client had been told OK; with a hybrid logical clock, 48 (5%) vanished, the same share as with perfect clocks. Then a one-second lease whose margins assumed a clock within 500 ppm: when a client's clock ran 20,000 ppm slow, its leases had a second holder almost every time, and when NTP stepped the clock back 50 ms each second, all 35 of its wall-clock leases overlapped.

Lab 22 · Time, Clocks and Ordering11 min read
Video transcript10:01

0:00Cold open

0:01

I kept three copies of one value, each taking updates, and set their clocks a hundred milliseconds apart.

0:09

Thirty-nine percent of the updates vanished, though each had been acknowledged. Nothing reported an error.

0:17

With a different kind of clock: five percent, about the same as with perfect clocks.

0:24

Then a lock: when I made time sync pull one client’s clock back every second, every lease it held had a second holder.

0:33

So how does a clock end up deciding who wins? And how do you stop it deciding wrong?

0:41Intro

0:42

Hands-on system design, part fifty-five.

0:46

Today: last write wins on ordinary clocks and on a hybrid clock, and leases that trust a clock.

0:54Meet Lucía

0:55

I’m Lucía, a platform engineer. Our data lives in several copies, called replicas. When two copies disagree, the one with the later timestamp wins. That’s last write wins.

1:08

Every copy applies the same rule, so they all end up agreeing. Part forty-seven showed what that rule costs when two regions write at once.

1:18

Most updates are read, modify, write: read the value, add one thing, write it back. So a new write should always be newer than what it read.

1:28

And a lease is a lock that runs out on its own. Hold it for a second; after that, someone else may take it.

1:36

Think of offices sharing a board. Each office keeps a copy of the board; the note with the latest time stays.

1:44

But the offices’ watches disagree: that’s clock skew. A lease is a meeting room booked for an hour, by my watch.

1:5301 · What you need

1:54

This one needs no Docker and no cloud: it’s a simulation. A small program plays the network, the delays and every clock, so it always knows the true order of events.

2:07

The quick tests, including the clocks and the simulator, pass in a couple of seconds.

2:1402 · The test

2:15

Three copies of one value, for a simulated minute. The value is a list of update ids: each update adds its own, so the final list shows which ones survived.

2:27

Each copy takes about five updates a second, at random: nine hundred twenty-five in all. Each client hears OK as soon as one copy takes its update, as in Cassandra.

2:40

The rule: keep a write only if it’s stamped later than what this copy holds. Messages between copies take one to ten milliseconds.

2:5103 · Perfect clocks

2:52

First, perfect clocks. Forty-seven updates were missing at the end: five percent.

2:59

Those were concurrent: two updates made so close together that neither copy had heard of the other yet. Last write wins has to drop one. Five percent here, at these rates and delays.

3:1304 · Skewed clocks

3:15

Now the clocks a hundred milliseconds apart: one copy behind, one on time, one ahead. Ordinary time-of-day clocks, also called wall clocks.

3:26

How many updates do you think went missing?

3:31

Three hundred fifty-nine: thirty-nine percent. The copies all agreed on the final value, and every client had been told OK.

3:41

Across the three copies, an older write won over a newer one nine hundred eighty-two times. One update can lose at each copy, so that’s more than nine hundred twenty-five.

3:5505 · Whose updates

3:56

Whose updates vanished? The copy whose clock ran ahead lost none.

4:02

The copy on time lost forty-one percent: it’s still a hundred milliseconds behind the copy ahead.

4:10

And the copy a hundred milliseconds behind lost seventy-eight percent.

4:16

Here’s why. That copy reads a value stamped by a clock set ahead of it, adds its update, and stamps it with its own, earlier time. Earlier loses: at the other copies, and at itself.

4:3006 · In code

4:31

In code: read the value, add the new id, and stamp it with this copy’s clock.

4:37

Then the same rule as for any write: keep it only if its stamp is later than what this copy holds.

4:45

Otherwise, it’s ignored. And the client has already been told it worked.

4:5107 · A hybrid clock

4:53

The fix is a hybrid logical clock, from part fifty-four. It reads like the time of day, but it never goes behind anything this copy has already seen. A small counter breaks ties.

5:06

When a copy sees a write, its clock jumps past that write’s time. So an update made after reading a value is always stamped after it.

5:16

The same skew, with a hybrid clock: forty-eight missing, five percent. Not one update lost to an older write.

5:26

That’s by design, not luck: the rule makes it impossible.

5:3208 · The clock in code

5:33

In code: when a write arrives, take the largest of three times. What the clock already had, the write’s own stamp, and the time of day.

5:43

And keep it. The next stamp this copy makes starts from there.

5:4909 · Order, not merge

5:50

But notice: five percent, about the same as perfect clocks. Those are the concurrent updates. It still can’t keep both.

5:59

A better clock fixes the order, not the merge. To keep both of two concurrent updates, you have to merge them, like part forty-seven’s counters and sets.

6:1110 · A lease

6:13

Now the second job: a lease. A lock lets only one client do something at a time.

6:20

A lock server lends a one-second lease to one of three clients at a time. It waits a full second, on its own clock, before lending it to anyone else.

6:30

The design assumes every clock runs within five hundred parts per million: half a millisecond off per second. So the client gives up one millisecond early, twice that, in case both clocks are off, timing from when it asked.

6:46

Then one client’s clock runs slow, so its second lasts longer than a real one. Each setting is simulated for two minutes.

6:5611 · Past the bound

6:57

Within the bound: no handover, where one client’s lease passes to the next, ever had two holders.

7:05

At four times past the bound: still none, in this run.

7:10

At ten times past: one handover overlapped.

7:16

At twenty thousand, forty times past the bound: thirty-eight overlaps, by up to fifteen milliseconds. That’s every one of its leases that had a next holder.

7:2812 · The hidden margin

7:29

Why did it hold so far past its bound? The margin in the design was one millisecond.

7:36

With perfect clocks, between one holder stopping and the next one starting, there were always more than three milliseconds, typically nine. Only one millisecond of that was written down.

7:49

It’s the request’s trip to the server, the wait for the next client to ask, and the lease’s trip to that client.

7:57

At five thousand parts per million, a lease ran five milliseconds past where it should have stopped: more than the smallest gap, and it overlapped once.

8:08

Make the network faster, or count from the grant instead of the request, and that hidden margin shrinks.

8:1613 · A clock that jumps

8:18

Last, no drift at all. Instead, a harsh test: time sync steps the client’s time-of-day clock back fifty milliseconds, every second.

8:29

With the lease timed on that clock: all thirty-five of its leases had two holders. A lease lasts about a second, so every one met a step.

8:39

Timed on the monotonic clock, which only ever counts forward and is never stepped: none.

8:46

And even a correct lease needs a fencing token, from part forty-four: a rising number the storage checks, so a paused old holder’s writes are refused.

8:5814 · The clock in code

9:00

In code, the whole difference is which clock this one line reads.

9:05

And here’s the written margin: one second, minus a millisecond, timed from the request.

9:13Back to Lucía

9:15

So, three lessons.

9:17

Last write wins on time-of-day clocks threw away newer updates, with no error. A hybrid clock never did.

9:26

A better clock fixes the order, not the merge. Concurrent updates still lose one side.

9:33

And write your clock bound down, and time leases on the monotonic clock.

9:39

Next time: Raft, how a group of servers agrees on one leader, using counters instead of the time of day.

9:47

For today: don’t let the time of day decide.Lucía: Don’t let the time of day decide.

9:51Summary

9:53

Stamp with a hybrid clock, merge what’s concurrent, and time leases on the monotonic clock.

Key takeaways

  • ✓Last write wins keeps the update with the later timestamp, so when the replicas' wall clocks were 100 ms apart, the copy that was behind stamped its update earlier than the value it had just read, and 359 of 925 updates (39%) were thrown away at every replica, though each client had been told OK.
  • ✓With perfect clocks, last write wins still lost 47 of 925 updates (5%), but those were concurrent: made so close together that neither replica had heard of the other, so one side has to be dropped, and it does not matter what the clocks say.
  • ✓A hybrid logical clock (HLC: a wall-clock time plus a counter that never goes back) lost 48 of 925 updates (5%) at ±100 ms of skew, and not one update to an older write, because each replica moves its clock past every write it has seen before it stamps its own.
  • ✓An HLC fixes the order of updates but not the merge: its 48 losses are concurrent updates, which only a merge rule can keep, such as the conflict-free counters and sets (CRDTs) of part 47.
  • ✓A one-second lease was written with margins for a clock within ±500 ppm (parts per million, where 500 ppm is half a millisecond per second); a client whose clock ran 20,000 ppm slow had 38 of its 39 leases followed by a second holder, overlapping by up to 15.27 ms, while 0 handovers overlapped at 2,000 ppm.
  • ✓The design wrote down a 1 ms margin, but the real gap between one holder stopping and the next starting was more than 3 ms and typically about 9 ms, which is why the lease held four times past its bound.
  • ✓When NTP (the network time protocol that corrects clocks) stepped one client's wall clock back 50 ms every second, all 35 of its leases timed on that clock had a second holder, overlapping by up to 92.8 ms, and the same leases timed on the monotonic clock (which never steps) had none in 38.

Three copies of one value took 925 updates. With their wall clocks 100 ms apart, 39% of them vanished, and no one saw an error. With a hybrid clock, 5% vanished, the same share as with perfect clocks. Then the chapter turns to leases, a lock that expires on its own, and what happens when the clock that times it is wrong. This chapter covers both: last write wins, a hybrid logical clock, and leases with the clock bounds they assume.

The examples come from Lab 22 (Time, Clocks and Ordering) of the system design labs: script 03_lww.py for the replicas and 04_lease.py for the lease. Both are simulations. A seeded program plays the network, the delays and every clock, so it knows the true order of events. The lab runs in Python only, with no Docker and no cloud. Results are recorded on an Apple M4 Max.

Last write wins, and how skew decides it

Data often lives in several copies called replicas. When two replicas disagree, last write wins (LWW) says the one with the later timestamp is kept. Every replica applies the same rule, so they all end up agreeing, which is the point of it. The cost shows up when the timestamps come from clocks that disagree.

Most updates are read-modify-write: read the current value, add one thing, write it back. The new write is supposed to be newer than the value it read. A wall clock, the ordinary time-of-day clock, does not guarantee that. If the replica that makes the write has a clock behind the one that stamped the value it read, its own write is stamped earlier, and LWW keeps the older value everywhere. The client gets its OK; the update is gone.

In the lab, each of three replicas took about five updates a second for a minute, reading, appending its update's id and stamping it, then sending it to the other two. A replica keeps a write only if its stamp is later than the one it holds, and it checks its own writes this way too. Every discarded write was checked against the simulator's knowledge of the true order.

Try it · Last write wins, wall clock vs hybrid clockrecorded run, 03_lww.py (simulated)
skew ±0 ms47 of 925 missing (5%)

older write thrown away in favour of a newer one, at a replica: 0 times

skew ±100 ms359 of 925 missing (39%)

older write thrown away in favour of a newer one, at a replica: 982 times

Both clocks lose about 5% to concurrent updates, which last-write-wins must choose between. Only the wall clock with skew throws away later updates in favour of earlier ones.

  • Perfect clocks: 47 of 925 updates were missing from the final value (5%). None was thrown away for an older write; all 47 were concurrent, made within a network delay of each other, so LWW had to pick one.
  • Wall clocks, ±100 ms of skew: 359 of 925 were missing (39%), and 982 rejections were older writes thrown away in favour of a newer stamp. Clients had been told OK for all of them.

The video replay shows which copy paid. The replica whose clock was 100 ms behind lost 78% of its own updates; the one on time lost 41%; the one 100 ms ahead lost none, because its stamps were never earlier than what it read. The per-replica figures come from that replay, not from the committed results file, but the total matches the results.

A hybrid logical clock

A hybrid logical clock (HLC) keeps the look of a time of day and adds a counter to break ties. It has one rule the wall clock lacks: when a replica receives a write, its clock jumps forward to at least that write's time, and the next stamp it makes starts from there. The clock never goes behind anything the replica has seen, so an update made after reading a value is always stamped later than that value.

The lab's HLC takes the largest of three times: the clock's current value, the stamp on the arriving write and the replica's own time of day. Then it keeps that value for its next stamp.

With the same ±100 ms of skew, the HLC lost 48 updates (5%), and none to an older write. The 48 are concurrent losses: the same kind as with perfect clocks. An HLC fixes the order; it does not merge two updates that were made at the same time. Keeping both would need a merge, such as the conflict-free counters and sets (CRDTs) of part 47.

Leases: a right to act that runs out

A lease is a lock that expires on its own. A lock server grants one client the right to act for one second; after that, the server may grant it to someone else. The lease is only safe if the client and the server agree about when a second is over, and each of their clocks may run a little fast or slow.

The design in the lab writes down the assumption. Every clock's rate is within ±500 ppm (parts per million: 500 ppm is half a millisecond per second, 100 ppm is about 8.6 seconds a day). Two margins follow from that:

  • The client counts its lease from when it sent its request, which is earlier than the grant, and it stops after 1 s × (1 − 2 × 500 ppm), which is 999 ms on its own clock. The 1 ms is the margin the design wrote down.
  • The server grants the lease to someone else only after 1 s on its own clock.

The lab used three clients asking for the lease every 10 ms, with delays of 1 to 5 ms. One client's clock ran slow by 0 to 20,000 ppm, so it believed its lease lasted longer than it did. The simulator checked every handover in true time: did the old holder still believe it held the lease after the new holder got it?

Try it · A lease past its clock boundrecorded run, 04_lease.py (simulated)
slow by 0 ppm (within the 500 ppm bound)0 of its 38 leases had a second holder

longest overlap: none

slow by 200 ppm (within the 500 ppm bound)0 of its 40 leases had a second holder

longest overlap: none

slow by 500 ppm (within the 500 ppm bound)0 of its 40 leases had a second holder

longest overlap: none

slow by 1,000 ppm (past the bound)0 of its 38 leases had a second holder

longest overlap: none

slow by 2,000 ppm (past the bound)0 of its 38 leases had a second holder

longest overlap: none

slow by 5,000 ppm (past the bound)1 of its 37 leases had a second holder

longest overlap: 0.23 ms

slow by 20,000 ppm (past the bound)38 of its 39 leases had a second holder

longest overlap: 15.27 ms

Bars show the slow client's leases that had a second holder. The last lease of each run had no next holder to overlap, so 20,000 ppm shows 38 of 39. Each setting ran 120 s (119 leases per run, simulated).

When a lease outlives its bound

Within the bound, no handover ever had two holders. Past it, the result depends on how far:

  • At 2,000 ppm (four times the bound): no handover overlapped across the slow client's 38 leases.
  • At 5,000 ppm (ten times the bound): 1 handover overlapped, by 0.23 ms.
  • At 20,000 ppm (forty times the bound): 38 handovers overlapped, by up to 15.27 ms, and 409 ms in total. The slow client had 39 leases; the last had no next holder to overlap.

Why did it hold so far past its bound? Because the design's margin was not the whole margin. Counting from the request, the lease also absorbed the request's trip to the server, the wait for the next client to ask, and the grant's trip back. In the video's replay with perfect clocks, the gap between one holder stopping and the next starting was more than 3 ms and typically about 9 ms. Only 1 ms of it was written down. At 5,000 ppm, the slow client's lease ran about 5 ms past where it should have stopped, which is more than that smallest gap, and it overlapped once. This hidden margin is arithmetic plus the replay's measurements, not something the lab's results file records. A faster network, or counting from the grant instead of the request, would shrink it, and the design would then fail sooner.

NTP steps: a clock that jumps

The last test had no drift at all. Instead, NTP stepped the client's wall clock back 50 ms once every second. A step is a jump, not a slow drift, and a lease lasts about a second, so every lease met a step.

  • Timed on the wall clock: all 35 of the client's leases had a second holder, overlapping by up to 92.8 ms. Two steps can land in one lease, which is why the longest overlap is much larger than 50 ms.
  • Timed on the monotonic clock: none of its 38 leases had a second holder. The monotonic clock only counts forward and is never stepped by NTP, though it still drifts.

A lease that is timed correctly still needs a fencing token (part 44): a number that rises every time the lease is granted, which the storage checks, so a holder paused past its lease cannot write with an old number.

The workflow and the results

The 03_lww.py script runs three replicas with skews of 0 and ±100 ms, once with wall clocks and once with HLCs, for 60 seconds each. The 04_lease.py script runs one client through seven clock rates, 120 seconds each, then the two NTP variants at 0 ppm. Each setting uses one seed (seed 1), so each row is a single recorded run.

Skew Timestamps Updates Missing from final value Thrown away for an older write Concurrent rejections
±0 ms wall clock 925 47 (5%) 0 60
±0 ms HLC 925 47 (5%) 0 60
±100 ms wall clock 925 359 (39%) 982 65
±100 ms HLC 925 48 (5%) 0 70

Rejections are counted at each replica, so a single update can be rejected at two replicas and the count can exceed the number missing.

Clock rate of one client, against the ±500 ppm bound Handovers with two holders Longest overlap Its leases
0, 200, 500 ppm (within the bound) 0 none 38 to 40
1,000, 2,000 ppm (past it) 0 none 38
5,000 ppm 1 0.23 ms 37
20,000 ppm 38 15.27 ms 39
0 ppm, clock stepped back 50 ms every second Leases with two holders Longest overlap
Lease timed on the wall clock 35 of 35 92.8 ms
Lease timed on the monotonic clock 0 of 38 none

Caveats

  • Everything is simulated. The network, the delays (1 to 10 ms for updates, 1 to 5 ms for leases) and every clock are the lab's model. The lab's own table has no real network or real NTP daemon behind it.
  • One seed per setting. Each row is one recorded run. The 5% concurrent loss depends on this workload's rates and delays, and is not a general rate.
  • The overlaps are small in number. The single 5,000 ppm overlap is one event. The 20,000 ppm result is the clearer one.
  • The hidden margin is not in the results file. The 3 to 9 ms gap and the 78%, 41% and 0% per-replica losses come from the video's replay of the same run, which reproduces the committed totals. The committed JSON has only the totals.
  • HLC's zero is by construction. The rule makes an update after a read always later, so zero losses to older writes is guaranteed, not measured. Its 5% concurrent losses are measured.
  • Not tested: an HLC maximum-offset rule (refusing a stamp far ahead of the local clock), fencing tokens in the lab's own code, counting the lease from the grant, and the overlaps in a real cluster. The lab lists some of these as exercises.

The checklist

  1. Don't let the time of day decide. Last write wins on wall clocks drops causally later updates whenever the clock behind stamps an earlier time.
  2. Stamp with a hybrid clock so an update made after a read is always later than the value it read.
  3. Merge what's concurrent. A better clock fixes the order, not the choice between two concurrent updates.
  4. Write the clock bound down, and test past it. A lease is only safe while the clock bound it assumed holds, and the margin you didn't write down is the one you'll remove.
  5. Time leases and timeouts on the monotonic clock, and add a fencing token for anything a paused holder could still write.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.A replica whose clock is 100 ms behind reads a value stamped by a replica whose clock is 100 ms ahead, adds its own update and stamps it with its own clock. With last write wins on wall clocks, what happens to that update?

  2. 2.At ±100 ms of skew, the hybrid logical clock lost no update to an older write. Why, when its replicas' clocks were still 100 ms apart?

  3. 3.A lease lasts one second and is written for clocks within 500 ppm. A client's clock runs 20,000 ppm slow, so its lease lasts longer than it should. What happens in the lab?

Check your understanding

Try each question before opening its answer.

Why did last write wins lose 982 later writes at ±100 ms of skew, when the replicas' clocks were just 100 ms apart?

A replica whose clock was behind read a value stamped by a clock that was ahead, then stamped its own update with its earlier time. Every replica keeps the value with the later stamp, so it threw the update away in favour of the older write it had already held. The client had been told OK. The count of 982 is at each replica, so one update can be counted more than once.

What does the hybrid logical clock fix, and what does it still lose?

It fixes the order: a replica's clock moves past every write it has seen, so an update made after reading a value is always stamped later, and the lab recorded no losses to older writes. It still loses concurrent updates, the 48 of 925 (5%) at ±100 ms, because two writes made within a network delay of each other have no order to keep. Only a merge rule can keep both.

A lease counts from when the request was sent and stops 1 ms early. Why did it hold to 2,000 ppm, four times its bound?

The design's margin was 1 ms, but the real gap between one holder stopping and the next starting was more than 3 ms and typically about 9 ms. The extra came from the request's trip to the server, the wait for the next client to ask, and the grant's trip back. Only the 1 ms was written in the design, so the lease held well past the bound the design assumed.

Why did the monotonic clock avoid all overlaps when the wall clock had 35 of 35 leases overlapped by an NTP step?

The monotonic clock only counts forward and is never stepped by NTP, so a 50 ms step in the wall clock doesn't change how long the client thinks its lease has run. It still drifts at its own rate, which is why the design still has a bound. The steps are the part a lease can't survive on a wall clock.

A client has been granted a lease and then pauses for longer than the lease. Why does a correct lease still need a fencing token?

The lease tells the client when it may act, but it cannot stop a paused client from acting after the lease has ended, because the pause is outside the lease's control. A fencing token is a number that rises with each grant. The storage refuses writes with an older number, so a paused old holder's late write is rejected.

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.