Skip to main content

Scenario: Google Spanner TrueTime

Diagram convention: Arrows and messages are labeled 1, 2, 3… to show processing order. Each diagram is followed by a Step-by-step flow table explaining every numbered step.

1. The Interview Question​

"How does Google Spanner provide external consistency globally, and what does TrueTime actually guarantee?"

2. Real-World Context​

DimensionDetail
Company / systemGoogle Spanner — globally distributed SQL; Cloud Spanner on GCP
ScaleMulti-datacenter; TrueTime via GPS + atomic clocks; external consistency at global scale
Why architects careRare example of strong global consistency — with latency, cost, and clock infrastructure tradeoffs
Public referencesSpanner paper (Corbett et al., OSDI 2012); TrueTime API

GCP deployment context​

Typical global OLTP workload on Google Cloud Spanner: multi-region instance spanning us-east1, us-central1, europe-west1; application on GKE or Cloud Run; TrueTime provided by GCP infrastructure (GPS + atomic clocks in Google DCs); VPC private access; Cloud Monitoring for commit latency and replication lag; use cases: global inventory, financial ledgers, identity, multi-region SaaS metadata.

Step-by-step flow:

StepActionExplanation
1Write orderUS client deducts inventory in global transaction.
2Read inventoryEU client reads stock — sees consistent global state.
3BEGIN transactionApp opens read-write transaction on Spanner.
4Paxos replicateWrite replicates synchronously across regions in Paxos quorum.
5TrueTime Now()Leader obtains time interval [earliest, latest].
6Commit waitWait until TT.now().earliest > commit_timestamp — external consistency.
7COMMITTransaction ack — globally externally consistent.

3. Step-by-Step Interview Answer​

Minutes 0–5: Define external consistency​

  • Transactions appear to execute in real-time order — if T1 commits before T2 starts, T2 sees T1's writes.
  • Stronger than serializability alone — serializable order may not match wall-clock order.
  • Relates to linearizability across clients with real-time constraint.
GuaranteeDefinitionSpanner provides?
SerializabilityTransactions appear in some total orderYes
LinearizabilityOperations appear instantaneous at some point between call and responseYes (per key)
External consistencySerializable order matches real-time orderYes — via TrueTime + commit wait

Step-by-step flow:

StepActionExplanation
1Real-time beforeT1 fully committed before T2 began (wall clock).
2Must see T1External consistency — T2's snapshot includes T1.

Minutes 5–15: Mechanism​

Step-by-step flow:

StepActionExplanation
1BEGINClient opens read-write transaction.
2Acquire locksLeader locks rows; reads at transaction timestamp.
3COMMIT requestClient requests commit.
4–5Paxos quorumWrite replicates to majority of replicas synchronously.
6TT.now()TrueTime returns interval [earliest, latest] — uncertainty ε.
7commit_tsAssign commit timestamp = latest from TrueTime.
8Commit waitCritical — wait until uncertainty window passes commit_ts.
9Poll until safeTT.now().earliest > commit_ts — no clock skew violation.
10COMMIT OKExternal consistency guaranteed for this transaction.

Architecture layers:

Step-by-step flow:

StepActionExplanation
1Single-shardOne Paxos group — local commit + commit wait.
2Cross-shard2PC coordinator + Paxos commit on each shard + commit wait.
ComponentRole
Paxos groupPer-shard replication; leader handles writes; quorum durability
2PC coordinatorCross-shard distributed transactions
TrueTimeGlobal time with bounded uncertainty ε (~1–7ms in Google DCs)
Commit waitDelay ack until TT.now().earliest > commit_ts

Minutes 15–30: What TrueTime is NOT​

Step-by-step flow:

ClaimReality
Perfect clockUncertainty ε exists — typically 1–7ms in Google DCs
NTP substituteNTP drift can be 10–100ms — commit wait would be unusable
Zero latency costCommit wait adds ~ε to every write — 8–15ms cross-region typical
MagicRequires GPS antennas, atomic clocks, ops discipline per DC

Why NTP fails:

Clock sourceTypical uncertainty εCommit wait impact
TrueTime (Google DC)1–7 msAcceptable for global OLTP
NTP (commodity)10–100+ msWrite latency unacceptable
HLC (CockroachDB)Logical — no wall clockExternal consistency not guaranteed

Minutes 30–45: When to use / alternatives​

Use Spanner whenUse alternative when
Global strong consistency requiredEventual consistency OK (DynamoDB, Cassandra)
SQL + horizontal scale globallySingle-region Postgres sufficient
Financial / inventory correctnessSub-10ms local writes required
Budget for cross-region write latencyCost-sensitive; PA/EL acceptable

Interview comparison:

SystemConsistencyClock mechanismWrite latency
Cloud SpannerExternal consistencyTrueTime + commit wait10–50ms multi-region
CockroachDBSerializableHybrid Logical Clock (HLC)Lower; no external consistency
Aurora GlobalRegional strongPer-region; async cross-regionLow in-region; stale cross-region
DynamoDB Global TablesEventual cross-regionLast-writer-winsSingle-digit ms
CalvinSerializableGlobal sequencerHigh throughput; different model

Step-by-step flow:

StepActionExplanation
1Majority servesPaxos quorum in 2 of 3 regions — reads/writes continue.
2Minority rejectsNo quorum — sacrifices availability for consistency (CP).

4. Whiteboard Guide​

  1. Draw Paxos group per shard with leader + followers across 3 regions
  2. Label TrueTime box with [earliest, latest] interval
  3. Draw commit wait timeline: assign commit_ts, wait until earliest > commit_ts
  4. Show 2PC arrow across two shards for distributed transaction
  5. Compare to NTP with large ε — why commit wait fails

GCP whiteboard layout​

Step-by-step flow:

StepActionExplanation
1SQL COMMITApplication commits distributed transaction.
2Paxos quorumSynchronous replication to majority.
3TT.now()Obtain time interval for commit timestamp.
4Commit waitWait for uncertainty window to pass.
5ACKExternally consistent commit confirmed.

5. Principal-Level Signals​

  • Explains commit wait without hand-waving — TT.now().earliest > commit_ts
  • States uncertainty interval ε honestly — not a perfect clock
  • Names latency cost — commit wait + WAN Paxos RTT per write
  • Compares to HLC (CockroachDB) when TrueTime unavailable
  • Distinguishes external consistency from serializability
  • Knows CP during partition — minority region unavailable

6. Red Flags​

  • "Spanner is CA" — CP when partitioned; minority loses quorum
  • "NTP is good enough for commit wait" — ε too large; writes stall
  • "Spanner is fast" — global writes 10–50ms; not for hot-row microsecond latency
  • Confuse bounded staleness reads with strong reads — product offers both
  • Ignore 2PC cross-shard latency for multi-shard transactions

7. Follow-Up Questions​

QuestionStrong answer
Why commit wait?Ensures no transaction commits with timestamp in the past relative to real time
What if GPS fails?TrueTime ε widens; commit wait increases; ops alert
CockroachDB vs Spanner?Cockroach: HLC, serializable, no external consistency; lower latency
Hot row problem?Spanner doesn't solve hot keys — shard design + application patterns
Read-only transaction?Snapshot at read timestamp; no commit wait; much faster

9. Practice Drill​

Whiteboard Spanner commit timeline (steps 1–10) in 10 minutes. Answer: "Why can't you use NTP instead of TrueTime?"


10. Production High-Level Design​

10.1 Architecture diagram index​

SectionTopic
§2GCP multi-region deployment
§3Paxos + TrueTime commit sequence
§10.2Global inventory use case
§10.3Instance + replica placement
§10.4Strong vs bounded staleness reads
§11.4Cross-shard transaction sequence
§11.5Schema + hot row mitigation
§12Regional failure behavior
§13Metrics and alerts
§146-week rollout
§15Consistency + failover tests
§16Production readiness

10.2 System context — global inventory​

Step-by-step flow:

StepActionExplanation
1Deduct stockUPDATE inventory SET qty = qty - 1 WHERE sku = X in transaction.
2Create orderSame transaction — atomic inventory + order.
3Record paymentCross-table ACID — no oversell.
4Strong readAdmin sees exact global stock.
5Bounded stalenessPartner API tolerates 10s stale for catalog browse.

10.3 Cloud Spanner instance topology​

Instance configuration:

SettingValueRationale
Instance typeMulti-regionGlobal external consistency
Regionsus-east1, us-central1, europe-west1US + EU user base
Processing units1000+Scale with QPS
Default leaderus-east1Co-locate with primary write traffic

Step-by-step flow:

StepActionExplanation
1WriteUS app writes to Paxos leader (may be in us-east1).
2Read strongEU app reads from local replica — still strong (Paxos quorum).
3–4Sync replicateEvery write replicates before ack.

10.4 Read vs write paths​

Read typeAPILatencyConsistency
Strong readDefaultHigher — latest commitExternal consistency
Bounded stalenessmax_staleness=10sLower — local replicaStale up to 10s
Stale readexact_stalenessLowestPoint-in-time snapshot
Read-only transactionBEGIN TRANSACTION READ ONLYFast — no locksSnapshot isolation

11. Production Low-Level Design​

11.1 Schema and sharding design​

CREATE TABLE Inventory (
sku STRING(64) NOT NULL,
warehouse_id STRING(32) NOT NULL,
quantity INT64 NOT NULL,
version INT64 NOT NULL,
updated_at TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true)
) PRIMARY KEY (sku, warehouse_id);

CREATE TABLE Orders (
order_id STRING(64) NOT NULL,
sku STRING(64) NOT NULL,
quantity INT64 NOT NULL,
status STRING(16) NOT NULL,
created_at TIMESTAMP NOT NULL OPTIONS (allow_commit_timestamp=true)
) PRIMARY KEY (order_id);

CREATE INDEX OrdersBySku ON Orders(sku, created_at DESC);
Design choiceRationale
PRIMARY KEY (sku, warehouse_id)Co-locate inventory per SKU+warehouse — single-shard hot path
allow_commit_timestamp=trueTrueTime commit timestamp on updated_at
Interleaved tablesParent-child same shard — single-shard transactions

11.2 Hot row mitigation​

ProblemMitigation
Single SKU global counterShard by warehouse_id; aggregate in app
Flash sale on one SKUPre-allocate inventory buckets per region
Write hotspotSpanner split/merge; distribute PK hash prefix

11.3 Client library — transaction pattern​

def deduct_inventory_and_create_order(sku: str, warehouse_id: str, qty: int, order_id: str):
def execute_transaction(transaction):
# Step 1: Read current stock (strong within transaction)
row = transaction.execute_sql(
"SELECT quantity FROM Inventory WHERE sku = @sku AND warehouse_id = @wh",
params={"sku": sku, "wh": warehouse_id},
request_options={"priority": spanner.RequestOptions.Priority.PRIORITY_HIGH},
).one()

if row[0] < qty:
raise InsufficientStockError(sku)

# Step 2: Deduct inventory
transaction.execute_update(
"UPDATE Inventory SET quantity = quantity - @qty, "
"updated_at = PENDING_COMMIT_TIMESTAMP() "
"WHERE sku = @sku AND warehouse_id = @wh",
params={"sku": sku, "wh": warehouse_id, "qty": qty},
)

# Step 3: Create order (same transaction — atomic)
transaction.execute_update(
"INSERT INTO Orders (order_id, sku, quantity, status, created_at) "
"VALUES (@oid, @sku, @qty, 'pending', PENDING_COMMIT_TIMESTAMP())",
params={"oid": order_id, "sku": sku, "qty": qty},
)

# Step 4: Commit — Paxos + TrueTime commit wait happens here
database.run_in_transaction(execute_transaction)

11.4 Inventory deduction — step-by-step​

Step-by-step flow:

StepActionExplanation
1BEGINStart read-write transaction.
2–3Read inventoryLock row; read current quantity.
4ValidateReject if insufficient stock.
5–6WriteUpdate inventory + insert order.
7COMMITClient requests commit.
82PC PrepareCross-shard two-phase commit.
9TT.now()Assign commit timestamps on each shard.
10Commit waitWait for TrueTime safe time on all shards.
11COMMIT OKGlobally externally consistent — no oversell.

11.5 Cross-shard vs single-shard​

Transaction scopeMechanismLatency
Single shardPaxos commit + commit wait~10–20ms
Cross-shard (2)2PC + 2× Paxos + 2× commit wait~20–50ms
Read-onlySnapshot timestamp; no commit wait~5–10ms

Design goal: Co-locate Inventory and Orders on same shard via interleaving when possible.

11.6 Bounded staleness read (catalog API)​

# Partner catalog API — EL acceptable
with database.snapshot(
read_timestamp=spanner.TimestampBounds(max_staleness=datetime.timedelta(seconds=10))
) as snapshot:
results = snapshot.execute_sql(
"SELECT sku, quantity FROM Inventory WHERE warehouse_id = @wh",
params={"wh": warehouse_id},
)
APIStalenessUse case
Admin dashboardStrong (default)Exact stock count
Partner catalogmax_staleness=10sBrowse; oversell protected at checkout
Analytics exportexact_stalenessPoint-in-time report

12. HA/DR and Failover​

Step-by-step flow:

StepActionExplanation
1WRITE to minorityEU region isolated from quorum.
2503No quorum — fail closed (CP behavior).
3Failover routeApp retries via US endpoint.
4COMMIT OKMajority quorum serves — RPO=0.
FailureRPORTOBehavior
Single replica crash0SecondsPaxos elects new leader
AZ failure0MinutesQuorum in remaining AZs
Region partition (minority)0N/AMinority unavailable until heal
Full region loss (majority)0MinutesRemaining regions serve if quorum

13. Observability and Operations​

MetricAlert threshold
spanner/transaction_stat.total.commit_latency p99> 100ms
spanner/transaction_stat.total.abort_countSpike — hot row contention
spanner/query_stat.total.execution_countCapacity planning
TrueTime ε (internal)> 10ms — GPS/atomic clock issue
2pc_abort_rate> 1% — cross-shard contention

Structured log:

{
"transaction_id": "txn_abc",
"operation": "deduct_inventory",
"shards_touched": 2,
"commit_latency_ms": 34,
"commit_timestamp": "2026-07-28T21:52:00.123Z",
"abort_reason": null
}

Runbook — elevated commit latency​

StepAction
1Check commit_latency p99 in Cloud Monitoring
2Identify hot rows — abort_count by table
3Review cross-shard transaction ratio
4Consider interleaved schema or PK redesign
5Scale processing units if CPU-bound
6Check TrueTime ε if commit wait dominates

14. Implementation Roadmap (6-Week Rollout)​

WeekDeliverable
1Cloud Spanner instance provisioning (multi-region)
2Schema design + interleaved tables
3Order service integration — single-shard transactions
4Cross-shard 2PC paths + latency testing
5Bounded staleness reads for catalog API
6Failover drill + commit latency dashboards

15. Testing Strategy​

TestPass criteria
Concurrent deduct same SKUNo oversell — quantity never negative
T1 commits before T2 startsT2 sees T1 writes (external consistency)
Minority region partitionWrites fail closed (503)
Bounded staleness readResponse < 10s stale per config
Cross-shard transactionAtomic commit or full rollback
Hot row 1K TPSAbort rate < 5%; latency p99 < 100ms

16. Architecture Review Checklist​

#GateStatus
1Multi-region instance for global consistency requirement☐
2PK design minimizes cross-shard transactions☐
3Hot rows identified — mitigation plan☐
4Strong reads for checkout; bounded staleness for browse☐
5commit_latency p99 dashboard + alert☐
6Minority partition fail-closed tested☐
7Processing units sized for peak QPS☐
8Interleaved tables for parent-child atomicity☐
9Compare vs Cockroach/Aurora — decision documented in ADR☐
10TrueTime / commit wait latency accepted by product SLO☐