Algorithms · Huge scale
TrueTime and clock uncertainty
How Google keeps time honest across the planet. No clock is exact. Google’s trick: know how wrong it might be, and wait that long.
The problem
Google's Spanner is a database spread across datacenters around the world. You buy something in one city, and a moment later someone else reads your balance from a server on another continent. The database must show them your purchase, because it really happened first.
To order transactions you stamp each with a time. But every server has its own clock, and no two clocks agree exactly. If server A's clock runs a little fast and B's a little slow, a later transaction can get an earlier stamp, and history gets scrambled.
The obvious way
Just read the local clock and use it as the timestamp. It's simple and fast. It breaks because clocks drift: if T1 finishes on a fast server and T2 starts a few milliseconds later on a slow one, T2's stamp can come out smaller than T1's. The database now believes T2 happened first.
The clever idea
Spanner stops pretending a clock knows the exact time. Its TrueTime API, built on GPS receivers and atomic clocks in datacenters, answers TT.now() with an interval [earliest, latest] that is guaranteed to contain the real time. The width of that interval is the uncertainty, called epsilon, typically a few milliseconds.
Then comes commit wait. Picture a race judge who won't announce a winner until the stopwatch error can't change the result. After choosing a commit timestamp, Spanner waits until TT.after(timestamp) is true, meaning that time has surely passed everywhere, and only then makes the commit visible. Any later transaction gets a bigger stamp.
How the code does it
Each server gets a hidden error in its offset, and local_clock returns the real time plus that error. The obvious way, these four lines, stamps both transactions with those skewed readings and counts every time T2's stamp comes out smaller. With errors up to ±7 ms and gaps of only 1–10 ms, that happens a lot.
The TrueTime way, this block, stamps T1 with latest (clock + epsilon), then commit_wait ticks forward until earliest (clock − epsilon) passes the stamp. T2 starts after that, so its own latest can't be lower. The first bar is the local-clock mistakes and the second is TrueTime's, which stays at zero. In this toy the wait comes out at about twice epsilon, around 14 ms.
Trade-offs
Correctness isn't free: every commit waits, and the wait grows with epsilon, so tighter clocks (GPS, atomic) directly mean faster writes. It also needs special hardware in datacenters. If you run a single server, or can live with slightly stale or loosely ordered data, plain local timestamps are far cheaper and perfectly fine.
Where else you'll see it
Any system that must order events across machines faces this: logs, distributed databases and message queues. Many avoid physical clocks entirely and use logical counters instead. Spanner's twist is to admit the uncertainty, measure it, and wait it out.
In the code, you change EPS from 7 to 14. What happens to the average commit wait and the wrong orders with TrueTime?
- Wait stays the same, wrong orders rise
- Wait roughly doubles, wrong orders stay 0
- Wait drops to zero, wrong orders stay 0
Show the answer
Wait roughly doubles, wrong orders stay 0. The wait is about twice epsilon, so it roughly doubles. Waiting out the full uncertainty is exactly what keeps the order correct.
- Change EPS to 2 and rerun
- Shrink the wait step 0.1 to 0.01
- Change range(3) to range(10) servers
The code
Python, with what each line means beside it. It compares the clever way with trusting each server’s own clock.
import randomBring in the random number toolsrandom.seed(7)Fix the seed so results repeat EPS = 7 # clock uncertainty, in msClocks may be off by up to 7 msoffsets = [random.uniform(-EPS, EPS) for _ in range(3)]Give each of 3 servers a random clock error def local_clock(server, real):A server reads real time plus its error return real + offsets[server]Return that skewed reading def commit_wait(server, ts, real):Define waiting out the uncertainty while local_clock(server, real) - EPS <= ts:Loop until earliest possible time passes the stamp real += 0.1Let a tenth of a millisecond tick by return realReport when the wait ended naive_wrong, tt_wrong, waits = 0, 0, []Start counters for mistakes and waitsfor _ in range(200):Repeat for 200 pairs of transactions a, b = random.sample(range(3), 2)Pick two different servers start = random.uniform(0, 1000)Pick a random moment for the first commit gap = random.uniform(1, 10)Pick a 1–10 ms gap before the second t1 = local_clock(a, start)Server A stamps T1 with its own clock t2 = local_clock(b, start + gap)Server B stamps T2 with its own clock if t2 < t1:If T2 got an earlier stamp naive_wrong += 1Count it as a wrong order ts1 = local_clock(a, start) + EPSStamp T1 with the latest possible time done = commit_wait(a, ts1, start)Wait until that stamp is surely past ts2 = local_clock(b, done + gap) + EPSStamp T2 the same way, after the gap waits.append(done - start)Record how long T1 waited if ts2 <= ts1:If T2's stamp isn't later than T1's tt_wrong += 1Count it as a wrong order show([naive_wrong, tt_wrong], "wrong orders of 200: local clocks vs TrueTime")Draw both mistake counts as barsprint("average commit wait:", round(sum(waits) / len(waits), 1), "ms")Print the average wait in milliseconds- drift line 5Each server's clock is wrong by its own fixed amount, never more than 7 ms either way. That's our stand-in for drift.
- TT.after lines 11–12Earliest possible real time is clock minus epsilon. Once that exceeds the stamp, the stamp is surely in the past.
- the trap lines 21–24T2 truly happens after T1, yet a slow clock on B can still stamp it earlier.
- commit wait lines 26–27Stamp with the latest possible time, then wait it out. Only afterwards can T1 be seen by anyone.
Read more
- research.google: TrueTime and clock uncertainty
- Ask Bento: What is a logical clock?
- Ask Bento: How does Spanner use GPS clocks?
- Ask Bento: Why not just sync clocks perfectly?
Run it. Then change it.
The code runs right in the page and draws as it goes. Free, nothing to install.