SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Clock Synchronization Problem
  • NTP: Network Time Protocol
  • Logical Clocks
  • Lamport Timestamps
  • Vector Clocks
  • Hybrid Logical Clocks (HLC)
  • TrueTime (Google Spanner)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Time and Ordering

TrueTime (Google Spanner)

A clock that says "the time is between here and here", and a database that waits out the doubt.

⏱ 13 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

TrueTime is Google's clock API for its global database Spanner. Instead of saying "it is 12:00:00.005", it says "the real time is somewhere between 12:00:00.001 and 12:00:00.009". It is honest about the doubt.

  • Each data centre has GPS receivers and atomic clocks, so the doubt (called Ξ΅, epsilon) is only a few milliseconds.
  • Before a transaction commits, Spanner waits out the doubt. This is called commit wait.
  • The result is external consistency: if transaction 1 finished before transaction 2 started, everyone sees 1 before 2, anywhere in the world.

02Concept: What is it?

No clock is exact, so most systems ignore the error and hope. TrueTime does the opposite: it measures the error and returns it. The call TT.now() returns an interval [earliest, latest] that is guaranteed to contain the real time. Two helper calls are TT.after(t) (is t surely in the past?) and TT.before(t) (is t surely in the future?).

To keep the interval small, Google puts GPS receivers and atomic clocks in every data centre, and each machine syncs from several time masters every 30 seconds. Between syncs the uncertainty grows slowly (assuming up to 200 microseconds of drift per second), so Ξ΅ is a sawtooth, usually 1 to 7 ms.

Commit wait: the clever part

A transaction needs a commit timestamp s. Spanner picks s = TT.now().latest, which is a time no earlier than real now. Then it waits until TT.after(s) is true, which means s is certainly in the past. Only then does it release the locks and tell the client "committed".

Choose the latest time, then wait it out
πŸ™‹Ask to commitTT.now() = [100, 108]
→↓pick s = 108
⏳Commit waituntil TT.after(108)
→↓108 is surely past
βœ…Tell the clientrelease locks
The wait is about 2Ξ΅. After it, the timestamp is in the real past, so any later transaction anywhere gets a larger one.
🧠Why it works
If T1 is acknowledged only after its timestamp s1 is in the real past, then T2, which starts after that, picks a time from a window whose latest is later than s1. So s2 > s1, with no communication between the two servers at all.

03Real-Life Example

🍡The Race Official with a Blurry Stopwatch
A race official knows their stopwatch is only right to within Β±2 seconds. To record a winner fairly, they note the latest possible finish time, then wait 4 seconds before announcing the result. After the wait, they know that any runner who finishes afterwards will be recorded with a larger time, no matter whose stopwatch is used. The wait is the price of being fair without a perfect clock.
Race
TrueTime and Spanner
A stopwatch right to Β±2 s
A clock with uncertainty Ξ΅
Writing the latest possible finish time
s = TT.now().latest
Waiting 4 s before announcing
Commit wait (about 2Ξ΅)
A better stopwatch, so a shorter wait
GPS and atomic clocks: smaller Ξ΅
Later runners always get a bigger time
External consistency
The official admits the doubt
TT.now() returns an interval, not a point
Official refuses to announce if the watch is lost
If Ξ΅ grows too big, writes slow down
External consistency
1️⃣T1 commitss1, client told
→↓real time passes
2️⃣T2 startson another continent
→↓s2 > s1
πŸ‘€Readerssee T1 before T2
If T1 finished before T2 started in the real world, then s1 < s2 for all observers.

04Why Do We Need It?

🌍Global strong consistency
A database spread across continents that still behaves like one machine.
πŸ“ΈLock-free snapshot reads
Pick a timestamp and read the whole database as of that moment, with no locks.
🧩No central clock
Every server picks its own timestamps and the order still comes out right.
πŸ”’Strong guarantee
External consistency is stronger than serializability alone: it also respects real time.
πŸ“Honest about error
A known bound turns a guess into a rule you can build a proof on.
πŸͺœCompared with HLC
It shows what you get when you are willing to pay for hardware and for waiting.
TrueTime trades a few milliseconds of waiting for a global order that matches real time, with no coordination between servers.

05Where Do We Use It?

πŸ›οΈGoogle Spanner
The home of TrueTime. It runs Google Ads, Play and many other services.
☁️Cloud Spanner
The same technology sold as a managed service on Google Cloud.
⏱️AWS Time Sync and ClockBound
AWS exposes a clock error bound in a similar spirit, so apps can reason about the uncertainty.
πŸͺ³CockroachDB
No special hardware, so it uses an uncertainty interval on reads and a hybrid clock instead.
πŸ›°οΈTime-critical systems
Finance and telecom use PTP and GPS time for tight bounds.
πŸ”¬Research and teaching
The reference example of using clock uncertainty on purpose.

06Types / Parts / How It Works

The TrueTime API

CallReturnsMeaning
TT.now()[earliest, latest]The real time is definitely inside this interval
TT.after(t)true or falseTrue if t has definitely passed (t < earliest)
TT.before(t)true or falseTrue if t has definitely not arrived yet (t > latest)
Ξ΅ (epsilon)(latest βˆ’ earliest) / 2The uncertainty. Typically 1 to 7 ms

Where the clock comes from

Two kinds of time master per data centre
GPS time masters
πŸ›°οΈGPS receiversexact, but antennas and signals can fail
Armageddon masters
βš›οΈAtomic clocksdrift slowly, no outside signal
Every machine
πŸ–₯️Time daemonpolls several masters, drops liars, tracks error
They fail in different ways, so one failing does not break the bound.

Three ways to order transactions

ApproachHow order is decidedCost
Plain wall clocksEach server stamps its own clockCan be wrong by the clock error
Hybrid logical clockWall time plus a counter, carried in messagesCausal order only, not real-time order
TrueTimeLatest of the interval, then wait until it is pastSpecial hardware and a few ms wait per write
Central timestamp serverOne machine hands out numbersA bottleneck and a single point of failure
VisualizerCommit wait: slide the uncertainty, skip the waitSet Ξ΅ and the gap between the two transactions. With commit wait, the order is always right. Switch it off and make the gap smaller than 2Ξ΅ to watch T2 get an older timestamp than T1. Also see the commit wait grow with Ξ΅.
Commit rule
Real time (ms) β†’010203040T1: server with a fast clockTT.now() = [earliest, latest]commit wait 8 mss1 = 16T2: server with a slow clock (starts after T1 is acknowledged)s2 = 19β–² T2 starts
Worst case allowed by the bound: server 1's clock is 4 ms fast and server 2's clock is 4 ms slow. Real time is always inside each TT interval.
Commit wait
8 ms
about 2 Γ— Ξ΅
s1 (T1 timestamp)
16
s2 (T2 timestamp)
19
Order matches real life?
Yes
s2 > s1
Hot-row limit
~125/s
writes to one row (wait mode)
T1 picked s1 = 16 (the latest time it could be) and waited 8 ms until that moment was certainly past. Only then did the client hear β€œcommitted”. T2 started later, so its interval begins after s1, and s2 = 19 > s1. The commit order matches real order, even though the two clocks disagree.

A simplified model of a Spanner write. Real Spanner picks the timestamp at the leader when the commit starts, and overlaps the wait with the replication it needs anyway. Google reports an average Ξ΅ of a few milliseconds (GPS and atomic clocks in each data centre).

07How to Use It / Steps / Implementation

Using the TrueTime idea in your own design

  1. 1
    Get a clock with a known error bound
    Use GPS, PTP or a cloud service that exposes the bound (for example AWS ClockBound). Know your Ξ΅, do not guess it.
  2. 2
    Read the interval, not the point
    Ask for [earliest, latest]. Treat the single timestamp as a lie.
  3. 3
    Pick the commit timestamp as the latest
    s = latest. It is a time that cannot be in the past.
  4. 4
    Wait until s is surely past
    Hold the commit until earliest > s. That is about 2Ξ΅. Do not release locks or answer the client before that.
  5. 5
    Overlap the wait with other work
    Spanner does the wait while the replicas are agreeing on the write (Paxos), so most of it is hidden.
  6. 6
    Use timestamps for snapshot reads
    A read at time T sees every commit with s ≀ T. No locks are needed for read-only work.
  7. 7
    Watch Ξ΅
    Alert when the uncertainty grows, because every write now waits longer.
πŸ’‘Doing less than Google
Without special hardware you can still use the same pattern: pick a bound for your clock error, add it to timestamps, and treat events closer than the bound as "order unknown". CockroachDB does this with its uncertainty interval.
⚠️The bound must be true
The whole scheme depends on the real time always being inside the interval. If the clock error is ever larger than reported, ordering silently breaks. That is why Google adds monitoring and evicts machines whose clocks drift.

08Key Terms to Know

TermMeaning in easy words
TrueTimeGoogle's clock API that returns a time interval
TT.now()Returns [earliest, latest], which contains the real time
TT.after(t)True if time t has definitely passed
Epsilon (Ξ΅)Half the width of the interval: the clock uncertainty
Commit waitWaiting until the chosen commit timestamp is surely in the past
External consistencyIf T1 finishes before T2 starts, T1 has the smaller timestamp, everywhere
Strict serializabilityTransactions behave as if run one by one, in real-time order
Time masterA machine with GPS or an atomic clock that serves time to others
Snapshot readA lock-free read of the data as of a chosen timestamp
Paxos groupThe replicas of one Spanner shard, which agree on each write
Clock error boundA promised limit on how wrong a clock can be

09Pros, Cons and Trade-offs

βœ… Pros
  • Global order that matches real time
  • Lock-free consistent reads at any timestamp
  • No central timestamp server
  • A provable guarantee, as long as the bound holds
  • Wait is short (a few ms) and overlaps with replication
⚠️ Cons
  • Needs GPS and atomic clocks in every data centre
  • Every write pays about 2Ξ΅ of waiting
  • Throughput on a single hot row is limited by 1 / (2Ξ΅)
  • Everything depends on the error bound being right
  • Hard to copy outside a company that runs its own hardware

Trade-offs

ChoiceWe gainWe lose
TrueTimeExternal consistency, global readsHardware cost and commit wait
Hybrid logical clockNo special hardware, no waitOnly causal order
Smaller Ξ΅Shorter commit wait, faster writesMore GPS and atomic clock gear and sync traffic
Larger Ξ΅ (cheap clocks)Cheap and easySlow writes, long waits
Read at a past timestampNever blocks on writesData a few seconds old
Strong readsAlways the newest dataMay wait for the latest commits

10Common Problems and Mistakes

Common mistakes

  1. Thinking it is just very good NTP. The key is not accuracy but the guaranteed bound that it exposes through the API.
  2. Skipping commit wait. Without it, two transactions can get timestamps in the wrong order relative to real time.
  3. Picking the earliest instead of the latest. The timestamp must be one that is not yet in the past when chosen.
  4. Releasing locks before the wait ends. Another transaction could read the data before the timestamp is safe.
  5. Assuming it works without special clocks. If Ξ΅ is 200 ms, every write takes 400 ms more.
  6. Trusting an unchecked bound. A faulty clock that reports a too-small Ξ΅ breaks consistency.
  7. Forgetting hot rows. Writes to the same row cannot be faster than one per 2Ξ΅.

Things to watch

πŸ“‘Time master failure
If all masters in a region fail, Ξ΅ grows and writes slow down.
πŸ”Clock outliers
A machine with a bad oscillator must be found and removed from service.
πŸ›°οΈGPS problems
Antenna damage and jamming happen. This is why atomic clocks are in the mix.
πŸ“ˆEpsilon sawtooth
Ξ΅ rises between syncs and drops after each one. Average and worst case differ.

11Real-World Examples

πŸ“„The Spanner paper (2012)
β€œSpanner: Google’s Globally Distributed Database”, which introduced TrueTime and external consistency.
πŸ“’Google Ads (F1)
Its main database moved to Spanner so it could stay consistent across data centres.
⏱️Ρ in practice
Google reported Ξ΅ of about 1 to 7 ms, with an average near 4 ms.
☁️Cloud Spanner
Customers get TrueTime-backed consistency without running any clock hardware.
πŸͺ³CockroachDB
Cannot assume a tight bound, so it restarts a read when a value falls inside its uncertainty window.
πŸ› οΈAWS ClockBound
A library that returns a clock error bound so apps can build similar logic on EC2.
πŸ“Note
Spanner is a CP system in CAP terms. When the network partitions, it stays correct and may become unavailable for some writes. TrueTime does not remove that trade-off.
Mini case: two bank transfers on two continents
πŸ‡ΊπŸ‡ΈT1 in the USs1 = latest, waits 8 ms
→↓client is told, then calls Europe
πŸ‡ͺπŸ‡ΊT2 in Europeinterval starts after s1
→↓s2 > s1
πŸ“ŠReport as of Tsees both or neither, in order
Commit wait stops the second transfer from looking older than the first.

12Related Topics to Read Next

Clock Synchronization Problem→

Why clocks disagree and why this extra effort is needed.

NTP: Network Time Protocol→

The ordinary way to sync clocks, and its limits.

Hybrid Logical Clocks (HLC)β†’

The cheaper option that uses normal hardware.

Consistency Models→

Where external consistency fits among the models.

CAP Theorem→

Spanner is CP: strong consistency, and less availability during a partition.

Paxos→

How the replicas of each Spanner shard agree on a write.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”TT.now(): an interval [earliest, latest] that contains the real time.
  • βœ”Ξ΅: the uncertainty, about 1 to 7 ms with GPS and atomic clocks.
  • βœ”Commit: choose s = latest, then wait until TT.after(s).
  • βœ”Wait length: about 2Ξ΅, overlapped with replication.
  • βœ”Gives: external consistency (real-time order) and lock-free snapshot reads.
  • βœ”Cost: special clocks, and a hot row is limited to about 1 / (2Ξ΅) writes per second.
  • βœ”Cheaper cousin: hybrid logical clock plus an uncertainty interval.
  • βœ”One line: β€œDo not pretend you know the time. Admit the doubt, then wait it out.”
← Previous
Hybrid Logical Clocks (HLC)
Next β†’
Consensus Algorithms