CockroachDB
01 / 02

Distributed SQL Fundamentals

CockroachDB: Distributed SQL Fundamentals

CockroachDB is a distributed SQL database: data is automatically split into ranges, replicated across nodes via Raft consensus, and rebalanced as the cluster grows -- while still speaking the Postgres wire protocol and defaulting to Serializable isolation, the strongest SQL consistency level.

Connecting (Postgres-Compatible)

# Local dev cluster -- in-memory, ephemeral, for exploring SQL
cockroach demo

# Single-node local start
cockroach start-single-node --insecure --store=node1

# Standard Postgres wire protocol -- existing drivers/ORMs work
psql "postgresql://root@localhost:26257/defaultdb?sslmode=disable"

# Node.js example -- the pg driver just works
const { Client } = require('pg');
const client = new Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const { rows } = await client.query('SELECT * FROM orders WHERE id = $1', [42]);

Ranges, Replication & Leaseholders

  • Table data is split into ranges (~512MB by default) -- the unit of distribution and replication.

  • Each range is replicated (typically 3x) across different nodes using Raft consensus -- a write commits once a quorum (majority) of replicas durably persist it.

  • One replica per range is the leaseholder -- serves reads and coordinates writes for that range, without every read needing full consensus.

  • As tables grow, ranges automatically split, and the cluster rebalances replicas across nodes to spread load -- transparent to the application.

  • Adding nodes scales the cluster horizontally -- CockroachDB rebalances data onto new capacity automatically, no manual resharding.

Serializable Isolation & Retries

-- CockroachDB defaults to (and only offers) Serializable isolation --
-- the strongest SQL level. Conflicting concurrent transactions can
-- get a retryable error rather than silently corrupting state:

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
-- ERROR: restart transaction: TransactionRetryWithProtoRefreshError

-- Applications (or ORM client libraries) are expected to retry on
-- this error class -- a normal, expected part of running under
-- strict isolation at scale, not a bug.

Online Schema Changes

-- Most DDL runs online -- non-blocking, cluster keeps serving
-- traffic while the schema migration happens internally in the
-- background across multiple safe steps.
ALTER TABLE orders ADD COLUMN status TEXT DEFAULT 'pending';
CREATE INDEX idx_orders_status ON orders (status);
-- No downtime, no table lock for the duration of the change.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free