Failure and Time

Two servers never share one clock. Let one clock drift past a message's 10 ms trip, and a log sorted by wall-clock time puts a reply before its request. A Lamport or hybrid clock never does.

Drag B's clock skew past 10 ms either way and watch the merged log break. Then switch to Lamport and to the hybrid clock. Then we build, piece by piece, how to suspect a dead node, how to sync clocks, and how to order events without trusting them.

You need a little Python and what a message between two machines is. Network Foundations and Service Communication help. We build the rest from zero.

Sort one log by three kinds of clock

−25 ms

Illustrative toy: A sends a write to B, B stores it and sends an acknowledgement, and each message takes 10 ms. A's clock is right. B's clock is off by the skew you set. Chapters 5 and 7 give the rules for the stamps.

Chapter 0

Slow or Dead? Before or After?

Lose the shared clock and the sure crash, then see which timing rules let a timeout work

On one machine, order comes free. Write event A to a log, then event B, and A comes first. If the program crashes, it stops, and you know.

Spread the work over three machines and both of those go. Each machine has its own clock, and the clocks disagree by milliseconds or more. Each machine sees the others only through messages, and a message can be slow or lost. So two questions get hard. Is that node dead, or slow? Did this event happen before that one?

The answers depend on the system model: the rules you assume about timing. Three models matter.

Pick a model and drag the timeout. Each reply that lands after the timeout is a live node you would have called dead.

Look for a safe timeout

Each bar is one reply from a live node. Yellow is your timeout. Red bars came after it. Pick a model, then drag the timeout.

500 ms

Illustrative delays from a fixed seed. Every node here is alive; the only question is how long its reply takes. Bars taller than the screen stop at its top edge.

In the asynchronous model no timeout is safe. In 1985 Fischer, Lynch and Paterson proved a stronger result, now called FLP. In an asynchronous system where even one process may crash, no deterministic algorithm can guarantee that the processes agree on a value.

Real systems escape by assuming partial synchrony. Raft and Paxos never break safety, whatever the delays, and they make progress once the network settles. This lesson also assumes crash-recovery failures: a node may stop and later restart from its disk, but it never lies. Nodes that lie are Byzantine, a harder case.

Failure. Symptom: the cluster fails over during every long garbage-collection pause. Measure: failover times lined up against the GC log. Cause: a timeout tuned as if the network were synchronous. Fix: set timeouts from measured tail delays, and treat a timeout as a suspicion, not a verdict.

  1. Timeouts: heartbeats, and how long a crash takes to notice.
  2. Phi: suspicion as a number that adapts to the network.
  3. NTP: clocks drift, and NTP pulls them back.
  4. TrueTime: a clock that reports its own error, and the wait it buys.
  5. Lamport: order by cause, with one counter.
  6. Vector: one counter per process, to spot concurrent events.
  7. HLC: a counter that stays close to real time.
  8. Showcase: four clocks on the same random events.
  9. In code: wall clock, monotonic clock and the leap second.
  10. The field guide: numbers, checklist, code and links.
In a partially synchronous model, which statement is true?

Chapter 1

Heartbeats and Timeouts

Send a heartbeat every interval, suspect after a timeout, and trade false alarms against slow detection

Node A wants to know if node B is alive. B sends a small heartbeat message every Δ milliseconds. A restarts a timer each time one arrives. If the timer reaches the timeout T with no heartbeat, A suspects B.

A suspects; it never knows. A crashed process and a process frozen by a long garbage-collection pause send the same nothing. A pause longer than the timeout gives a false positive: a live node called dead. A longer timeout avoids that, but then a real crash goes unnoticed for longer.

How long does A take to notice a crash? Call the time between heartbeats the interval Δ, and the timeout T. Call the time from the crash to the suspicion the detection delay D.

Say it aloud

T minus delta is less than D, and D is at most T.

D
D the detection delay: from the moment B crashes to the moment A suspects it, in milliseconds.
T
T the timeout: how long A waits after the last heartbeat. "At most T" is the sign ≤.
T − Δ
T minus delta the timeout less the heartbeat interval Δ. "Less than" is the sign <.
In plain words

The last heartbeat before the crash came at most Δ earlier. A's timer fires T after that heartbeat. So D lands between T minus Δ and T. The same sum gives the pause rule: a pause shorter than T minus Δ never trips the timer.

With numbers

With made-up numbers: Δ = 250 ms and T = 1,000 ms. A notices a crash 750 to 1,000 ms after it. A 500 ms pause is safe, because 500 is less than 750. At 1,000 requests a second, up to 1,000 requests go to the dead node first.

Tune the timeout

Blue ticks are heartbeats every 250 ms. Pink spans are pauses; the red cross is the crash. A red mark on A's row is a false alarm, green is the crash caught. Drag the timeout.

1,000 ms

Illustrative: pauses of 400, 900 and 1,600 ms and a crash at 12.13 s. A paused node sends nothing, then resumes at once. Network delay is left out, so the gaps are exact.

Kubernetes makes the same trade on purpose. Its probe defaults are a 10 s period, a 1 s timeout and 3 failures before it acts. So a hung container restarts after about 30 s. A restart is costly, so it accepts slow detection to avoid false alarms.

Failure. Symptom: leader elections every few hours, with no crash in any log. Measure: the longest heartbeat gaps against the GC pause log. Cause: T − Δ is shorter than the longest pause. Fix: raise T, shorten the pauses, or use the adaptive detector of the next chapter.

B sends a heartbeat every 200 ms, and A's timeout is 1,000 ms. B crashes. When does A suspect it?

Chapter 2

Suspicion as a Number: Phi Accrual

Learn how B's heartbeats usually arrive, then turn a silence into a suspicion level

A fixed timeout ignores what A has learned about B. If B's heartbeats arrive 1,000 ms apart, give or take 20 ms, a gap of 1,300 ms is alarming. If they wander by 400 ms, the same gap is normal.

The phi accrual failure detector (Hayashibara and others, 2004) turns this into a number. A keeps the last few hundred gaps between heartbeats and fits their mean μ and standard deviation σ. As the silence grows, A asks: how often does a live node leave a gap this long?

Call the time since the last heartbeat t. Call F(t) the chance that a normal gap is at most t, read from the fitted bell curve. The suspicion level is φ (phi).

Say it aloud

Phi equals minus log base ten of one minus F of t.

φ
phi the suspicion level. 0 means no doubt; each step of 1 means ten times rarer.
1 − F(t)
one minus F of t the share of live gaps longer than t, the time since B's last heartbeat. F of t is the share at most t.
−log10
minus log base ten counts the powers of ten: 0.01 gives 2, 0.001 gives 3.
In plain words

Find how rare a silence of t is for a live node: one minus F of t. Count the powers of ten in that chance. The count is phi. Phi 1 means one live gap in 10 is this long; phi 3 means one in 1,000.

With numbers

With made-up numbers: μ = 1,000 ms and σ = 200 ms. At t = 1,500 ms, 1 − F = 0.0062, so φ = 2.2. At t = 2,000 ms, 1 − F = 0.00000029, so φ = 6.5. φ reaches a threshold of 8 at t = 2,122 ms.

Watch suspicion rise

Top: the gaps a live B leaves, with the share longer than your silence shaded pink. Bottom: phi as the silence grows; the dashed line is the threshold 8. Drag both sliders.

200 ms
1,500 ms

Illustrative: gaps modelled as a bell curve with mean 1,000 ms, as in the 2004 paper. The device computes the tail exactly, so φ stays finite far out.

The application picks the threshold. Cassandra's phi_convict_threshold defaults to 8, though it models the gaps with a simpler exponential curve. A jittery network widens σ, so the same threshold waits longer. At σ = 50 ms, φ reaches 8 at 1,281 ms. At σ = 400 ms, it takes 3,245 ms.

Theory says what to hope for. Chandra and Toueg (1996) grade detectors by completeness (every crashed node is in the end suspected) and accuracy (live nodes are not). An eventually perfect detector may wrongly suspect for a while, then stops for good. Even weaker detectors are enough for consensus while a majority of nodes stays up.

Failure. Symptom: the cluster marks a node dead each time the network has a slow minute. Measure: φ over time next to the heartbeat gaps. Cause: a history so steady that σ is tiny, so one slow gap gives a huge φ. Fix: a floor on σ; Akka's detector has a minimum standard deviation setting for this.

A phi accrual detector reports φ = 3 for node B. What does that say?

Chapter 3

Clocks Drift, NTP Pulls Them Back

Measure how fast two clocks part, then use four timestamps to estimate the gap

A computer's clock counts the ticks of a quartz crystal, and no two crystals tick at the same rate. That rate error is the drift, in parts per million (ppm): 20 ppm means 20 µs gained or lost each second. The gap between two clocks at one moment is the skew.

Call clock A's drift ρA, clock B's drift ρB, and the time since they last agreed t. The skew s grows like this.

Say it aloud

s equals rho-A minus rho-B, times t.

s
s the skew: how far apart the two clocks read now, in seconds.
ρA
rho-A clock A's drift, as a fraction: +20 ppm is +0.000020.
ρB
rho-B clock B's drift; a slow clock's drift is negative.
t
t the seconds since the clocks last agreed.
In plain words

Subtract B's drift from A's. Multiply by the time t since they last agreed. That is s, how far apart they read now.

With numbers

With made-up numbers: A gains 20 ppm and B loses 20 ppm, so ρA − ρB = 0.000040. After one day, t = 86,400 s, so s = 3.5 s.

The Network Time Protocol (NTP) pulls a clock back toward a server's time (RFC 5905). The client sends a request and notes its own clock, t1. The server notes when the request arrives, t2, and when its reply leaves, t3. The client notes when the reply lands, t4. Call the client's offset from the server θ (theta).

Say it aloud

Theta equals t-two minus t-one, plus t-three minus t-four, all over two.

θ
theta how far the server's clock is ahead of the client's. Positive means the client is behind.
t1
t-one the client's clock when the request leaves.
t2
t-two the server's clock when the request arrives.
t3
t-three the server's clock when the reply leaves.
t4
t-four the client's clock when the reply arrives.
In plain words

t-two minus t-one is the trip out plus theta. t-three minus t-four is theta minus the trip back. Average the two and, if the trips are equal, they cancel. Theta is left.

With numbers

With made-up stamps: t1 = 100.000 s, t2 = 100.005, t3 = 100.006, t4 = 100.010. Then θ = (0.005 − 0.004) / 2 = 0.5 ms. The client is 0.5 ms behind. The round trip is δ = (t4 − t1) − (t3 − t2) = 9 ms.

The trips cancel only if they are equal. A 7 ms trip out and a 2 ms trip back put θ off by (7 − 2) / 2 = 2.5 ms. NTP cannot see this error. It knows only the limit, δ / 2.

Fool NTP with an uneven path

Blue is the request, teal the reply. Each stamp is read on its own machine's clock. Make the two trips unequal and see the estimate drift from the truth.

5 ms
7 ms
2 ms

Illustrative: the server takes 1 ms between t2 and t3. The formulas are RFC 5905's offset and delay.

RFC 5905 says clients on fast LANs stay within a few hundred microseconds; over the internet, uneven routes cost milliseconds. A stratum 1 server reads a GPS receiver or an atomic clock, and each hop away adds one to the stratum.

Failure. Symptom: one host's log lines land seconds out of place. Measure: chronyc tracking shows its offset. Cause: its time daemon stopped. Fix: alert on the offset, say above 50 ms, and on a stopped daemon.

Two clocks drift at 20 ppm, one fast and one slow. Nobody syncs them for 24 hours. How far apart can they be?

Chapter 4

TrueTime: Wait Out the Uncertainty

Get the time as an interval, then hold each commit until its timestamp is surely past

Most clocks return one number and hide its error. Google's TrueTime, built for the Spanner database, returns an interval instead (Corbett and others, OSDI 2012). TT.now() gives [earliest, latest], and the true time lies inside. Each datacenter has time masters: most read GPS receivers, the rest have atomic clocks.

Half the width of the interval is the uncertainty ε (epsilon). Between syncs a machine's clock may drift, so ε grows. Call the uncertainty just after a sync ε0, the worst drift the system assumes ρ, and the time since the last sync τ (tau).

Say it aloud

Epsilon equals epsilon-zero plus rho times tau.

ε
epsilon the uncertainty: the true time is within ε of the clock's reading, either way.
ε0
epsilon-zero the error left right after a sync, mostly the delay to the time masters.
ρ
rho the worst drift the system assumes, in microseconds per second.
τ
tau the seconds since the last sync.
In plain words

Start from the error left after a sync, epsilon-zero. Add the worst drift rho for every second tau since. The interval widens like a sawtooth and snaps back at each sync.

With numbers

From the Spanner paper: a machine syncs every 30 s, with an assumed drift of 200 µs per second. That gives 0 to 6 ms, and the delay to the masters adds about 1 ms. So ε0 = 1 ms, and just before the next sync ε = 1 + 0.2 × 30 = 7 ms. The paper reports ε moving between about 1 and 7 ms.

Spanner uses the interval to order transactions across the world. When a transaction commits, its leader picks a timestamp s no earlier than TT.now().latest. Then it commit-waits: it holds the locks and hides the write until TT.now().earliest is past s. Now s is surely in the past, so any transaction that starts later, anywhere, gets a larger timestamp and sees the write.

Commit and wait

The yellow band is TT.now() around the true time. Purple marks the commit timestamp s. Pink is the commit wait. Drag the time since the last sync, then press Commit.

30 s

ε = 1 ms + 0.2 ms per second since the sync, the Spanner paper's numbers. The drawing holds ε fixed during the few milliseconds shown.

The wait is about 2ε, the whole width of the interval. The paper puts the expected wait at no less than twice the average ε of about 4 ms. In its benchmark, commit wait took about 5 ms. Better clocks mean shorter waits.

Failure. Symptom: write latency jumps by tens of milliseconds. Measure: the uncertainty the time daemon reports. Cause: the machine lost contact with its time masters, so ε keeps growing. Fix: several independent time sources, and an alert on ε, not only on offset.

TrueTime's uncertainty is ε = 4 ms. About how long does a commit wait?

Chapter 5

Lamport Clocks: Count Causes, Not Seconds

Define happened-before, then keep one counter that never lets an effect outrank its cause

Physical clocks drift, so Leslie Lamport's 1978 paper stops using them for order and tracks causes instead. He defines happened-before, written a → b, in three cases. Both events are on one process and a comes first. Or a sends a message and b receives it. Or a chain of such steps leads from a to b.

If neither a → b nor b → a, the events are concurrent: neither could have affected the other. Concurrent says nothing about wall-clock time; the two events may be seconds apart.

A Lamport clock is one counter per process. Before each local event or send, the process adds 1 and stamps the event. Each message carries the sender's stamp. Call the receiver's counter L and the stamp on the arriving message Lm.

Say it aloud

L becomes the max of L and L-m, plus one.

L ←
L becomes the receiver's new counter, which is also the stamp of the receive event.
L
L the receiver's counter just before the message arrives.
Lm
L-m the stamp the sender put on the message.
max
the max of the larger of the two numbers.
+ 1
plus one one more step, for the receive event itself.
In plain words

On a receive, take the larger of your own counter L and the message's stamp L-m. Add one. That is the stamp of the receive and your new L.

With numbers

In the trace below, P1's counter is 0 when message m1 arrives stamped 2, so L = max(0, 2) + 1 = 3. Later P0's counter is 3 when m3 arrives stamped 6, so L = max(3, 6) + 1 = 7.

Step a Lamport clock

Each row is a process; time runs to the right. Blue arrows are messages. Purple numbers are Lamport stamps. Press Step to run one event.

A fixed trace of nine events, worked by hand and checked with a short script.

The rule guarantees one direction: if a → b, then L(a) < L(b). The reverse fails. In the trace, P2's first event has stamp 1 and P1's receive has stamp 3, yet they are concurrent. Equal stamps happen too, so a system that needs one total order compares the pair (L, process ID).

Failure. Symptom: a "last write wins" store keeps the wrong one of two writes made at the same moment. Measure: pairs of writes to one key with no causal link. Cause: a Lamport stamp orders concurrent writes by accident. Fix: detect concurrency with version vectors (next chapter) and merge.

An event on P1 has Lamport stamp 5, and an event on P2 has stamp 8. The two processes never exchanged messages, directly or through others. What follows?

Chapter 6

Vector Clocks: Spot Concurrent Events

Keep one counter per process, merge entry by entry, and compare stamps to find concurrency

To detect concurrency, each process keeps a vector clock: one counter for every process. Entry j of my vector counts how many of process j's events I know about.

The rules extend Lamport's. Before a local event or send, process i adds 1 to its own entry. A message carries the whole vector. Call the receiver's vector V and the message's vector Vm. On a receive, for every process j:

Say it aloud

V of j becomes the max of V of j and V-m of j.

V[j] ←
V of j becomes the receiver's new count for process j.
V[j]
V of j how many of process j's events the receiver knew about before.
Vm[j]
V-m of j how many of process j's events the sender knew about.
max
the max of the larger count, done for each j from first to last.
In plain words

Go through the entries one by one and keep the larger of your count V of j and the message's count V-m of j. Then add 1 to your own entry, for the receive itself.

With numbers

In the trace, P1 holds [0, 0, 0] when m1 arrives carrying [2, 0, 0]. Entry by entry the max is [2, 0, 0]. Adding 1 to P1's own entry gives [2, 1, 0].

To compare two stamps, go entry by entry. If every entry of V(a) is at most the matching entry of V(b), and they differ, then a → b. If each vector is larger somewhere, the events are concurrent.

Compare two vector stamps

The trace of Chapter 5, now with vectors. Pick a pair; the two events light up, and the table below compares their entries.

The same fixed trace as Chapter 5; a short script checked every vector.

The price is size: n entries per stamp for n processes. A key-value store such as Amazon's Dynamo keeps a version vector per key instead, with one entry per replica that wrote it. When two versions of a key are concurrent, the store keeps both and lets the application merge them; Dynamo's example is a shopping cart.

Failure. Symptom: one key collects dozens of sibling versions. Measure: siblings per key. Cause: clients write without reading first, so each write is concurrent with the last. Fix: read before you write, or use dotted version vectors, which Riak adopted in version 2.0.

Event A has vector [3, 2, 0] and event B has [2, 3, 0]. How are they related?

Chapter 7

Hybrid Logical Clocks

Follow physical time when it moves forward, and count when it does not

Lamport stamps say nothing about when an event happened, and vectors grow with the cluster. The hybrid logical clock (HLC) keeps two numbers (Kulkarni and others, 2014). The first, l, stays close to physical time. The second, c, is a counter that breaks ties when l does not move.

Call the node's physical clock reading pt, its stamp (l, c), and an arriving message's stamp (lm, cm). On a receive, the new l is:

Say it aloud

l becomes the max of l, l-m and p-t.

l ←
l becomes the time part of the receive's new stamp.
l
l the node's time part before the message arrives.
lm
l-m the time part of the sender's stamp.
pt
p-t this node's physical clock now, in milliseconds.
max
the max of the largest of the three.
In plain words

Take the largest of the three times. If the new l equals an old l, add 1 to the largest matching counter c; if pt won, set c to 0. A local event or send uses the same rule without l-m.

With numbers

With made-up numbers: A sends at pt 101 with stamp (101, 0). B's clock is 5 ms behind and reads 98 when the message lands. l = max(0, 101, 98) = 101. That ties the message, so c = 0 + 1 and B stamps (101, 1). At B's next event its clock reads 99, so l stays 101 and c becomes 2. When B's clock reads 103, l jumps to 103 and c resets to 0.

Skew B's clock under a hybrid clock

Each event shows its physical clock pt in grey and its stamp (l, c) in purple. Drag B's skew and watch the counter c climb while B's clock lags.

−5 ms

Illustrative: events at 0, 1, 3, 4, 8, 9 and 11 ms after clock 100, and messages of 2 ms. The rules come from the 2014 paper.

HLC keeps Lamport's promise: if a → b, then HLC(a) < HLC(b), comparing l first and then c. Its l never runs ahead of the fastest clock in the cluster, so l − pt stays within the clock skew. It is always two numbers, whatever the cluster size. Like a Lamport clock, it cannot detect concurrency. CockroachDB stamps its writes with an HLC.

Failure. Symptom: HLC stamps on every node run far ahead of the wall clock. Measure: l − pt on each node. Cause: one peer's clock is fast, and every message from it pulls l forward. Fix: refuse peers whose clocks pass a set maximum offset, as CockroachDB does.

What does a hybrid logical clock give that a vector clock does not?

Chapter 8

Four Clocks, One Log

Run random traffic over three nodes and grade each clock on every pair of events

Now put all four clocks on the same events. The device makes three nodes do a random mix of local events and messages. Each node's physical clock is off by up to the skew you set. For every pair of events, it checks the clock's verdict against the true causal order.

Each pair lands in one of three groups. A causal pair has an order, and the clock either keeps it or reverses it. A concurrent pair has no order: a clock either says so, or quietly invents one.

Grade four clocks

Rows are nodes, time runs right. A red arrow is a message the clock stamps as received before its send. The strip below is the merged log in the clock's order. Pick a clock, drag the skew, and press New scenario.

30 ms

Illustrative: about 14 events in 100 ms, messages of 4 to 20 ms, physical clocks read to the millisecond. The true order comes from the messages themselves.

In the starting scenario, with clocks off by up to 30 ms, the wall clock reverses or ties 6 of 98 causal pairs. Four messages look received before they left. Lamport, vector and hybrid clocks keep all 98, at any skew.

The difference is in the 38 concurrent pairs. Lamport and hybrid clocks give each one an order, and only the vector clock says they have none. The hybrid stamps also stay within 8 ms of each node's clock. Things to try:

  1. Set the skew to 0 on the wall clock: the reversals go, but the concurrent pairs still get an order.
  2. Raise the skew to 50 ms and press New scenario a few times. Count the red arrows.
  3. Switch between Lamport and Hybrid: the same verdicts, but only hybrid stamps tell you when.

Failure. Symptom: a trace view shows a server's reply span ending before the client's request span began. Measure: the clock offset of each host in the trace. Cause: spans placed by wall-clock time on hosts with skew. Fix: order spans by their parent links, which are causal, and record each host's offset.

You build a replicated store and must detect two writes to one key that did not see each other. Which clock do you need?

Chapter 9

Clocks in Your Code

Time durations with the monotonic clock, and know what the wall clock does at a leap second

Your operating system gives you two clocks. The wall clock (time.time() in Python) says what time it is, and NTP may step it forward or back. The monotonic clock (time.monotonic()) counts from an arbitrary start, usually boot, and never goes back. Use the monotonic clock for every duration and every timeout.

Time a 300 ms call with the wall clock while NTP steps the clock back 1 s, and the call took −700 ms. Try it.

Time a call while the clock moves

Top: what each clock reads during the call. Bottom: the duration each one reports. Pick what NTP does halfway through, then press Run.

Illustrative: the step lands 150 ms into the call. The smear slows the wall clock by 1 s per 24 hours.

This bites real systems. At the leap second of 31 December 2016, Cloudflare's DNS software subtracted two wall-clock readings and got a negative duration. It passed that to a random-number function, which panicked. Go 1.9, released in 2017, made time.Now() carry a monotonic reading, so subtracting two times uses it.

A leap second keeps UTC within a second of the Earth's rotation: 23:59:60 follows 23:59:59. Google instead smears it, slowing its clocks over 24 hours, noon to noon. One second over 86,400 s is a rate change of 11.6 ppm, and the clock is never more than 0.5 s off. In 2022 the General Conference on Weights and Measures decided to let the gap between UTC and the Earth's rotation grow past one second by 2035. Until then, atomic time without leap seconds (TAI) is 37 s ahead of UTC.

Failure. Symptom: a negative latency in metrics, or a timeout that fires at once. Measure: search duration code for time.time() or System.currentTimeMillis(). Cause: the wall clock used for elapsed time. Fix: time.monotonic() in Python, System.nanoTime() in Java, Instant in Rust.

You measure how long an RPC takes, to set its timeout. Which clock do you read?

Chapter 10

The Field Guide

Keep the numbers, the checklist and the code for the next time a node goes quiet

A distributed system has no shared clock and no sure way to tell a slow node from a dead one. Heartbeats and timeouts give suspicion, and phi accrual makes it adapt. NTP keeps clocks close but cannot see its own error; TrueTime bounds the error and waits it out. For order, count causes. Lamport clocks keep causes ahead of effects, and vector clocks also spot concurrency. Hybrid clocks do Lamport's job in two numbers close to real time.

Terms and numbers

TermWhat it isThis lesson's number
Detection delayT − Δ < D ≤ TΔ 250 ms, T 1,000 ms: 750 to 1,000 ms
Phiφ = −log10(1 − F(t))μ 1,000, σ 200: φ = 2.2 at 1,500 ms; 8 at 2,122 ms
Skews = (ρA − ρB) · t±20 ppm for a day: 3.5 s
NTP offsetθ = ((t2 − t1) + (t3 − t4)) / 20.5 ms; error up to δ / 2
TrueTimeε = ε0 + ρ · τ; wait about 2ε1 to 7 ms; commit wait about 5 ms measured
LamportL ← max(L, Lm) + 1max(0, 2) + 1 = 3
VectorV[j] ← max(V[j], Vm[j])[0,0,0] meets [2,0,0]: [2,1,0]
HLCl ← max(l, lm, pt), counter c(101, 0) received at pt 98: (101, 1)
Leap smear1 s spread over 24 h11.6 ppm; TAI − UTC = 37 s

Which clock for which job

JobUseWhy
Time a call, set a timeoutMonotonic clockNever steps back
Show a time to a personWall clock, in UTCMeans something outside the machine
Order events by causeLamport or hybrid clockAn effect never outranks its cause
Find conflicting writesVersion vectorsOnly vectors can say "concurrent"
Order transactions by real time, worldwideBounded clocks plus commit waitWaiting out ε makes s surely past

Checklist

  1. Treat every timeout as a suspicion; act on it in steps (stop routing first, reassign work later).
  2. Keep T − Δ above your longest pause, or use phi accrual with a floor on σ.
  3. Run a time daemon on every host and alert on its offset.
  4. Never order cross-machine events by wall-clock time alone.
  5. Use the monotonic clock for durations, timeouts and rate limits.
  6. Store and log time in UTC; carry a trace ID or a logical stamp for order.

The core as code

python# a phi accrual detector and a hybrid logical clock, the two tools of this lesson
import math, statistics, time

class PhiDetector:
    def __init__(self, window=200, min_sigma=0.1):
        self.gaps, self.window, self.min_sigma, self.last = [], window, min_sigma, None
    def heartbeat(self):
        now = time.monotonic()                       # durations: monotonic clock
        if self.last is not None:
            self.gaps.append(now - self.last); self.gaps = self.gaps[-self.window:]
        self.last = now
    def phi(self):
        if len(self.gaps) < 2: return 0.0
        mu = statistics.mean(self.gaps)
        sigma = max(statistics.stdev(self.gaps), self.min_sigma)  # floor on sigma
        z = (time.monotonic() - self.last - mu) / sigma
        tail = 0.5 * math.erfc(z / math.sqrt(2))        # 1 - F(t), exact in the tail
        return -math.log10(max(tail, 1e-300))

class HLC:
    def __init__(self, clock=lambda: time.time_ns() // 1_000_000):
        self.l, self.c, self.pt = 0, 0, clock     # pt: the wall clock, in ms
    def tick(self):                                  # a local event or a send
        l = max(self.l, self.pt())
        self.c = self.c + 1 if l == self.l else 0
        self.l = l; return (self.l, self.c)
    def recv(self, lm, cm):                          # a message stamped (lm, cm)
        l = max(self.l, lm, self.pt())
        if l == self.l == lm: self.c = max(self.c, cm) + 1
        elif l == self.l:      self.c += 1
        elif l == lm:          self.c = cm + 1
        else:                  self.c = 0
        self.l = l; return (self.l, self.c)

Keep going

The takeaway. Silence is not death, and a timestamp is not an order. Suspect with timeouts that fit your pauses, keep clocks synced but never trust them for causality, and order events with logical or hybrid clocks. When you need real-time order, bound the clock error and wait it out.

Now press Present or Teach and explain five things from memory. Explain the detection window, what φ = 3 means, why NTP's error hides in uneven paths, why Spanner waits 2ε, and how a vector clock finds concurrency. Then go back to the hero, set B's skew to +30 ms and compare the three clocks.

Failure and Time
Lamport 1978 · RFC 5905 · Spanner · Back to Gleams