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.
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
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.
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.
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.
Chapter 1
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.
T minus delta is less than D, and D is at most T.
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 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.
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.
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.
Chapter 2
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).
Phi equals minus log base ten of one minus F of t.
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 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.
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.
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.
Chapter 3
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.
s equals rho-A minus rho-B, times t.
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 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).
Theta equals t-two minus t-one, plus t-three minus t-four, all over two.
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 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.
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.
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.
Chapter 4
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).
Epsilon equals epsilon-zero plus rho times tau.
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.
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.
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.
ε = 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.
Chapter 5
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.
L becomes the max of L and L-m, plus one.
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.
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.
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.
Chapter 6
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:
V of j becomes the max of V of j and V-m of j.
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.
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.
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.
Chapter 7
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:
l becomes the max of l, l-m and p-t.
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 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.
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.
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.
Chapter 8
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.
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.
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:
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.
Chapter 9
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.
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.
Chapter 10
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.
| Term | What it is | This lesson's number |
|---|---|---|
| Detection delay | T − Δ < 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 |
| Skew | s = (ρA − ρB) · t | ±20 ppm for a day: 3.5 s |
| NTP offset | θ = ((t2 − t1) + (t3 − t4)) / 2 | 0.5 ms; error up to δ / 2 |
| TrueTime | ε = ε0 + ρ · τ; wait about 2ε | 1 to 7 ms; commit wait about 5 ms measured |
| Lamport | L ← max(L, Lm) + 1 | max(0, 2) + 1 = 3 |
| Vector | V[j] ← max(V[j], Vm[j]) | [0,0,0] meets [2,0,0]: [2,1,0] |
| HLC | l ← max(l, lm, pt), counter c | (101, 0) received at pt 98: (101, 1) |
| Leap smear | 1 s spread over 24 h | 11.6 ppm; TAI − UTC = 37 s |
| Job | Use | Why |
|---|---|---|
| Time a call, set a timeout | Monotonic clock | Never steps back |
| Show a time to a person | Wall clock, in UTC | Means something outside the machine |
| Order events by cause | Lamport or hybrid clock | An effect never outranks its cause |
| Find conflicting writes | Version vectors | Only vectors can say "concurrent" |
| Order transactions by real time, worldwide | Bounded clocks plus commit wait | Waiting out ε makes s surely past |
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)
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.