Skip to main content

CockroachDB Architecture

1. Executive Summary​

CockroachDB is a distributed SQL database designed for survivability, horizontal scale, and serializable transactions without custom clock hardware. Data is partitioned into ranges (contiguous key spans), each replicated across nodes via Raft. A distributed transaction layer provides serializable isolation using multi-version concurrency control (MVCC) and Hybrid Logical Clocks (HLC) for timestamp ordering—conceptually related to Google Spanner but portable on commodity NTP-synchronized infrastructure.

Nodes are symmetric—any node can serve as SQL gateway, routing to leaseholders for ranges. Geo-partitioning pins data to regions for latency and compliance. CockroachDB targets globally distributed OLTP and multi-region active-active workloads where teams want PostgreSQL-compatible SQL with built-in replication and failover.

Principal architects compare CockroachDB to Spanner, Aurora, and traditional PostgreSQL—evaluating serializable cost, follow-the-workload latency, range splitting, and operational complexity of running a distributed consensus system. Honest HLC vs TrueTime comparison separates credible architects from marketing slides.

2. Why This Topic Matters​

CockroachDB is the reference Spanner-alternative interview topic:

  • Raft per range vs Spanner's Paxos per shard.
  • HLC vs TrueTime — external consistency differences.
  • Serializable default — performance implications.
  • Multi-region survival goals — SURVIVE ZONE/REGION FAILURE.
  • Range merges/splits — automatic rebalancing.

Misunderstanding leads to designing hot rows on single ranges, ignoring transaction contention, or expecting Spanner-exact external consistency on NTP alone.

Bring a Spanner comparison cheat sheet to every Cockroach interview—panels will ask for clock and consistency differences within five minutes.

3. Problems Being Solved​

ProblemCockroachDB approach
Single-node DB HA limitsRaft-replicated ranges
Horizontal scale SQLAutomatic range splitting
Multi-region OLTPGeo-partitioning + replication zones
Postgres compatibilityWire protocol subset + SQL
Survive node/zone/region failureConfigurable survival goals
Cloud-neutral deploymentSelf-host or Cockroach Cloud

Workload fit matrix​

WorkloadFitCaveat
Multi-region OLTPStrongLatency + contention
Financial transactionsStrongSerializable overhead
Heavy analytics scansModerateUse CDC to warehouse
Single-region low-latencyModeratePostgres simpler
Hot row updatesWeakContention on single range
Edge SQLite scale-outWeakDifferent product tier

4. Assumptions and System Model​

AssumptionImplication
HLC with bounded clock skewMax offset configuration required
Raft majority per rangeQuorum for writes
Serializable defaultTransactions may retry on conflict
Symmetric nodesNo special master except ephemeral leaseholders
Network partitionsSurvival goals determine availability

Safety: Serializable isolation; Raft log durability. Liveness: Requires quorum per range; clock jump beyond max offset can cause issues—monitor NTP.

5. Essential Terminology​

TermDefinition
RangeReplicated shard of sorted keyspace (~512 MB default target)
LeaseholderRaft leader holding range lease for writes
StoreRocksDB instance on a node holding ranges
HLCHybrid Logical Clock—physical + logical time
Transaction recordCoordinates distributed txn commit
IntentProvisional write pending commit
GossipNode membership and capacity dissemination
Zone configReplication and placement rules
Follow-the-workloadMove leaseholder near traffic
SERIALIZABLEDefault isolation—strongest SQL standard level

6. Core Mechanism​

6.1 Cluster architecture​

Figure 1: Any node serves SQL; ranges replicate via Raft across stores.

6.2 Distributed write transaction (simplified)​

Figure 2: Transaction coordinator writes intents on ranges, commits txn record, then resolves intents.

6.3 Multi-region placement​

Figure 3: Geo-partitioning places data near users; survival goals define replica count per region.

7. Step-by-Step Walkthrough​

Walkthrough A: Single-range read​

  1. Client connects to any node; SQL gateway parses query.
  2. DistSQL plans scan on users PK range.
  3. Leaseholder serves consistent read at HLC timestamp.
  4. MVCC selects visible versions; results return.

Walkthrough B: Cross-range transfer transaction​

  1. BEGIN; UPDATE accounts SET balance... touches two ranges.
  2. Gateway picks txn timestamp; writes intents on both ranges.
  3. Commits transaction record; marks committed.
  4. Resolves intents to visible values.
  5. On conflict, serializable restart error—client retries.

Walkthrough C: Node failure​

  1. Node 2 dies; ranges with replicas on node 2 elect new Raft leaders.
  2. Leaseholders reassign after ~seconds [config-dependent].
  3. Clients retry transient errors; survive zone goal met if quorum intact.

Walkthrough D: Range split under growth​

  1. Range exceeds size threshold (~512 MB).
  2. Split at midpoint key; new Raft group for right half.
  3. Rebalancer moves replicas per zone config.

Walkthrough E: Follower reads with closed timestamps​

  1. Application configures AS OF SYSTEM TIME follower_read_timestamp() for analytics.
  2. Read served from nearest replica without contacting leaseholder—lower latency in multi-region.
  3. Staleness bounded by closed timestamp propagation—document in API SLA.
  4. Financial balance reads still use strong read on leaseholder—tiered consistency by endpoint.
  5. Misuse of follower reads on money path caught in architecture review checklist.

Walkthrough F: IMPORT and bulk ingest​

  1. IMPORT INTO from CSV on cloud storage—distributed ingest bypassing SQL insert path.
  2. Ranges split and replicate during import; transaction per batch internally.
  3. Faster than row-by-row INSERT for initial load; validate constraints post-import.
  4. Run SHOW RANGES to verify distribution; rebalance if skew detected.
  5. Cutover application only after import validation and backup snapshot.

CockroachDB vs Spanner decision matrix​

RequirementLean CockroachDBLean Spanner
Multi-cloud portable✓
GCP-native managed✓
External consistency narrativeModerate (HLC)Strong (TrueTime)
PostgreSQL wire compatibility✓ (subset)PostgreSQL dialect
Commodity NTP only✓Needs TrueTime infra
Global strong SQL defaultBoth—evaluate latency

Walkthrough E: SURVIVE REGION FAILURE drill​

  1. Cluster configured with SURVIVE REGION FAILURE and replicas across three regions.
  2. Simulate full loss of one region during load test.
  3. Ranges in lost region elect new leaseholders in surviving regions; writes resume after seconds to minutes [verify SLO].
  4. Applications see elevated 40001 restart rate on contended keys during rebalancing.
  5. Post-drill report documents RTO/RPO achieved vs product marketing claims—adjust client retry and schema if needed.

Practice explaining intents and transaction records on a whiteboard before comparing Cockroach to Spanner in interviews. Mention serializable client retries in every multi-region design. Compare HLC limits to Spanner commit wait without equating the two systems. Zone survival goals should match actual failure domains, not marketing region names alone. Hot-row contention is the default failure mode for naive global SQL schemas on Cockroach. Application-level queues per hot key are a valid pattern when serializable restarts spike. Clock sync monitoring is as important as replication monitoring in multi-region Cockroach deployments.

8. Invariants and Guarantees​

PropertyCockroachDB
SerializableDefault isolation
LinearizablePer-key via Raft + leaseholder
External consistencyWeaker than Spanner TrueTime—HLC-based
DurabilityRaft committed entries
SurvivalConfigurable zone/region goals

Serializable restart: Conflicting concurrent txns may abort with 40001 retry error—safety over blind progress.

9. Failure Scenarios​

FailureBehaviorMitigation
Hot row contentionHigh restart rateQueue redesign; shard key in app
Clock skew spikeNode may become unavailable--max-offset monitoring; NTP
Loss of quorum rangeRange unavailableSurvival goals; add replicas
Network partitionMinority partition read-only/unavailableMulti-region topology design
Large transactionExceeds size limitBatch operations
Schema changeOnline but resource-heavySchedule off-peak
Follower reads staleBy design without closed timestampUse correct read API

10. Performance Characteristics​

DimensionBehavior
Single-row readLow ms in-region
Cross-range txn2PC-style overhead
SerializableExtra restarts under contention
Geo-distributed writesWAN latency on consensus
ScansDistributed parallel; can contend with OLTP

Compare to Spanner: no commit wait on TrueTime—different external consistency story.

11. Scalability Limits​

  • Hot ranges limit single-key throughput.
  • Raft groups millions of ranges—control plane must scale.
  • Cross-region writes latency bounded by speed of light + consensus.
  • Serializable conflicts cap write concurrency on overlapping keys.
  • SQL compatibility gaps vs PostgreSQL—verify extensions needed.

12. Operational Considerations​

  • Configure --max-offset and monitor clock sync.
  • Set zone configs for num_replicas and constraints.
  • Watch txn restarts, range unavailability, replication lag.
  • Rolling upgrades node by node.
  • Backup to cloud storage; test restore drills.
  • Capacity: 3+ nodes minimum production; odd count for quorum math in small clusters.
  • Run cockroach node status in monitoring; alert on liveness and replication red flags.
  • Document client retry policy for 40001 in every service README using Cockroach.
  • Quarterly game day: kill random node during business hours in staging; measure app impact.
  • Review zone configs after every region addition—survival goals drift silently.

13. Security Considerations​

  • TLS node-to-node and client connections.
  • RBAC SQL users and roles.
  • Encryption at rest in stores.
  • Network policies restrict DB port exposure.
  • Audit logging for compliance.

14. Cost Considerations​

  • Minimum 3 nodes even for small workloads—overhead vs single Postgres.
  • Cross-region replication doubles/triples storage and WAN traffic.
  • Cockroach Cloud vs self-host ops labor.
  • Serializable restarts translate to application retry load—factor in app servers.

Serializable retry application pattern​

Client libraries should implement exponential backoff on 40001 serialization failure with jitter and max attempts. Idempotency keys on writes prevent duplicate side effects when retry succeeds after ambiguous timeout. Document retry budget in API SLO—users experience latency spikes during contention storms, not hard errors, if clients behave correctly.

RANGE vs REPLICA GC tuning (multi-region)​

ALTER DATABASE CONFIGURE ZONE survival goals and replica placement determine behavior during region loss. SURVIVE REGION FAILURE requires replicas in 3+ regions with careful quorum math—consult Cockroach docs for current syntax. Misconfigured zones create clusters that appear multi-region but lose quorum on single region failure.

Changefeed to warehouse pattern​

Use changefeeds (enterprise feature—verify licensing) to stream row changes to Kafka → Snowflake for analytics. Keeps OLTP path on Cockroach without full table scans. Monitor changefeed lag as critical SLO—backpressure can impact OLTP if misconfigured.

When Cockroach loses to Postgres​

Single-region, <1 TB, team knows Postgres deeply, no horizontal scale requirement—Cockroach adds consensus overhead without benefit. Principal architects defend simplicity; distributed SQL is a deliberate complexity purchase.

15. Production Implementations​

Case study: Multi-region payment metadata (illustrative)​

Context​

Fintech needs active-active US/EU with serializable balance updates.

Design​

REGIONAL BY ROW on accounts table; SURVIVE REGION FAILURE; gateway in each region.

Challenge​

Hot merchant account—serializable restarts spiked. Mitigated with per-merchant queue serializing updates in application layer.

Spanner comparison​

Chose Cockroach for multi-cloud portability; accepted HLC vs TrueTime tradeoff for external consistency narrative.

Extended operations narrative​

Region failure drill: US-East loss failed over reads to EU replicas in 4 minutes; writes resumed after lease rebalancing. Clock skew alert during NTP maintenance paused one node—monitoring prevented split-brain write acceptance. Changefeed to Kafka feeds Snowflake analytics—lag SLO 5 minutes with paging. Schema migration on 800 GB table completed online but saturated disk IO—now throttle DDL during peak.

16. Alternatives and Tradeoffs​

SystemComparison
Google SpannerTrueTime external consistency; managed GCP
TiDB/YugabyteSimilar distributed SQL; different internals
AuroraSingle-writer region; simpler
PostgreSQL + PatroniHA single primary; manual sharding
CassandraNo serializable SQL transactions

17. Common Misconceptions​

MisconceptionReality
"Same as Spanner"HLC not TrueTime; different guarantees
"Postgres drop-in"Feature subset; test migrations
"Serializable means no retries"Restarts expected under contention
"Any node is equally fast"Leaseholder locality matters
"Geo-partitioning is automatic"Requires schema and zone design

18. Principal Architect Perspective​

  1. Prototype contention on hot keys before multi-region commit.
  2. Document serializable retry in all client libraries.
  3. Compare external consistency needs vs Spanner honestly.
  4. Use survival goals aligned with actual failure domains.
  5. CDC to warehouse for analytics—not heavy scans on OLTP.

CockroachDB buyers want Spanner-like stories without GCP lock-in—principal honesty about HLC limits and serializable restarts builds trust; overselling external consistency creates audit and latency surprises later. Application teams must implement idempotent retry as a platform standard, not per-service improvisation.

Operating playbook (first 90 days)​

Days 1–30: Validate NTP/max-offset monitoring on all nodes. Document survival goals and zone configs in ADR.

Days 31–60: Load test hot keys identified in schema review; measure serialization restart rate. Client libraries implement retry with idempotency keys.

Days 61–90: Multi-region failover drill; measure RTO. Compare measured cross-region write latency to product SLO promises.

19. Architecture Review Exercise​

Scenario: Global inventory table with single sku PK; high concurrent updates worldwide.

Findings: Single range hotspot; redesign sku + warehouse shard or queue per SKU.

20. Whiteboard Explanation​

"CockroachDB shards the keyspace into ranges—each range is a Raft group with a leaseholder handling writes. SQL gateways on any node receive queries, use DistSQL to plan distributed execution, and coordinate transactions with intents and a transaction record—two-phase style across ranges. Timestamps come from Hybrid Logical Clocks combining physical time and a logical counter to order events without GPS clocks. Default isolation is serializable: conflicting transactions may restart. Ranges split as they grow; the rebalancer moves replicas per zone configuration for survival and locality. "It's PostgreSQL-wire compatible for many apps but architecturally a consensus-based distributed store, not a single-node Postgres."

Principal addendum: Contrast Spanner—commit wait and TrueTime enable stronger external consistency. For Cockroach, discuss serializable restarts and hot row limits honestly. Draw three-node Raft quorum when explaining range survival.

21. Interview Questions​

  1. Range vs shard? — Cockroach range is Raft-replicated key span.
  2. Raft role? — Consensus per range.
  3. Leaseholder? — Raft leader serving writes for range.
  4. HLC purpose? — Timestamp ordering without TrueTime hardware.
  5. Intent in transaction? — Provisional write pending commit.
  6. Serializable restart? — Conflict abort; client retries.
  7. Cockroach vs Spanner clocks? — HLC+NTP vs TrueTime GPS/atomic.
  8. Survival goals? — ZONE vs REGION failure tolerance.
  9. Geo-partitioning? — Pin ranges to regions.
  10. Hot row problem? — Single range serializes writes.
  11. Gossip protocol? — Cluster metadata dissemination.
  12. STORE vs NODE? — Node has one or more stores (disks).
  13. Follow-the-workload? — Move lease near query source.
  14. When choose Postgres instead? — Single region, simpler ops.

Scoring rubric (principal)​

DimensionStrongWeak
InternalsRanges, Raft, intents, HLC"Distributed Postgres"
ConsistencySerializable + restartsIgnores conflicts
Spanner compareTrueTime vs HLC honest"Same thing"
OpsClock sync, zone configsIgnore survival goals

Extended scoring notes​

Principal bar: Explains intents + txn record without confusing with 2PC textbook only. Compares HLC to TrueTime honestly. Weak hire: "Distributed Postgres" hand-wave with no restart or hot row discussion.

  1. IMPORT vs INSERT load? — Distributed ingest path for bulk.
  2. Follower reads tradeoff? — Staleness bound vs latency.
  3. When Yugabyte/TiDB instead? — Similar space; evaluate portability and ops.

22. Interview Follow-Ups​

  1. Design multi-region bank accounts table. — REGIONAL BY ROW, survival goals, retry logic.
  2. High serialization restart rate—debug? — Contention visualization; schema change.
  3. Prove Raft quorum math for 5-node 3-region. — Replica placement per zone config.
  4. External consistency audit question. — Explain HLC limits vs Spanner commit wait.
  5. Migrate from Postgres—risks? — Extension compatibility, serializable semantics.

Additional principal scenarios​

Scenario: Latency SLO missed for cross-region writes. Answer: Measure WAN + consensus; consider regional by row; async replication for non-critical reads; do not promise Spanner-like global write latency without TrueTime-class infra.

Scenario: 40001 restart storm during flash sale. Answer: Queue per hot SKU at application layer; shard inventory rows; reduce transaction scope; pre-scale nodes before event.

Scenario: Auditor asks if Cockroach matches Spanner external consistency. Answer: Honest no—serializable with HLC; different real-time ordering guarantees; document in compliance narrative with commit-wait distinction.

22A. Production Low-Level Design (Interview + Game Day)​

Interview + ops bar per Production LLD and Game Day Standard. Whiteboard range splits + Raft per range vs serializable retries (40001).

C4 context​

Step-by-step flow:

StepMechanismExplanation
1Serializable txnDefault isolation
2–3IntentsProvisional writes per range
4Raft per rangeDurability + consensus
5Commit + resolvePercolator-style visibility
6Range splitHot range mitigation
7OpsSerialization restart rate

Production stack​

LayerComponentPurpose
ClusterCockroachDB 23.xDistributed SQL
StorageRocksDB per nodeLSM per store
PlacementZone configs + REGIONAL BY ROWGeo-partitioning
Clientspgwire + retry wrapperHandle 40001
ObsDB Console + PrometheusRanges, splits, restarts

Schema snippet​

CREATE TABLE inventory (
sku STRING PRIMARY KEY,
qty INT,
region STRING
) LOCALITY REGIONAL BY ROW;

-- Hot SKU → single range → split or app-layer queue

Happy-path sequence​

Failure / serializable restart + range split​

Step-by-step flow:

StepFailureMitigation
Hot SKURestart stormPer-SKU queue; REGIONAL BY ROW
40001Client must retryIdempotent UPDATE
SplitMomentary latencyPre-scale before events
WAN cross-regionHigh commit latencySurvival goals; regional data

SLOs (one-liner)​

SLOTarget (illustrative)How achieved
Single-range write p99< 50 ms local3-node min; good schema
SerializableDefaultOCC + restart
Restart rate< 1% txnContention design
Range balanceNo range > 512 MB sustainedSplits + monitoring
Multi-region write p99Region-dependentREGIONAL BY ROW

22B. Game Day Playbooks​

Catalog​

#DrillFrequencyPrimary SLO under test
GD-1Hot row restart stormQuarterlySuccess rate
GD-2Range split under loadSemi-annualLatency spike
GD-3Node loss in 3-regionQuarterlyRaft quorum
GD-4Cross-region txn latencyAnnualLatency budget
GD-5Zone config misplacementSemi-annualSurvival goals
GD-6Clock skew / HLC edgeAnnualSerializable safety

GD-1 — Serializable restart storm​

GD-2 — Range split during flash sale​

Pass criteria: Client retry library handles 40001; no unbounded restart loops.

23. Strong Answer Example​

Question: "How does CockroachDB achieve distributed transactions?"

Answer using PRACTICE. Strong voice: intents + Raft per range + HLC + serializable restarts.

Student interview script (PRACTICE)​

P — Problem framing​

"SQL across shards needs atomicity without a single log. Cockroach uses Percolator-style intents on each range (Raft group), a transaction record, and HLC timestamps for serializable ordering. Conflicts return 40001 restart—apps must retry idempotently. Range splits prevent one hot range from owning all traffic."

R — Requirements​

TypeRequirement
FRACID across ranges
NFRSerializable default
OpsRestart rate, range metrics

A — Assumptions​

AssumptionWhy
pg-compatible wireRetry wrapper required
Multi-region possibleLatency cost explicit
Not Spanner TrueTimeHLC — no commit wait

C — Capacity​

Hot keys → single range until split; queue at app for flash sales.

T — Topology​

Gateway → leaseholders → Raft; DistSQL for reads.

I — Invariants​

"Intents resolve only after txn record commits; serializable conflicts → restart; Raft quorum per range."

C — Constraints​

ConstraintResponse
Hot rowQueue; split
Cross-regionREGIONAL BY ROW
vs SpannerHLC vs TrueTime honestly

E — Evolution​

Single region → multi-region zones → geo-partitioned tables.

Closing: "Intents on Raft ranges, HLC serializable, client retries on 40001, splits for hot ranges—distributed Postgres semantics with real distributed-systems costs."

Scoring signals​

StrongWeak
Intents + Raft ranges"Distributed Postgres"
40001 retriesIgnore restarts
Range splitsNo hot row plan
HLC vs TrueTimeClaim external consistency

Compact outline (2 min)​

"Txn coordinator; intents per range; Raft replicate; commit record; resolve intents; serializable via HLC; 40001 retry; splits on hot ranges; REGIONAL BY ROW for geo."

24. Weak Answer Example​

Weak: "CockroachDB uses Raft so it's consistent; Postgres apps work unchanged globally."

Red flags: No ranges/intents; ignores retries; overstated Postgres compatibility.

25. Hands-On Exercise​

  1. Start 3-node local cluster; run distributed SQL demo.
  2. Observe range splits inserting large dataset.
  3. Provoke serializable restart with concurrent updates.
  4. Configure multi-region demo in docs sandbox if available.
  5. Compare query plan to single-node Postgres.

26. Knowledge Check​

  1. Consensus per? (Range / Raft group.)
  2. HLC combines? (Physical + logical time.)
  3. Default isolation? (Serializable.)
  4. Intent is? (Provisional write.)
  5. Leaseholder serves? (Writes for range.)
  6. Hot row hits? (Single range contention.)
  7. Serializable restart code? (40001 typically.)
  8. Spanner clock difference? (TrueTime vs HLC.)
  9. Store contains? (RocksDB data.)
  10. Survival goal defines? (Fault tolerance level.)
  11. Intent is? (Provisional write.)
  12. DistSQL plans? (Distributed queries.)
  13. Geo-partitioning pins? (Data to regions.)

27. Flashcards​

FrontBack
RangeReplicated keyspace shard
RaftPer-range consensus protocol
LeaseholderRange leader for writes
HLCHybrid Logical Clock
IntentProvisional distributed write
SerializableStrongest default isolation
Zone configReplication and placement rules
Geo-partitioningRegional data pinning
Transaction restartConflict abort requiring retry
DistSQLDistributed query execution

28. Cheat Sheet​

ARCHITECTURE
SQL gateway → ranges → Raft → RocksDB

TRANSACTIONS
Intents + txn record + resolve | serializable restarts

CLOCKS
HLC on NTP (not TrueTime)

DESIGN
Avoid hot rows | plan multi-region survival | retry idempotency

VS SPANNER
Portable HLC | weaker external consistency story

PRINCIPAL ANCHORS
Serializable restarts expected
Hot row = range bottleneck
Raft per range
Intents + txn record
max-offset clock monitor
Zone config = survival
Honest Spanner compare
Client retry idempotent

30. References​

Primary sources​

  • Taft, R., et al. (2020). CockroachDB: The Resilient Geo-Distributed SQL Database. SIGMOD.
  • CockroachDB documentation — architecture, transactions, zone configs.
  • Corbett et al. Spanner paper — design comparison.
  • Peng, D., & Dabek, F. — Percolator transaction model.

Principal study path​

Essential companions: Google Spanner, Raft, Two-Phase Commit, MVCC, and Linearizability for consistency hierarchy context in principal interviews. Always contrast HLC with TrueTime when Spanner appears in the same loop.

Distinction​

ClaimType
Serializable defaultCockroachDB documentation
HLC vs external consistencyAcademic and vendor papers
Postgres compatibility listVersion-specific feature matrix