Time, clocks and ordering
Server clocks drift, jump and disagree. Learn which clock to use for what, why timestamps can lose data, and how logical clocks put events in order.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
At midnight UTC on 1 January 2017, a leap second was added to the world's clocks. At that moment, some DNS lookups through Cloudflare began to fail. 1
Their DNS software, RRDNS, is written in Go. For CNAME records, it asked upstream DNS servers. It measured how long they took to answer, with code like time.Now().Sub(start). Around the leap second, time.Now() could return a time earlier than start. So the measured time was negative. 1
The negative numbers flowed into the code that picks which server to ask next. That code called rand.Int63n, which panics if its argument is negative. Lookups for customers who use CNAME records failed. At the peak, about 0.2% of DNS queries to Cloudflare were affected. 1
The post names the root cause as one belief: time cannot go backwards. The code assumed the difference between two times would be, at worst, zero. At that time, the post notes, Go did not offer a monotonic time source. 1
The fix was live worldwide by 06:45 UTC. 1
The idea in simple words
Every server has its own clock, and no two agree exactly. NTP keeps them close, but not equal. Over the public internet, NTP can usually keep clocks within tens of milliseconds. Uneven routes and busy networks can sometimes cause errors of 100 ms or more. 8
So you often cannot tell which of two events came first by comparing their clock times. Leslie Lamport made this point in 1978. In a distributed system, he wrote, it is sometimes impossible to say which of two events occurred first. 5
The key idea. Use a clock to measure how long something takes, on one machine, with the monotonic clock. To decide what came first across machines, use counters, messages or one server that assigns the order. Do not trust wall-clock timestamps for that.
How it works
Two clocks on every machine
Your operating system gives you two clocks. Linux calls the first one CLOCK_REALTIME. It is the wall clock, which shows the real date and time. It can jump if someone sets it, and NTP also adjusts its speed. 2
The second is CLOCK_MONOTONIC. Nobody can set it. It counts from some point in the past, and that point has no meaning of its own. 2
Go's documentation puts the rule simply: "the wall clock is for telling time and the monotonic clock is for measuring time." In its example, an operation measured with time.Now() and Sub gives a positive time of about 20 ms. This holds even if the wall clock changes during the operation. 3
Skew, NTP and leap seconds
Clock skew is the gap between two clocks. NTP shrinks it, but cannot remove it. Wall-clock time also has kinks. Leap seconds and jumps in system time can make timestamps go backwards. 8
A leap second is one extra second added to UTC. A clock that steps back for it can break code like Cloudflare's. Google spreads the extra second over the hours around the leap instead. This is called a leap smear. 4
Google recommends a 24-hour linear smear, from noon to noon UTC. During the smear, each second is about 11.6 μs longer than normal. 4 Our advice: use the same time source for every server in a fleet. Our own arithmetic shows why: halfway through a 24-hour smear, a smeared clock is about half a second away from one that is not smeared.
Why "last write wins" can lose data
Many stores settle conflicts with last write wins. Cassandra does this, with a separate timestamp on every column. The timestamp comes from the client's clock, or from the clock of the node that coordinates the write. 7 Cassandra says its correctness depends on these clocks, and tells you to run NTP. 7 Dynamo also describes last write wins: the version with the largest physical timestamp is kept. 6
Now add skew. If one server's clock is a little behind, a newer write can get an older timestamp. It then loses to the write it should replace. Nothing fails, and no error is logged. The data is just gone.
Step through it.
- Two servers both accept writes. NTP keeps their clocks close, but not equal. Right now, Server B's clock is 3 seconds behind Server A's.
- A shop owner sets a price of ₹500 through Server A. Server A stamps the write with its own clock: 10:00:05.
- One second later, the owner fixes the price to ₹450. This request lands on Server B. Its slow clock stamps the newer write 10:00:03.
- The servers sync and use last write wins. The older write has the bigger timestamp, so both keep ₹500. The newer price is lost, and no error is raised.
- Now replay it with Lamport counters. Server A's write gets counter 7. Server B reads the price before it changes it, so it sees 7.
- Server B's own counter was lower, so it jumps past 7 and stamps its write 8. The counter follows what B saw, not B's clock. Both servers keep ₹450. This works only because B saw A's write first.
Ordering without clocks: Lamport clocks
Lamport defined order by what could affect what, not by time. Event a happens-before event b if one of three rules holds. Both are in one process and a comes first. Or a sends a message and b receives it. Or a happens-before c, and c happens-before b. 5 If neither event happens-before the other, they are concurrent. 5
A Lamport clock gives each event a number with two rules. Each process adds one to its counter between any two of its events. Each message carries the sender's counter. The receiver then moves its own counter past that value. 5
These rules give the Clock Condition: if a happens-before b, then a's number is smaller than b's. 5 To get one total order, sort by the number, and break ties by a fixed order of the processes, such as their IDs. 5
Know the limit. The reverse is not true. A smaller number does not prove that a happened first, because the two events may be concurrent. 5 In the diagram, the counter fixed the order only because Server B read the price before it changed it.
Vector clocks, in one paragraph
A vector clock is a list of (node, counter) pairs, one list per version of the data. Dynamo uses them to see whether two versions have a causal order or sit on parallel branches. If they are on parallel branches, Dynamo keeps both and the client must merge them. 6 So vector clocks can find conflicts that a Lamport clock hides. The cost is size: the list can grow with the number of nodes. 8
Hybrid logical clocks
A hybrid logical clock (HLC) mixes the two ideas. Like a Lamport clock, it follows the happens-before order. It also keeps its value close to the NTP clock, so the timestamp still means roughly "when". 8
An HLC fits in the 64-bit NTP timestamp format. It only reads the physical clock and never sets it. It keeps working, and still tracks causality, even when NTP has small problems. 8
TrueTime and commit wait
Google's Spanner takes a different path: it makes clock error visible. Its TrueTime API does not return one time. TT.now() returns an interval, [earliest, latest]. The true time is always inside it. 9
TrueTime uses GPS and atomic clocks as time sources. 9 This keeps the uncertainty small, generally under 10 ms. 9 In Google's production, the error bound moved between about 1 and 7 ms in each poll interval. Its average was 4 ms most of the time. 9
For each write, Spanner picks a commit timestamp no smaller than TT.now().latest. Then comes commit wait. Clients cannot see the new data until TT.after(s) is true, that is, until the timestamp has surely passed. 9
This gives external consistency. If transaction T1 commits before T2 starts, T1 gets the smaller timestamp. 9 The price is waiting: in the paper's tests, commit wait was about 5 ms. 9 The HLC paper notes that TrueTime needs special hardware, which is not possible for many systems, such as those on leased cloud machines. 8
Trade-offs
| Option | Orders events across servers? | Cost | Use it when |
|---|---|---|---|
| Wall-clock timestamps | No Skew can make a newer write lose. | Free and simple. | Showing dates to people. Rough order is fine. |
| Monotonic clock | No It means nothing outside one machine. | Free. | Timeouts, retries, durations and rate limits. |
| One server assigns sequence numbers | Yes , for everything that goes through it. | Every write goes through one place. | Most apps. Let the database or leader give the order. |
| Lamport clock | Yes , it respects happens-before. It cannot spot concurrent events. 5 | One counter on every message. | You need one total order that respects cause and effect. |
| Vector clock | Yes , and it can find conflicting versions. 6 | Size grows with the number of nodes. 8 | Many nodes take writes, and the app can merge conflicts. |
| Hybrid logical clock | Yes , and stays close to real time. 8 | A little more logic than a plain counter. | Databases that need timestamps that are both causal and near real time. |
| TrueTime | Yes , with external consistency. 9 | Special hardware, and a short wait on every commit. 9 8 | You run on a platform that offers it. |
At work: how a senior uses this
- Search the code for durations computed from wall-clock time. In Go, keep the value from
time.Now()and useSub, so the monotonic reading is used. 3 In other languages, find the monotonic clock in the official docs. - Never trust client clocks for order. A phone's clock is set by its user. Store the client time as information only.
- Let one place assign order when you can: a database sequence or a leader. See unique ID generation.
- In a design review, ask: "If two of our servers' clocks are one second apart, what breaks?" If the answer is "the newest write might be lost", you have last write wins on wall-clock time.
- Do not build locks or leases on clocks from different machines. See leader election and leases.
- Watch clock offset on every host, and alert when NTP stops syncing.
With AI
What to ask the agent
"Find every place in this repo that subtracts two wall-clock readings to get a duration or timeout. Show the file and line, and suggest the monotonic clock call for this language. Link the official docs for it."
"This table uses last write wins with an updated_at set by each app server. List the cases where a newer update could be lost, and suggest a fix with a version number or a database sequence."
What to check yourself
- Every suggested clock call is the monotonic one, checked in the language's official documentation.
- The agent did not "fix" ordering by adding more NTP servers. Smaller skew still allows lost writes.
- Any version check is done in the database, in one atomic step, not read first and compared later in app code.
- Code that runs during a leap second, or a clock jump, still works. Ask for a test that moves the wall clock backwards.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 9 sources and related lessons
- Cloudflare, “How and why the leap second affected Cloudflare DNS” (January 2017) (opens in a new tab)
The postmortem. A negative time difference reached rand.Int63n, which panicked, and some DNS lookups failed. - Linux man-pages: clock_gettime(2) (opens in a new tab)
CLOCK_REALTIME (settable wall clock) and CLOCK_MONOTONIC (cannot be set). - Go standard library documentation: package time, “Monotonic Clocks” (opens in a new tab)
The wall clock is for telling time, the monotonic clock for measuring time, with a short code example. - Google Public NTP: Leap Smear (opens in a new tab)
How Google spreads a leap second over 24 hours, and the smear it recommends to others. - Leslie Lamport, “Time, Clocks, and the Ordering of Events in a Distributed System”, Communications of the ACM 21(7), July 1978 (opens in a new tab)
The “happened before” relation, the Clock Condition, the two rules for logical clocks, and how to break ties for a total order. - Werner Vogels, “Amazon's Dynamo” (2007), with the SOSP paper (opens in a new tab)
Shows vector clocks catching conflicting versions, and when the client must merge them. It also mentions last write wins. - Apache Cassandra documentation: Dynamo (architecture) (opens in a new tab)
Cassandra resolves conflicts by last write wins, with a timestamp per column, and says its correctness depends on clocks. - Sandeep Kulkarni, Murat Demirbas, Deepak Madeppa, Bharadwaj Avva and Marcelo Leone, “Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases” (2014) (opens in a new tab)
The hybrid logical clock (HLC) paper. Section 1 also compares Lamport clocks, vector clocks, NTP time and TrueTime. - James C. Corbett et al. (Google), “Spanner: Google's Globally-Distributed Database”, OSDI 2012 (opens in a new tab)
Section 3 explains the TrueTime API, and section 4.1.2 the commit wait rule.
Real incident: Cloudflare, 1 Jan 2017: Cloudflare DNS outage: a leap second made a time difference negative
Case studies: Google: Spanner: a global database built on known clock error
Related: Why distributed systems are hard · Unique ID generation · Quorums and leaderless replication · CRDTs and coordination avoidance (coming soon) · Leader election and leases · Distributed transactions and two-phase commit