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
| Problem | CockroachDB approach |
|---|---|
| Single-node DB HA limits | Raft-replicated ranges |
| Horizontal scale SQL | Automatic range splitting |
| Multi-region OLTP | Geo-partitioning + replication zones |
| Postgres compatibility | Wire protocol subset + SQL |
| Survive node/zone/region failure | Configurable survival goals |
| Cloud-neutral deployment | Self-host or Cockroach Cloud |
Workload fit matrix
| Workload | Fit | Caveat |
|---|---|---|
| Multi-region OLTP | Strong | Latency + contention |
| Financial transactions | Strong | Serializable overhead |
| Heavy analytics scans | Moderate | Use CDC to warehouse |
| Single-region low-latency | Moderate | Postgres simpler |
| Hot row updates | Weak | Contention on single range |
| Edge SQLite scale-out | Weak | Different product tier |
4. Assumptions and System Model
| Assumption | Implication |
|---|---|
| HLC with bounded clock skew | Max offset configuration required |
| Raft majority per range | Quorum for writes |
| Serializable default | Transactions may retry on conflict |
| Symmetric nodes | No special master except ephemeral leaseholders |
| Network partitions | Survival 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
| Term | Definition |
|---|---|
| Range | Replicated shard of sorted keyspace (~512 MB default target) |
| Leaseholder | Raft leader holding range lease for writes |
| Store | RocksDB instance on a node holding ranges |
| HLC | Hybrid Logical Clock—physical + logical time |
| Transaction record | Coordinates distributed txn commit |
| Intent | Provisional write pending commit |
| Gossip | Node membership and capacity dissemination |
| Zone config | Replication and placement rules |
| Follow-the-workload | Move leaseholder near traffic |
| SERIALIZABLE | Default 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
- Client connects to any node; SQL gateway parses query.
- DistSQL plans scan on
usersPK range. - Leaseholder serves consistent read at HLC timestamp.
- MVCC selects visible versions; results return.
Walkthrough B: Cross-range transfer transaction
BEGIN; UPDATE accounts SET balance...touches two ranges.- Gateway picks txn timestamp; writes intents on both ranges.
- Commits transaction record; marks committed.
- Resolves intents to visible values.
- On conflict, serializable restart error—client retries.
Walkthrough C: Node failure
- Node 2 dies; ranges with replicas on node 2 elect new Raft leaders.
- Leaseholders reassign after ~seconds [config-dependent].
- Clients retry transient errors; survive zone goal met if quorum intact.
Walkthrough D: Range split under growth
- Range exceeds size threshold (~512 MB).
- Split at midpoint key; new Raft group for right half.
- Rebalancer moves replicas per zone config.
Walkthrough E: Follower reads with closed timestamps
- Application configures
AS OF SYSTEM TIME follower_read_timestamp()for analytics. - Read served from nearest replica without contacting leaseholder—lower latency in multi-region.
- Staleness bounded by closed timestamp propagation—document in API SLA.
- Financial balance reads still use strong read on leaseholder—tiered consistency by endpoint.
- Misuse of follower reads on money path caught in architecture review checklist.
Walkthrough F: IMPORT and bulk ingest
IMPORT INTOfrom CSV on cloud storage—distributed ingest bypassing SQL insert path.- Ranges split and replicate during import; transaction per batch internally.
- Faster than row-by-row INSERT for initial load; validate constraints post-import.
- Run
SHOW RANGESto verify distribution; rebalance if skew detected. - Cutover application only after import validation and backup snapshot.
CockroachDB vs Spanner decision matrix
| Requirement | Lean CockroachDB | Lean Spanner |
|---|---|---|
| Multi-cloud portable | ✓ | |
| GCP-native managed | ✓ | |
| External consistency narrative | Moderate (HLC) | Strong (TrueTime) |
| PostgreSQL wire compatibility | ✓ (subset) | PostgreSQL dialect |
| Commodity NTP only | ✓ | Needs TrueTime infra |
| Global strong SQL default | Both—evaluate latency |
Walkthrough E: SURVIVE REGION FAILURE drill
- Cluster configured with
SURVIVE REGION FAILUREand replicas across three regions. - Simulate full loss of one region during load test.
- Ranges in lost region elect new leaseholders in surviving regions; writes resume after seconds to minutes [verify SLO].
- Applications see elevated
40001restart rate on contended keys during rebalancing. - 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
| Property | CockroachDB |
|---|---|
| Serializable | Default isolation |
| Linearizable | Per-key via Raft + leaseholder |
| External consistency | Weaker than Spanner TrueTime—HLC-based |
| Durability | Raft committed entries |
| Survival | Configurable zone/region goals |
Serializable restart: Conflicting concurrent txns may abort with 40001 retry error—safety over blind progress.
9. Failure Scenarios
| Failure | Behavior | Mitigation |
|---|---|---|
| Hot row contention | High restart rate | Queue redesign; shard key in app |
| Clock skew spike | Node may become unavailable | --max-offset monitoring; NTP |
| Loss of quorum range | Range unavailable | Survival goals; add replicas |
| Network partition | Minority partition read-only/unavailable | Multi-region topology design |
| Large transaction | Exceeds size limit | Batch operations |
| Schema change | Online but resource-heavy | Schedule off-peak |
| Follower reads stale | By design without closed timestamp | Use correct read API |
10. Performance Characteristics
| Dimension | Behavior |
|---|---|
| Single-row read | Low ms in-region |
| Cross-range txn | 2PC-style overhead |
| Serializable | Extra restarts under contention |
| Geo-distributed writes | WAN latency on consensus |
| Scans | Distributed 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-offsetand monitor clock sync. - Set zone configs for
num_replicasandconstraints. - 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 statusin monitoring; alert onlivenessandreplicationred flags. - Document client retry policy for
40001in 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
| System | Comparison |
|---|---|
| Google Spanner | TrueTime external consistency; managed GCP |
| TiDB/Yugabyte | Similar distributed SQL; different internals |
| Aurora | Single-writer region; simpler |
| PostgreSQL + Patroni | HA single primary; manual sharding |
| Cassandra | No serializable SQL transactions |
17. Common Misconceptions
| Misconception | Reality |
|---|---|
| "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
- Prototype contention on hot keys before multi-region commit.
- Document serializable retry in all client libraries.
- Compare external consistency needs vs Spanner honestly.
- Use survival goals aligned with actual failure domains.
- 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
- Range vs shard? — Cockroach range is Raft-replicated key span.
- Raft role? — Consensus per range.
- Leaseholder? — Raft leader serving writes for range.
- HLC purpose? — Timestamp ordering without TrueTime hardware.
- Intent in transaction? — Provisional write pending commit.
- Serializable restart? — Conflict abort; client retries.
- Cockroach vs Spanner clocks? — HLC+NTP vs TrueTime GPS/atomic.
- Survival goals? —
ZONEvsREGIONfailure tolerance. - Geo-partitioning? — Pin ranges to regions.
- Hot row problem? — Single range serializes writes.
- Gossip protocol? — Cluster metadata dissemination.
- STORE vs NODE? — Node has one or more stores (disks).
- Follow-the-workload? — Move lease near query source.
- When choose Postgres instead? — Single region, simpler ops.
Scoring rubric (principal)
| Dimension | Strong | Weak |
|---|---|---|
| Internals | Ranges, Raft, intents, HLC | "Distributed Postgres" |
| Consistency | Serializable + restarts | Ignores conflicts |
| Spanner compare | TrueTime vs HLC honest | "Same thing" |
| Ops | Clock sync, zone configs | Ignore 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.
- IMPORT vs INSERT load? — Distributed ingest path for bulk.
- Follower reads tradeoff? — Staleness bound vs latency.
- When Yugabyte/TiDB instead? — Similar space; evaluate portability and ops.
22. Interview Follow-Ups
- Design multi-region bank accounts table. — REGIONAL BY ROW, survival goals, retry logic.
- High serialization restart rate—debug? — Contention visualization; schema change.
- Prove Raft quorum math for 5-node 3-region. — Replica placement per zone config.
- External consistency audit question. — Explain HLC limits vs Spanner commit wait.
- 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:
| Step | Mechanism | Explanation |
|---|---|---|
| 1 | Serializable txn | Default isolation |
| 2–3 | Intents | Provisional writes per range |
| 4 | Raft per range | Durability + consensus |
| 5 | Commit + resolve | Percolator-style visibility |
| 6 | Range split | Hot range mitigation |
| 7 | Ops | Serialization restart rate |
Production stack
| Layer | Component | Purpose |
|---|---|---|
| Cluster | CockroachDB 23.x | Distributed SQL |
| Storage | RocksDB per node | LSM per store |
| Placement | Zone configs + REGIONAL BY ROW | Geo-partitioning |
| Clients | pgwire + retry wrapper | Handle 40001 |
| Obs | DB Console + Prometheus | Ranges, 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:
| Step | Failure | Mitigation |
|---|---|---|
| Hot SKU | Restart storm | Per-SKU queue; REGIONAL BY ROW |
| 40001 | Client must retry | Idempotent UPDATE |
| Split | Momentary latency | Pre-scale before events |
| WAN cross-region | High commit latency | Survival goals; regional data |
SLOs (one-liner)
| SLO | Target (illustrative) | How achieved |
|---|---|---|
| Single-range write p99 | < 50 ms local | 3-node min; good schema |
| Serializable | Default | OCC + restart |
| Restart rate | < 1% txn | Contention design |
| Range balance | No range > 512 MB sustained | Splits + monitoring |
| Multi-region write p99 | Region-dependent | REGIONAL BY ROW |
22B. Game Day Playbooks
Catalog
| # | Drill | Frequency | Primary SLO under test |
|---|---|---|---|
| GD-1 | Hot row restart storm | Quarterly | Success rate |
| GD-2 | Range split under load | Semi-annual | Latency spike |
| GD-3 | Node loss in 3-region | Quarterly | Raft quorum |
| GD-4 | Cross-region txn latency | Annual | Latency budget |
| GD-5 | Zone config misplacement | Semi-annual | Survival goals |
| GD-6 | Clock skew / HLC edge | Annual | Serializable 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."