Google Spanner System Design
A globally replicated SQL database kept consistent by synchronized clocks
By Ankur NayakReviewed
How Google built a database that replicates data across continents and still offers externally consistent transactions: every shard is a Paxos group, transactions across shards use two-phase commit, and TrueTime, an API backed by GPS and atomic clocks, gives every commit a timestamp that respects real time. This is the architecture from the 2012 paper.
Open in Studio· edit a copy- Users
- Google services, first F1 (ads)
- Storage
- Trillions of rows (design goal)
- Designed for
- Millions of machines
- Clock uncertainty (ε)
- ~1–7 ms
- Spanservers per zone
- 100s to 1000s
- F1 replicas
- 5
Requirements
Functional
- Store relational, schematized tables with SQL queries
- Run read-write transactions that span shards and data centres
- Serve consistent reads at a past timestamp without locking
- Let applications choose how many replicas their data has, and where
- Move data between machines and data centres while it is in use
Non-functional
- Externally consistent (linearizable) transactions
- Survive the loss of a data centre or region
- Scale to millions of machines and trillions of rows
- Low read latency from nearby replicas
In depth
A database that spans the planet
Most databases make you choose. You can have SQL and transactions on one machine, or you can scale out across many machines and give up cross-shard transactions and strong consistency. Spanner, which Google described in a 2012 OSDI paper, refuses the choice: it shards data across data centres on several continents, replicates every shard synchronously, and still runs general read-write transactions that are externally consistent. If transaction T1 commits before T2 starts, T2 sees T1's effects and gets a later timestamp, everywhere.
Its first customer was F1, the rewritten backend of Google's advertising system, which ran with five replicas spread across the United States. The design goal was far larger: millions of machines across hundreds of data centres and trillions of rows.
This page describes the architecture in the 2012 and 2013 papers. Google Cloud's managed Spanner builds on it, but its current internals aren't fully public.
Universes, zones and spanservers
A Spanner deployment is a universe, divided into zones: the unit of administrative deployment and of physical isolation. Each zone has one zonemaster, which assigns data to between one hundred and several thousand spanservers, and per-zone location proxies that clients use to find the spanservers holding their data. Two singletons sit above the zones: the universe master, mostly a status console for debugging, and the placement driver, which moves data between zones over minutes to meet replication constraints or balance load.
Each spanserver is responsible for 100 to 1,000 tablets. A tablet's state is a set of B-tree-like files plus a write-ahead log, all stored on Colossus, the successor to the Google File System.
A Paxos group for every tablet
On top of every tablet runs a Paxos state machine. The tablet's replicas, in different zones, form a Paxos group that agrees on one log of writes. Spanner's Paxos uses long-lived leaders with timed leases, 10 seconds by default, so a leader can serve reads and manage locks without consulting the group each time. See consensus.
The leader of each group also keeps the lock table for two-phase locking. Most transactions touch a single group, and for them the lock table plus Paxos are all that's needed. When a transaction touches several groups, the leaders run two-phase commit: one group is chosen as coordinator and the others are participants. Because every participant is a replicated Paxos group, the usual weakness of 2PC, blocking when a single machine dies, mostly disappears: a new leader takes over from the logged prepare record.
Applications control placement through directories, sets of keys that share a prefix. A directory is the unit of data placement, so one user's data can have three replicas in Europe while another's has five in North America. A background task, movedir, moves directories between groups without blocking reads and writes, using a short transaction only for the last nominal amount of data.
TrueTime: making uncertainty explicit
The famous part of Spanner is TrueTime. Instead of pretending clocks are synchronized, it exposes their error. TT.now() returns an interval [earliest, latest] that is guaranteed to contain the true current time.
It is built from a set of time masters in every data centre. Most have GPS receivers; the rest, called Armageddon masters, have atomic clocks, which fail in different ways from GPS. A timeslave daemon on every machine polls several masters every 30 seconds, applies a variant of Marzullo's algorithm to reject liars, and widens its uncertainty between polls by a conservative drift rate. In production the uncertainty ε was a sawtooth, varying from about 1 to 7 ms over each poll interval. Machines whose local clocks drift beyond the worst-case bound are evicted.
Commit wait
TrueTime makes external consistency simple to state. The coordinator leader picks a commit timestamp s no less than TT.now().latest and no less than any participant's prepare timestamp. Then it waits until TT.after(s) is true, that is, until s has certainly passed, before letting anyone see the writes. That wait is roughly 2ε. Any transaction that starts afterwards must get a larger timestamp, so timestamp order matches real-time order.
The cost of uncertainty is latency, never correctness. If the time masters become unreachable and ε grows, commits slow down but stay consistent.
Reads without locks
Timestamps also make reads cheap. A snapshot read at timestamp t takes no locks and can run on any replica that is up to date enough. Each replica tracks a safe time, the maximum timestamp at which it is up to date; if t is at or below safe time, the replica answers immediately with a consistent snapshot. Clients can give an exact timestamp or a staleness bound and let Spanner pick one. A snapshot transaction, read-only and lock-free, picks a timestamp and runs all its reads at it.
This is why Spanner can be both consistent and fast for reads: the expensive coordination happens on writes, and reads are served locally at a timestamp.
What happens when things fail
- A zone goes offline. Every group still has a majority in other zones. After the old leader's lease expires, a new leader is elected and writes resume.
- Clock uncertainty grows. Commit wait lengthens; transactions get slower, not wrong.
- A replica lags. Snapshot reads at recent timestamps wait for its safe time, or go to another replica.
The trade-offs
Spanner pays real costs for its guarantees. Every read-write transaction waits for a majority of replicas and then for commit wait. Cross-group transactions add two-phase commit. And TrueTime needs dedicated hardware in every data centre. In return, application developers get something most distributed databases don't offer: SQL-style schemas, general transactions and consistent reads at global scale, without having to reason about replication lag.
Compare it with the different set of promises in Amazon DynamoDB, and see how Zanzibar builds its consistency model on Spanner's timestamps.
What to take into an interview
- Replicate each shard as a consensus group with a long-lived leader
- Use two-phase commit only across groups, and make participants replicated
- If you need global ordering, either centralise timestamps or bound clock error and wait it out
- Serve reads at a timestamp to avoid locks
- Let data placement follow its users
Components
Application (e.g. F1)
Client. A Google service using Spanner through its client library. The first customer was F1, the rewritten backend of Google's advertising system.
Location Proxy
Service. Per-zone proxies that clients use to find which spanservers serve their data.
Zonemaster
Coordination. One per zone: assigns data to the spanservers in that zone.
Why: A zone is the unit of administrative deployment and of physical isolation; each has its own master.
Spanservers
Zone ASQL database. Each spanserver is responsible for 100 to 1,000 tablets. Every tablet has a Paxos state machine on top of it, so a tablet's replicas across zones form a Paxos group with a long-lived leader.
Why: Replicating each shard with Paxos means no single machine, zone or region holds the only copy, and failover keeps the data consistent.
Building block: Consensus (Paxos & Raft), Database Sharding
Coordinator Leader
Coordination. Leader of one participant group, chosen to coordinate two-phase commit and pick the commit timestamp.
Building block: Two-Phase Commit
Participant Leader
Coordination. Leader of another group in the transaction: acquires write locks, chooses a prepare timestamp and logs a prepare record through Paxos.
Lock Table
Cache. Kept at every leader replica; maps key ranges to lock states for two-phase locking. Mostly volatile, not replicated by Paxos.
Group Replicas
SQL database. The other members of each Paxos group, in other zones. A majority must log each prepare and commit record.
Building block: Consensus (Paxos & Raft)
Tablet Files + WAL
B-tree-like filesObject storage. Each tablet's state is stored as B-tree-like files plus a write-ahead log on Colossus.
Building block: Write-Ahead Log
Replica Spanservers
Zone BSQL database. Replicas of the same tablets in another zone or region. Any sufficiently up-to-date replica can serve snapshot reads.
Colossus
Object storage. Google's distributed file system (successor to GFS), where tablet files and logs are stored.
TrueTime Masters
GPS + atomic clocksCoordination. A set of time master machines per data centre. Most have GPS receivers; the rest, 'Armageddon masters', have atomic clocks, so the two kinds fail in different ways.
Why: Commit timestamps must respect real time across the planet; a bounded clock error makes that possible without a central timestamp server.
Timeslave Daemon
Service. Runs on every machine and polls several masters every 30 seconds, rejecting liars. TT.now() returns an interval [earliest, latest] guaranteed to contain true time.
Placement Driver
Scheduler. Moves data across zones on the timescale of minutes, to meet replication constraints or balance load. The unit it moves is a directory: keys sharing a prefix.
Universe Master
Monitoring. Primarily a console showing status information about every zone, for interactive debugging.
Request flows
Commit a read-write transaction
- The client library asks a location proxy which spanservers hold the rows it needs.
- Reads go to each group's leader, which takes read locks in its lock table.
- At commit the client sends its buffered writes; the leaders run two-phase commit, one acting as coordinator.
- The coordinator picks a commit timestamp s no earlier than TT.now().latest.
- The commit record is replicated through Paxos to a majority of each group's replicas.
- Replicas append it to their write-ahead logs on Colossus.
- After commit wait (until true time is certainly past s) the client is told the transaction committed.
Lock-free read at a timestamp
- The client finds the replicas for its data and picks a read timestamp, or a staleness bound.
- It sends the read to a nearby replica in Zone B, with no locks.
- The replica checks its safe time: it must have applied every write up to the read timestamp.
- Once it is up to date it returns a consistent snapshot of the data at that timestamp.
Move data closer to its users
- The placement driver sees a directory whose replication constraints changed, for example a user who moved to Europe.
- The directory is moved in the background to a group with the right replicas; only the final step is a short transaction.
Failure scenarios
What if: a whole zone goes offline?
Every tablet is replicated across zones by Paxos. If a zone's spanservers disappear, each affected group still has a majority elsewhere, elects a new leader once the old leader's lease runs out, and keeps serving reads and writes.
User impact: A pause of seconds for writes whose leaders were in that zone; no committed data is lost.
- Replicas in several zones per Paxos group
- Leader leases (10 s by default) bound the failover wait
What if: clock uncertainty grows?
If time masters become unreachable or unreliable, the timeslave daemons widen ε. Correctness doesn't depend on ε being small: commit wait just gets longer, so transactions slow down while staying externally consistent. Machines whose clocks drift too far are evicted.
User impact: Higher commit latency; never inconsistent data.
- Two kinds of time master (GPS and atomic clocks)
- Polling several masters and rejecting outliers
- Evict machines with bad local clocks
What if: a replica falls behind?
A snapshot read at a recent timestamp can't run on a replica whose safe time is older; it waits or the client reads from another, more up-to-date replica.
User impact: Slower reads from that replica.
- Read from any sufficiently up-to-date replica
- Accept a staleness bound to read without waiting
Trade-offs
Commit wait instead of a timestamp oracle
Pick timestamps from TrueTime and wait out the clock uncertainty before making a commit visible.
- Pros
- Global, externally consistent order without a central timestamp server
- Lock-free consistent reads at any timestamp
- Cons
- Every read-write commit pays roughly 2ε of waiting
- Needs special hardware: GPS receivers and atomic clocks
Synchronous Paxos replication across zones
Replicate every write to a majority of replicas before acknowledging it.
- Pros
- Failover loses no committed data
- Replicas never diverge
- Cons
- Write latency includes a round trip to a majority, possibly across regions
Two-phase commit across Paxos groups
Coordinate multi-shard transactions with 2PC between group leaders.
- Pros
- General transactions across any keys
- Participants are replicated, so 2PC doesn't block on a single machine
- Cons
- Cross-group transactions are slower than single-group ones
Alternatives: Keep related data in one directory so most transactions touch one group
Application-controlled placement
Let applications set replication policy per directory: how many replicas, in which regions.
- Pros
- Data can live near its users
- Durability and latency are tuned per dataset
- Cons
- Applications must think about schema and key design to keep related data together
Frequently asked questions
What is TrueTime in Spanner?
TrueTime is an API whose TT.now() call returns an interval [earliest, latest] that is guaranteed to contain the true current time. It is backed by GPS and atomic-clock time masters in every data centre; in 2012 the uncertainty was typically about 1 to 7 milliseconds.
What is commit wait?
After choosing a commit timestamp s, Spanner's coordinator doesn't let anyone see the transaction's writes until TrueTime says s has definitely passed. That wait, roughly twice the clock uncertainty, guarantees that a transaction that starts later in real time always gets a later timestamp.
How does Spanner replicate data?
Data is split into tablets, and each tablet's replicas form a Paxos group with a long-lived leader. Writes are committed once a majority of the group has logged them, and transactions that touch several groups use two-phase commit between the groups' leaders.
Does Spanner beat the CAP theorem?
No. Spanner chooses consistency: a Paxos group that can't reach a majority stops accepting writes. It stays available through the loss of a zone because every group has replicas in several zones, not because it avoids the trade-off. Eric Brewer's 2017 paper explains why Spanner is consistent with CAP.
Building blocks used
Sources
- Spanner: Google's Globally-Distributed Database · Google (OSDI)
- Spanner: Google's Globally Distributed Database (ACM TOCS) · Google
- Spanner, TrueTime and the CAP Theorem · Google (Eric Brewer)
- TrueTime and external consistency · Google Cloud Documentation