Spanner: Google's Globally-Distributed Database
2012 · OSDI · ~11 min read
Read the original paperA globally replicated SQL database whose timestamps match real time, achieved by measuring clock error and waiting it out. Read it to see clock accuracy turned directly into write latency.
Spanner is a database that replicates data across continents and still gives every transaction a timestamp consistent with real time, everywhere. The paper shows that the obstacle Lamport identified in 1978, that clocks on different machines cannot be compared, can be handled by measuring how wrong each clock might be and waiting out the uncertainty.
The pressure came from Google’s advertising backend. It ran on MySQL, manually sharded by customer, and the paper reports that the last re-sharding took more than two years of effort across many teams. The team wanted a database that would move data between machines and data centres by itself, survive the loss of a region, and keep SQL and real transactions. Bigtable scaled but had no transactions across rows. Megastore, built on Bigtable, had transactions and synchronous replication but relatively poor write throughput.
One requirement made a global design look impossible. The paper calls it external consistency: if transaction T1 commits before transaction T2 starts, in real time and anywhere in the world, then T2’s commit timestamp must be greater than T1’s. Our running example: in Tokyo, Alice removes Bob from the list of people who can see her photos (T1). After that commits, in Dublin, she posts a photo (T2). A reader taking a snapshot at any timestamp must never see the new photo with Bob still on the list.
Why ordinary timestamps produce impossible histories
Try it with ordinary clocks. Put true time on a common axis in milliseconds. The Tokyo server’s clock is 5 ms fast. At true time 100, T1 commits and is stamped 105. Alice’s client gets the reply and, two milliseconds later at true time 102, starts T2 in Dublin, where the clock is 3 ms slow. T2 reads 99 and is stamped 99.
A snapshot read at timestamp 100 now includes T2, the photo, and excludes T1, the removal. Bob, reading at that snapshot, sees a photo he was supposed to be blocked from. The history is impossible in real time, yet every server behaved correctly by its own clock. The skew was eight milliseconds, comfortably within what NTP leaves you with. Before Spanner, systems either sent every commit through one place that assigned timestamps, which does not work across oceans, or gave up this guarantee.
Lamport’s logical clocks do not help here, and the reason is the “anomalous behaviour” from his paper. T1 and T2 are linked by Alice, outside the database. No message inside the system connects them, so a logical clock is free to order them either way.
A clock that reports its own error
TrueTime is Spanner’s answer. Its central call, TT.now(), does not return a time. It returns an interval, earliest to latest, and guarantees that the true time is inside it. Two helpers follow: TT.after(t) is true when t has definitely passed, and TT.before(t) is true when t has definitely not arrived. The half-width of the interval is called ε.
Behind the API, each data centre has time master machines. Most have GPS receivers; the others, which the paper calls Armageddon masters, have atomic clocks, so that a fault affecting GPS does not affect every master. A daemon on every machine polls several masters, rejects outliers, and synchronises. Between polls, it assumes the local clock may drift at a worst-case rate and widens ε accordingly.
The paper gives numbers we can check against each other. Daemons poll every 30 seconds, and the assumed worst-case drift is 200 microseconds per second. Over 30 seconds that is 30 × 200 μs = 6 ms. Add about a millisecond of uncertainty from communicating with the masters, and ε rises from about 1 ms just after a poll to about 7 ms just before the next, a sawtooth that averages around 4 ms. The 200 μs per second figure is deliberately pessimistic, well beyond what a healthy crystal does, and the daemon evicts machines whose clocks drift more than that.
Commit wait, with numbers
With an honest interval, the rule for committing is short. When a transaction is ready to commit, the leader picks timestamp s no smaller than TT.now().latest. It then waits until TT.after(s) is true before releasing locks and replying. The paper calls this commit wait.
s = TT.now().latest # no earlier than any possible true time now
apply_and_replicate(s) # Paxos, in parallel with the wait
while not TT.after(s): # wait until s is definitely in the past
sleep briefly
release_locks(); reply(s)Rerun the photo example with ε = 4 ms everywhere. At true time 100, Tokyo reads the interval [96, 104] and picks s = 104. It must wait until earliest exceeds 104, which happens once true time passes 108. Alice gets her reply at about 108. She starts T2 in Dublin at true time 110; Dublin reads [106, 114] and stamps T2 at 114 or later. Since 114 is greater than 104, a snapshot that includes the photo also includes the removal.
The argument does not depend on the specific numbers. When T1 replies, its timestamp is definitely in the past. Anything that starts after that reply reads a later true time, and its interval’s latest edge is later still. The cost is the wait, about 2ε per write transaction, roughly 8 ms on average with the paper’s figures. Spanner hides part of it by overlapping the wait with Paxos replication, which takes several milliseconds anyway.
This is also why Google spent money on GPS receivers and atomic clocks instead of relying on NTP. The algorithm is correct with any honest ε; what ε controls is how long each write waits. With ordinary NTP over a wide network, a safe bound might be tens or hundreds of milliseconds, and every write would wait twice that. The hardware is a latency optimisation, which is an unusual way to think about clocks: Spanner turns clock accuracy directly into write latency.
Drag the uncertainty. T1 takes the latest possible time as its timestamp, then waits until that moment is surely past. T2, which starts after T1 has replied, can only get a larger timestamp.
TrueTime never claims to know the time; it returns a window that is guaranteed to contain it. By waiting out the window, a transaction makes its timestamp mean something on every machine on Earth, and the cost is a few milliseconds, paid once per commit.
A problem with nearby time masters makes ε grow from 4 ms to 8 ms for a while. What happens to the correctness of commits, and what happens to write latency?
Show the worked answer
Correctness is unchanged, because the intervals still contain true time; they are just wider. Latency rises: commit wait is about 2ε, so roughly 8 ms becomes 16 ms per write, and any part not hidden behind Paxos replication shows up in client latency. The system slows down instead of becoming wrong. What would break correctness is the opposite failure: a clock that drifts beyond the assumed bound, so the interval no longer contains true time.
Paxos groups, two-phase commit and locks, stacked
TrueTime only orders transactions. Durability and atomicity come from layers that were already well understood, stacked so that each layer’s weakness is covered by the one beneath. Data is split into tablets. Each tablet is replicated by its own Paxos group, typically across three or five zones, with a long-lived leader that holds a timed lease, ten seconds by default. A write is durable once a majority of the group has logged it.
A read-write transaction takes locks at the Paxos leaders, using two-phase locking with wound-wait to avoid deadlock. If it touched more than one group, the client picks one group’s leader as coordinator and runs two-phase commit. Each participant leader logs a prepare record through Paxos and chooses a prepare timestamp; the coordinator picks a commit timestamp at least as large as all of them and at least TT.now().latest, logs the commit through Paxos, performs commit wait, then tells participants.
Two-phase commit has a well-known weakness: if the coordinator crashes after participants have prepared, they hold their locks and cannot decide alone. In Spanner the coordinator is a Paxos group, not a machine. If its leader dies, another replica takes over with the full log, and the protocol continues. That is how Spanner can use a protocol many systems avoid. The cost is latency: a cross-group commit is several Paxos rounds, each needing a majority across zones, plus commit wait.
Data placement decides how often that cost is paid. Spanner groups rows that share a key prefix into a unit the paper calls a directory, and moves directories between Paxos groups in the background to balance load or bring data closer to its users. Applications declare hierarchies of tables, so that a user’s row and the rows of their photos and settings sit in the same directory. A transaction that touches only Alice’s own data then involves one Paxos group and skips two-phase commit entirely. Our example, with the access list in Tokyo and the album in Dublin, is the expensive case on purpose; a well-designed schema makes it rare.
The paper also relies on a subtle property of leader leases. Each Paxos leader’s lease intervals must not overlap with those of the next leader, and each leader assigns timestamps within its lease, increasing over time. Without that, a new leader could assign a timestamp smaller than one the old leader had already given out.
What the timestamps buy: reads without locks
The payoff is on the read side. Because commit timestamps match real-time order, a snapshot at any timestamp t is a consistent view of the whole database as it was at that moment. Any replica can serve a read at t, with no locks and no conversation with the leader, as long as it knows it has applied every write up to t. Each replica tracks this as a safe time, derived from the Paxos writes it has applied and from any transactions that are prepared but not yet committed.
A read-only transaction picks t = TT.now().latest and reads at it. Analytics over the whole database “as of ten seconds ago” can run on nearby replicas without slowing writers. Schema changes become transactions scheduled at a future timestamp: every server applies the change when its clock passes that timestamp, so there is no global pause. In the photo example, Bob’s client can read the access list and the album at the same snapshot, from replicas in whatever region is closest, and the result is always a state that really existed.
Change one variable: the replica nearest Bob is lagging. Bob’s read picks timestamp 120, but that replica has applied writes only up to 112, so its safe time is 112. It cannot answer at 120, because a write between 112 and 120 might still be on its way. It waits until Paxos brings it past 120, or the client chooses a slightly older timestamp, say 110, which the replica can serve at once. Spanner exposes that choice as bounded-staleness reads: the application states how old a snapshot it will accept and in exchange reads locally without waiting. The guarantee that the snapshot is consistent does not weaken; only its age does.
What it costs, and who copied it
The bill comes in three parts. Writes pay commit wait and cross-zone Paxos rounds, so Spanner is not where you put a workload that needs single-digit-millisecond writes across regions. The guarantees depend on a clock bound that requires dedicated hardware and operational discipline. And during a partition, Spanner favours consistency: a minority side cannot commit. Eric Brewer’s 2017 note argues that Spanner is technically a CP system, but that Google’s private network makes partitions rare enough that users experience it as effectively available as well.
| system | time source | what it guarantees across regions | what it pays |
|---|---|---|---|
| Spanner | TrueTime: GPS and atomic clocks, explicit ε | external consistency | commit wait of about 2ε on writes, special hardware |
| CockroachDB | hybrid logical clocks over NTP, configured maximum offset | serialisable transactions; real-time order within the offset bound | reads that hit the uncertainty window may restart |
| Dynamo-style stores | vector clocks, no physical order | eventual convergence, application merges | conflicts surface to the application |
| single-leader database | one leader assigns order | linearisable while the leader is reachable | every write travels to one region |
CockroachDB and YugabyteDB reproduce Spanner’s architecture without atomic clocks. They use hybrid logical clocks, which combine wall time with a Lamport counter, and a configured maximum clock offset. Instead of waiting out uncertainty on every write, a read that finds a value inside its uncertainty window restarts at a higher timestamp. The guarantees are slightly weaker and the cost moves from writes to some reads. Google later published how Spanner became a full SQL system, and offers it as Cloud Spanner. AWS now exposes bounded clock error through its Time Sync service and the ClockBound library, which return an interval for applications to use the same way.
When should you not want this? If your writes come from one region, a single-leader database with replicas is simpler and faster. If your data can merge, a Dynamo-style store keeps writing through partitions. Spanner’s design pays off when you need transactions across partitions of data spread over regions, and consistent snapshots across all of it.
How to read the original
Read Section 1 for the motivation and Section 3 on TrueTime, which is short. Then read Section 4 slowly, especially 4.1.2 on how timestamps are assigned to read-write transactions and the two rules, start and commit wait, that give external consistency; follow the small proof with our photo example beside you. Section 4.1.3 on safe time is dense; skim it first and return to it. Section 2 on the server organisation and directories can be skimmed unless you care about data placement. In the evaluation, look at the figure showing the distribution of ε over time and the experiment in which Paxos leaders were killed; the throughput dip and its duration follow directly from the lease length. The F1 case study at the end connects the design back to the advertising workload that motivated it.
That completes this set. Each paper here answered the question Lamport posed in a different way: MapReduce avoided it with a single master, Dynamo accepted partial order and merged, Raft built a total order with a majority, and Spanner bounded physical time. The next set, Databases & Storage, starts with Codd’s relational model and moves down through recovery and storage engines to the log.
The original. Read it after this page; the explainer above is a map, not a substitute.
The author of the CAP theorem explains how Spanner relates to it, in eight readable pages.
The production documentation for the mechanism this page explains.