CockroachDB

On this page 8

CockroachDB is a distributed SQL database that spreads data across many nodes, replicates it with the Raft consensus protocol and offers serializable ACID transactions through a PostgreSQL-compatible interface. Among database systems it belongs to the category often called NewSQL: it keeps the relational model and SQL while scaling horizontally like a NoSQL store.

The design goal, reflected in the name, is survivability: a cluster should keep serving reads and writes when a disk, a node, an availability zone or even a whole region fails. In databases built for global applications, that resilience is traded against higher write latency caused by consensus between replicas.

How CockroachDB stores and replicates data

CockroachDB stores all data in a single ordered key-value space that is split into contiguous chunks called ranges. Tables and indexes are encoded as keys, and each range holds a slice of that key space, by default up to about 512 MiB before it splits automatically.

Each range is replicated, typically three times, and the replicas form a Raft group. One replica holds the leaseholder role and serves consistent reads, while writes are committed only after a majority of replicas acknowledge them. Underneath, every node persists its replicas in Pebble, a log-structured merge storage engine written in Go.

The architecture is organized in layers, each with a clear responsibility.

LayerResponsibilityKey mechanism
SQL layerParses and plans queriesCost-based optimizer and distributed execution
Transaction layerGuarantees ACID semanticsWrite intents and hybrid logical clocks
Distribution layerMaps keys to rangesRange descriptors and meta ranges
Replication layerKeeps replicas consistentRaft consensus per range
Storage layerWrites data to diskPebble LSM engine
Main layers of the CockroachDB architecture

Transactions and consistency model

CockroachDB runs transactions at SERIALIZABLE isolation by default, the strongest level defined by the SQL standard. It achieves this without a central coordinator by combining multi-version concurrency control with timestamps from hybrid logical clocks, which merge physical time with a logical counter.

Because node clocks are never perfectly synchronized, the system assumes a maximum clock offset, 500 ms by default. Reads that encounter values within this uncertainty window may need to restart at a higher timestamp, and a node that detects excessive clock drift shuts itself down to protect consistency. Unlike Google Spanner, CockroachDB does not rely on atomic clocks, which is why it handles uncertainty in software.

Contention shows up as transaction retry errors with SQLSTATE 40001. Applications must be prepared to retry failed transactions, and drivers or client libraries often wrap this logic. Since version 23.2, READ COMMITTED isolation is also available for workloads migrated from engines where that level is the norm.

CockroachDB compared with other database systems

CockroachDB sits between single-node relational engines and distributed NoSQL stores. It speaks the PostgreSQL wire protocol, so many PostgreSQL drivers and tools work, but it is a separate engine with its own storage, planner and feature set.

SystemScaling modelConsistencyTypical fit
CockroachDBHorizontal, automatic shardingSerializable by defaultGlobal transactional applications
PostgreSQLVertical, manual sharding or extensionsConfigurable, read committed defaultGeneral-purpose relational workloads
MySQLVertical with read replicasRepeatable read default in InnoDBWeb applications and OLTP
Apache CassandraHorizontal, peer-to-peerTunable, eventual by defaultHigh write throughput, wide rows
Amazon DynamoDBManaged horizontal partitionsEventual or strong per readKey-value access on AWS
Positioning against related systems

PostgreSQL compatibility is wide but not complete. Some extensions, certain system catalogs and specific behaviors such as sequence semantics differ, so migrations need testing rather than a simple connection string change.

Multi-region deployment and data placement

CockroachDB lets architects declare where data lives using SQL rather than custom application routing. A database is assigned regions and a survival goal, and individual tables receive a locality setting that determines replica and leaseholder placement.

LocalityData placementBest for
REGIONAL BY TABLELeaseholder in one home regionData used mostly from one region
REGIONAL BY ROWEach row homed by a region columnUser data that must stay near its owner
GLOBALReplicated everywhere, fast readsRarely changed reference data
Table locality options in multi-region clusters

The two survival goals are ZONE survival, which tolerates loss of one availability zone, and REGION survival, which tolerates loss of an entire region but needs at least three regions and adds cross-region latency to writes. Row-level homing also supports data residency requirements, because rows can be pinned to replicas in a given jurisdiction.

Operating CockroachDB in practice

Operations focus on node count, schema design and contention rather than manual sharding. Adding a node triggers automatic rebalancing of ranges, and rolling upgrades allow version changes without full downtime.

  • Avoid sequential primary keys: monotonically increasing keys concentrate writes on one range and create a hotspot; UUIDs or hash-sharded indexes spread the load.
  • Keep transactions short: long transactions widen the contention window and increase retries.
  • Size for at least three nodes: fewer nodes cannot keep a Raft majority after a failure.
  • Watch clock synchronization: NTP or a cloud time service must keep offsets well below the configured maximum.
  • Use follower reads for slightly stale analytics queries to avoid crossing regions.

The software is offered as a self-hosted binary, on Kubernetes through an operator, and as a managed cloud service. Licensing changed over time, and current releases are distributed under a proprietary license with a free tier, so organizations should review licensing terms before adoption.

Limitations and common misconceptions

CockroachDB is not automatically faster than a single-node database. Every write needs a consensus round trip, so single-row write latency is usually higher than in PostgreSQL on local storage, and cross-region writes can take tens to hundreds of milliseconds.

MisconceptionRealityImplication
It is just distributed PostgreSQLIt is a separate engine with wire compatibilityTest extensions and edge behaviors
Scaling removes all bottlenecksHot keys still serialize on one rangeDesign keys for even distribution
Serializable means no errorsConflicts surface as retry errorsImplement client-side retry loops
It suits analytics workloadsIt is optimized for OLTPPair it with an analytical store such as ClickHouse
Misconceptions and the reality behind them

In plain words

CockroachDB is a database that lives on many computers at once instead of one. Every piece of data is kept in at least three copies, and the copies vote before any change is accepted, so the information stays correct even if one machine breaks.

Think of a ledger kept by three clerks in different buildings. A change is final only when a majority of the clerks agree. If one building loses power, the other two keep working, and the missing clerk catches up later.

A real-world example

A payment platform serves customers in Europe and North America and must keep European account data inside the European Union. It runs a CockroachDB cluster with nine nodes across three regions: Frankfurt, Virginia and Oregon, with REGION survival enabled.

The accounts table uses REGIONAL BY ROW, with a region column set at sign-up, so European rows keep their replicas and leaseholders in Frankfurt. Currency reference tables are marked GLOBAL for fast local reads everywhere. Local writes complete in roughly 10 to 20 ms, while the rare cross-region transfer takes around 150 ms.

When a cloud provider outage takes the Virginia region offline for two hours, the cluster keeps accepting payments from the remaining regions, and no committed transaction is lost. After recovery the Virginia nodes rejoin and catch up automatically.