System Design Space
Knowledge graphSettings

Updated: June 24, 2026 at 5:01 PM

CockroachDB: distributed SQL database and architecture

medium

CockroachDB as a distributed SQL DBMS: SQL over distributed KV, key ranges, leaseholders, Raft replication, multi-region locality, and automatic rebalancing.

CockroachDB promises a unified SQL interface without manual sharding, but this chapter makes the price explicit: data locality, routing, and latency never disappear.

In real systems, it helps you reason about range and leaseholder placement, transaction retries, and idempotency as unavoidable parts of strict transactional design.

In interviews and architecture reviews, this material is useful when you need to explain why a team would pay extra latency and complexity for strong consistency in distributed SQL.

Practical value of this chapter

Range locality

Plan range and leaseholder placement for critical regions to keep latency within the SLO.

Serializable by default

Design transaction retries and idempotency around strict transaction guarantees.

Clock and network assumptions

Account for clock uncertainty and inter-region network impact on write latency and throughput.

Interview defense

Defend CockroachDB through distributed SQL requirements and the cost of strong consistency.

Decision frame and editorial focus

Chapter focus

key ranges, leaseholders, Raft replication, and multi-region locality

Workload profile

The focus is transactional SQL at horizontal and often regional scale where one classic node no longer scales cleanly.

Good fit

Distributed SQL is justified when strong guarantees matter more than simplicity and the team accepts latency, coordination, and operations cost.

Boundary and risk

Key risks are hot keys, cross-region transactions, consensus cost, rebalancing, and the illusion of free sharding.

Connect next

Always validate the choice against a PostgreSQL/MySQL baseline, distributed transactions, and multi-region architecture.

Source

Wikipedia: CockroachDB

CockroachDB timeline, release milestones, and broad context for its distributed SQL positioning.

Open article

Official website

CockroachDB Product Overview

How the product positions itself: resilience, horizontal scaling, locality controls, and the workloads it is built for.

Open page

CockroachDB is a distributed SQL DBMS that takes on what you would otherwise wire up by hand: strong consistency, surviving the loss of a whole zone, and growing write throughput by adding nodes. In system design you reach for it when an OLTP service has to run across regions, fail over on its own, and still look like plain SQL with no manual sharding in application code. You pay for that with coordination latency and design discipline — covered below.

History and context

2014design draft

Initial project concept

Spencer Kimball publishes the first design sketch for a distributed SQL system that later becomes CockroachDB.

2015Cockroach Labs

Company foundation

Cockroach Labs is founded to develop the product as a distributed SQL platform for fault-tolerant services.

2017v1.0.0

First production-ready release

The 1.0 line closes the base contract you can build production on: SQL interface, transaction guarantees, and cluster mode.

2019Business Source License

Shift to source-available licensing

Project licensing changes from Apache 2.0 to the Business Source License (BuSL).

2025v25.1.4

Stable 25.1 release line

The 25.1 line shifts the focus toward teams already running the cluster in production: performance, scaling behavior, and operational maturity.

Core architecture elements

SQL gateway + PostgreSQL compatibility

Any node accepts the query: it speaks the PostgreSQL wire protocol and becomes a gateway for distributed execution itself. For the application this means no new driver and no rewritten queries.

Ranges, leaseholder, and Raft

The keyspace is split into ranges; a leaseholder owns each one, and Raft keeps the replicas in agreement. The price of this scheme is an extra network hop whenever the range you need lives in another region.

ACID transactions and Parallel Commits

The transaction layer holds strong consistency with write intents and an atomic commit protocol. Parallel Commits remove one network round from the hot path — otherwise a distributed write would cost noticeably more.

Geo-locality and auto-rebalancing

The cluster places data across regions and rebalances it as nodes join — no manual sharding. The flip side: if rows are pinned to the wrong region, locality adds read latency instead of removing it.

Data model and transaction path

The heart of CockroachDB is the seam where a familiar SQL table turns into a distributed key-value store. The interactive section below walks that transition: ranges, replicas, write intents, isolation modes, and locality controls.

CockroachDB data model: ranges, replicas, transactions

CockroachDB builds SQL semantics on top of a distributed KV engine where data is split into ranges and replicated via Raft.

Why CockroachDB differs from classic single-node SQL

  • Tables and indexes map to a distributed KV keyspace that auto-splits into ranges.
  • Each range has replicas; leaseholder coordinates reads/writes for that range.
  • Transactions rely on write intents, lock table, and atomic commit protocol (Parallel Commits).
  • Multi-region locality controls are available for data placement and latency goals.

SQL -> KV keyspace

Table rows and secondary index entries are stored as key-value pairs in a global keyspace.

Key elements

Primary index keysSecondary index keysRange boundariesAutomatic split/merge

Typical use cases

  • Horizontal growth
  • Hot key isolation
  • Large table partitioning

Example

CREATE TABLE orders (
  id UUID PRIMARY KEY,
  tenant_id UUID,
  status STRING,
  created_at TIMESTAMPTZ
);

CockroachDB architecture by layer

To see where latency comes from, it helps to split the database into layers: SQL gateway, transaction layer, range distribution, Raft replication, and storage with locality mechanics. Each layer adds its own step to the request path.

Clients and SQL access
PostgreSQL wire protocolDrivers + ORMSQL shellCloud/self-hosted
Layer transition
SQL and transaction layer
Cost-based optimizerDistributed tx coordinatorSerializable / Read CommittedParallel Commits
Layer transition
Ranges and replicas
KV keyspaceRange splits/mergesLeaseholderAuto-rebalancing
Layer transition
Consensus and replication
Raft per rangeMajority commit3 replicas by defaultQuorum reads/writes
Layer transition
Storage and locality
MVCC valuesWrite intentsZone/region placementMulti-AZ resilience
Layer transition
Operations
Online schema changesNode add/removeBackupsObservability

System view

Distributed SQLStrong consistency focusCloud-native resilience

Workload profile

Transactional OLTPGeo-distributed servicesOperational analytics (limited)

Operational trade-offs

Cross-range transaction overheadSchema/key design mattersMore complex than single-node SQL

Read / Write Path through components

This is where the cost of each query becomes visible: the path from the SQL gateway through range routing, leaseholder handling, Raft consensus, and on to transaction commit. The more steps cross into another region, the costlier the operation.

Read/Write Path Explorer

Interactive walkthrough of CockroachDB requests through gateway, leaseholder, Raft, and transaction layer.

1
Client Tx
INSERT UPDATE UPSERT
2
Range Routing
meta lookup
3
Write Intents
provisional values
4
Raft Replication
majority quorum
5
Commit + Resolve
txn record
Write path: transaction lays down write intents on leaseholders, replicates through Raft quorum, and commits via transaction record/Parallel Commits.

Write path

  1. Tables/indexes are split into ranges; transaction keys decide single-range vs multi-range execution.
  2. Writes are first recorded as intents (provisional values with lock semantics).
  3. Commit requires Raft majority per affected range plus transaction-layer coordination.
  4. Under contention, retryable errors are expected and clients should retry transactions.

When to choose CockroachDB

Good fit

  • Mission-critical OLTP where losing a zone or region is not an option and the data has to stay consistent under ACID semantics.
  • Products whose load keeps growing, where you would rather scale reads and writes by adding nodes than by another round of manual sharding.
  • Global SaaS and fintech workloads: keep data close to users, survive a region failure, and stay available throughout.
  • A team ready to invest in schema, index, and key design and to operate a distributed SQL cluster — without that, the upside never lands.

Avoid when

  • A single-node app that a classic local SQL database serves fine — the distributed layer only makes it costlier and harder here.
  • Heavy analytical scans: those want a specialized OLAP engine, not a transactional store.
  • An application that cannot retry a transaction under contention for the same rows — here retries are normal operation, not a failure.
  • No people or tooling to operate multi-node infrastructure and observe the distributed layer — the cluster quietly turns into a black box.

Practice: DDL and DML

From theory to code: practical CockroachDB SQL examples. DDL sets up the schema, indexes, and multi-region settings; DML shows transactions, UPSERT, and concurrent access to the same rows — exactly where retries show up.

DDL and DML examples in CockroachDB

DDL controls schema/indexes; DML handles transactional and distributed read/write paths.

CockroachDB supports PostgreSQL-like SQL DDL with online schema changes, but key/index design is critical for distributed performance.

Create table with primary key

CREATE TABLE

Primary key shape influences distribution in keyspace/ranges.

CREATE TABLE accounts (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  balance DECIMAL(18,2) NOT NULL,
  status STRING NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

Covering secondary index

CREATE INDEX ... STORING

Helps avoid extra lookups for hot read endpoints.

CREATE INDEX idx_accounts_tenant_status
ON accounts (tenant_id, status)
STORING (balance, created_at);

Configure multi-region database

ALTER DATABASE ... REGION

Multi-region SQL features support locality and survivability goals.

ALTER DATABASE appdb PRIMARY REGION "us-east1";
ALTER DATABASE appdb ADD REGION "eu-west1";
ALTER DATABASE appdb ADD REGION "ap-southeast1";

Related chapters

  • Database Selection Framework - Where to draw the line: when CockroachDB's distributed SQL earns its cost on consistency and scaling, and when the operating cost outweighs it.
  • PostgreSQL: history and architecture - What to compare against: the classic single-node PostgreSQL OLTP path next to CockroachDB's distributed SQL model — you can see what you pay and what you get back.
  • YDB: distributed SQL database and architecture - Two distributed SQL platforms side by side: where their multi-region behavior, transactional guarantees, and operational cost diverge.
  • Distributed Transactions (2PC/3PC) - What happens under the hood of a commit: how a distributed transaction is coordinated and what the write path pays for it in latency and availability.
  • Multi-region and global systems - Geo-distributed design in practice: how data locality and region-failure resilience pull latency in opposite directions and where you have to choose.
  • Jepsen and consistency models - Claimed guarantees and real ones are different things: how to test a distributed database's consistency under node and network failures instead of taking the docs at their word.

Enable tracking in Settings