Chapter 03 / 10 · Distributed Systems

Time and order

A freeze and an unfreeze land on two machines whose clocks disagree. Order has to come from messages, and sometimes there is none to find.

This chapter lets you decide what order two events happened in when they were recorded on different machines, and recognise when that question has no answer. Those two skills keep an audit trail truthful and stop a replicated store from quietly keeping the wrong write.

The wallet now runs on several application servers. Compliance asks for a single audit trail per account, so each server writes an entry for every balance change, stamped with its own clock, and a nightly job merges the entries by timestamp. One morning an auditor opens Asha’s trail and finds a payment of ₹1,800 at 10:15:02.140, followed by the ₹2,000 top-up that funded it at 10:15:02.190. Asha appears to have spent money she did not have. The ledger is correct. The trail is wrong, and it is wrong because we trusted timestamps from two machines to mean the same thing.

What a timestamp from another machine is worth

Every server keeps time with a quartz oscillator, and quartz drifts. A typical error is in the tens of parts per million. At 20 parts per million a clock gains or loses about 1.7 seconds a day (86,400 seconds × 0.00002). The Network Time Protocol corrects this by comparing against reference servers and adjusting. Inside a well-run data centre, NTP commonly keeps machines within a few milliseconds of each other. It does worse when its servers are unreachable, when a virtual machine is paused and resumed, or when the network path is congested and its round-trip estimates are skewed.

NTP also has two ways of correcting a clock. Usually it slews: it runs the clock slightly fast or slow until the error is gone. When the error is large it may step: it sets the clock to a new value at once, and that value can be in the past. Leap seconds have caused similar jumps, which is why large operators now smear them across a day instead.

Now compare those numbers with how long a message takes. A round trip inside one data centre is around half a millisecond. A clock difference of a few milliseconds is therefore several times larger than the time a message takes to travel. Server A can send a request stamped 10:15:02.140, and server B can receive it and stamp the reply 10:15:02.137. The reply appears to come before the question. In Asha’s trail, the server that processed the top-up was running about 60 ms ahead of the server that processed the payment, more than enough to reverse two events that happened 10 ms apart.

Where it stops being cosmetic

A misordered audit trail is embarrassing. A misordered write is worse. Suppose the wallet keeps account settings, including a status field that can be active or frozen, in a store that accepts writes in both data centres and resolves conflicts by keeping the write with the later timestamp. This policy is called last write wins, and several databases offer it as the default.

Asha calls support from DC-2’s region, verifies her identity, and an agent unfreezes her account. Forty milliseconds later, by true time, the fraud system in DC-1 sees a login from an unfamiliar device and freezes it again. DC-1’s clock is 100 ms behind DC-2’s.

Predict first

The unfreeze is stamped 10:00:00.000 in DC-2. The freeze happens 40 ms later in real time and is stamped by DC-1’s clock, which runs 100 ms slow. Which status do both data centres end up with, and does anything report an error?

Show the worked answer

The freeze is stamped 10:00:00.040 − 0.100 = 09:59:59.940. Last write wins compares 09:59:59.940 with 10:00:00.000 and keeps the unfreeze. Both data centres converge on active.

Nothing reports an error. The store did what it promised: it converged, and every replica agrees. It agrees on the wrong answer, and the fraud team’s freeze has vanished without a trace. The account is open while the suspicious device is logged in.

The lesson is that convergence and correctness are different properties. Last write wins guarantees the first. It decides correctness by whichever clock happened to run fast.

Two clocks in every machine

Before the theory, one rule you can apply today. Operating systems expose two clocks. The wall clock answers “what time is it?” and is the one NTP adjusts, including backwards. The monotonic clock answers “how much time has passed?” and only moves forward, though its value means nothing outside the machine that produced it. Every duration, timeout and latency measurement belongs on the monotonic clock.

// wrong: elapsed can be negative, or jump by seconds, if NTP steps the clock
const start = Date.now()
await wallet.transfer(req)
const elapsed = Date.now() - start

// right: monotonic, meaningful only for durations on this machine
const t0 = performance.now()
await wallet.transfer(req)
const tookMs = performance.now() - t0

The same applies to lease expiry, which the coordination chapter depends on. A server that computes “my lease ends at 10:00:10” on the wall clock will hold its lease too long if its clock is stepped backwards. Leases are measured as durations on the monotonic clock, with a safety margin for clocks that run at slightly different rates.

Order from cause, not from time

If clocks cannot order events across machines, something else has to. Leslie Lamport’s 1978 paper made the move that the rest of the field builds on. Instead of asking when an event happened, ask which events could have influenced it.

He defined a relation called happens-before. Event a happens before event b if they are on the same machine and a came first; or if a is the sending of a message and b is its receipt; or if there is a chain of such steps from a to b. Two events with no chain between them in either direction are concurrent. Concurrent here does not mean simultaneous. It means neither could have known about the other.

Apply that to the audit trail. Asha topped up, the wallet replied, her phone showed the new balance, and she then sent the payment. There is a chain: top-up commit, reply, phone, payment request, payment commit. The top-up happened before the payment, whatever any clock says, because the payment request was sent by someone who had seen the top-up’s result. Now apply it to the freeze. The support agent did not know about the fraud alert, and the fraud system did not know about the call. No message links them. They are concurrent, and asking which came first has no answer worth building on.

That reframing is the main idea of this chapter. Some pairs of events have an order, and it comes from messages. Other pairs have none, and a design that pretends they do will pick one arbitrarily.

Lamport clocks: a counter that respects cause

A Lamport clock turns happens-before into numbers. Each server keeps an integer counter. It adds one before each event it records. It attaches the counter to every message it sends. When it receives a message, it sets its counter to one more than the larger of its own value and the value in the message.

server Aserver B12345send, stamped 51267receive: max(2, 5) + 1 = 6
Fig 3 · Server B is at 2 when a message stamped 5 arrives, so B jumps to 6. Anything B does afterwards is numbered after the send

For the audit trail, the wallet returns its counter with each response, the API passes it back on the client’s next request (as an opaque token the app stores), and the server that handles the payment starts from at least that value. The top-up is stamped 41, the reply carries 41, and the payment server, sitting at 17, jumps to 42. Sorting the trail by counter, with server id to break ties, now puts the top-up before the payment. If a happened before b, a’s counter is smaller.

The converse does not hold, and this limitation matters. A smaller counter does not mean the event came first in any causal sense. The freeze and the unfreeze get counters too, maybe 88 and 91, and sorting by them picks an order. It is a consistent order that every replica will agree on, but for concurrent events it is as arbitrary as the wall clock was. Lamport clocks cannot tell you that two events raced.

Vector clocks: noticing that two writes raced

To detect concurrency, each replica keeps one counter per writer instead of one in total. With two data centres accepting writes, a vector clock has two entries, written [DC-1, DC-2]. A data centre increments its own entry when it writes, and on receiving another’s update it takes the larger value in each position.

Say Asha’s status record is at [3, 5]: both sides have seen everything so far. The agent in DC-2 unfreezes her, producing [3, 6]. Before that replicates, the fraud system in DC-1 freezes her, producing [4, 5]. When the two versions meet, compare them position by position. One version is newer than another only if it is greater or equal in every position. Here [3, 6] is ahead in the second position and behind in the first, so neither supersedes the other. The store knows the writes were concurrent.

Knowing is all it can do. Something still has to choose, and that choice belongs to the domain, not to the clock. For account status, a sensible rule is that the more restrictive state wins and the conflict is sent to a human: freeze beats unfreeze, and support gets a ticket. A store that keeps both versions (often called siblings) and hands them to the application is doing the honest thing. A store that silently picks one is making a business decision on your behalf.

Vector clocks have costs. Each version carries a vector whose length grows with the number of writers. Amazon’s Dynamo used entries per coordinating node and truncated old entries when the vector grew too long, accepting occasional false conflicts. Every reader must be prepared to receive several versions and merge them, and merge code is easy to get wrong.

What production systems do instead

Most systems avoid needing either clock for their core data, by making sure that writes which could conflict pass through one place.

ApproachWhat it givesWhat the design must also handle
One leader per key rangeA single order for every write to that range, assigned by the leader’s log; no clocks involvedAll writes go to one node; replacing that node safely needs consensus
Lamport or vector clocksCausal order; vectors also detect concurrent writesMetadata on every version; application merge logic
Hybrid logical clocksTimestamps close to wall time that never go backwards and respect happens-beforeCorrectness still assumes clock skew stays under a configured bound
Bounded-uncertainty clocksTimestamp order that matches real time across regionsSpecial time hardware, and waiting out the uncertainty on each commit

A hybrid logical clock, used by CockroachDB and others, keeps a timestamp made of a physical part and a counter. On each event or message it takes the maximum of its own wall clock and any timestamp it has seen, and bumps the counter to break ties. The result stays close to real time, so humans can read it, and still respects causality like a Lamport clock. CockroachDB also refuses to run a node whose clock drifts beyond a configured maximum offset, because some of its guarantees depend on that bound. Google’s Spanner goes further with GPS and atomic clocks; we will look at what it buys in the chapter on systems that shipped.

For the wallet, the first row is the answer. Every balance change and every status change for an account goes through that account’s leader, which appends it to a log and gives it a sequence number. The audit trail is sorted by sequence number per account, so it is correct by construction. The freeze and the unfreeze can no longer be concurrent writes in two places: they queue at the same leader, and the second one sees the first. If we still want the more restrictive state to win, that becomes an ordinary rule in code (an unfreeze after a recent freeze needs review) rather than an accident of clocks.

Cross-account order is the remaining gap. Asha’s debit and Ravi’s credit may live on different leaders, and an auditor reading both logs may want to see that the money left before it arrived. That is a causal relationship, and the cheap way to preserve it is to carry it: Ravi’s credit entry records the id and sequence number of Asha’s debit that caused it.

A hybrid clock, worked through

Hybrid logical clocks are worth tracing once, because the mechanism is small and the failure it guards against is instructive. Each timestamp is a pair: a time part l and a counter c. For brevity we will write the time part as milliseconds past 10:00:00.

On a local event or a send, a server sets l to the larger of its current l and its physical clock. If l did not change, it adds one to c; if l moved forward, c goes back to zero. On receiving a message stamped (lm, cm), it sets l to the largest of its own l, lm and its physical clock, and sets c so that the new timestamp is strictly greater than both its previous one and the message’s.

Server A’s physical clock reads 100 when it sends a message, so the message carries (100, 0). Server B’s clock runs 60 ms behind. When the message arrives, B’s physical clock reads 45 and its last timestamp was (40, 0). B takes the largest of 40, 100 and 45, which is 100, and since that came from the message, sets the counter one past the message’s: (100, 1). The receive is ordered after the send, as causality requires. B’s next local events, while its physical clock is still below 100, are stamped (100, 2), (100, 3) and so on. About 55 ms later its physical clock passes 100, l follows the physical clock again, and the counter resets.

Three properties fall out. Timestamps never go backwards on any server, even if NTP steps the clock back, because l only ever takes a maximum. Timestamps respect happens-before, like a Lamport clock. And the time part never runs further ahead of a server’s physical clock than the largest skew in the cluster, so the timestamps remain readable as times.

That last property depends on the skew staying small. If one server’s clock is wrongly set a day ahead, every timestamp it sends drags its receivers’ l a day ahead, and they pass it on. Within minutes the whole cluster is stamping events with tomorrow’s date, and nothing in the algorithm brings it back until real time catches up. That is why systems built on hybrid clocks monitor clock offset between nodes and shut down a node whose offset exceeds the configured maximum, rather than letting it contaminate everyone else. Hybrid clocks tolerate skew; they do not tolerate an unbounded amount of it.

When the wall clock is fine

None of this means wall-clock timestamps are useless. They are the right tool for showing Asha when she sent money, for log lines a human reads during an incident, for metrics, and for expiry times with generous margins, such as deleting idempotency keys after a day. In all of these, an error of a few milliseconds, or even a second, changes nothing.

They are the wrong tool when the timestamp decides an outcome: which write survives, who holds a lease, which ledger entry comes first. The test is simple. If shifting one machine’s clock by 100 ms could change what the system does, the design is using time to stand in for order, and it will eventually get it wrong. Revisit the question whenever you add a second place where the same data can be written.

We have decided that each account’s writes go through one leader. The next chapter, Replication and consistency, keeps copies of that leader’s data on other machines so that the wallet survives losing one, and meets the first consequence: Asha sends money and then sees her old balance.