CockroachDB Cheat Sheet
CockroachDB distributed SQL database covering cluster setup, transactions, geo-partitioning, and PostgreSQL-compatible syntax.
Starting a Local Cluster
Spin up a 3-node insecure cluster for local development.
cockroach start --insecure --store=node1 --listen-addr=localhost:26257 \ --http-addr=localhost:8080 --join=localhost:26257,localhost:26258,localhost:26259 &cockroach start --insecure --store=node2 --listen-addr=localhost:26258 \ --http-addr=localhost:8081 --join=localhost:26257,localhost:26258,localhost:26259 &cockroach start --insecure --store=node3 --listen-addr=localhost:26259 \ --http-addr=localhost:8082 --join=localhost:26257,localhost:26258,localhost:26259 &cockroach init --insecure --host=localhost:26257cockroach sql --insecure --host=localhost:26257
Transaction Retry Handling
CockroachDB uses serializable isolation and may require client-side retries.
BEGIN;SAVEPOINT cockroach_restart;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;RELEASE SAVEPOINT cockroach_restart;COMMIT;-- On a 40001 (serialization_failure) error, client should:-- ROLLBACK TO SAVEPOINT cockroach_restart; and retry the statements.-- Most drivers (pgx, node-postgres via cockroach adapters) do this automatically.
Geo-Partitioning
Pin rows to specific regions for data locality and compliance.
ALTER TABLE users ADD COLUMN region STRING NOT NULL DEFAULT 'us-east';ALTER TABLE users PARTITION BY LIST (region) ( PARTITION us (VALUES IN ('us-east', 'us-west')), PARTITION eu (VALUES IN ('eu-west')));ALTER PARTITION us OF TABLE users CONFIGURE ZONE USING constraints = '[+region=us-east1]';ALTER PARTITION eu OF TABLE users CONFIGURE ZONE USING constraints = '[+region=eu-west1]';
Distributed SQL Concepts
What makes CockroachDB behave differently from single-node Postgres.
- Range- the unit of data distribution (~512MB by default), automatically split and rebalanced
- Raft consensus- each range is replicated (typically 3x) and agrees on writes via Raft
- Serializable isolation- the only isolation level; strongest consistency guarantee, may cause retryable errors under contention
- SQL_ERROR 40001- serialization failure code the client must catch and retry
- Follower reads / AS OF SYSTEM TIME- read slightly stale data from the nearest replica for lower latency
- Zone configs- control replica placement, count, and lease preferences per table/partition
Changefeeds (CDC)
Stream row-level changes to Kafka, cloud storage, or webhooks for downstream pipelines.
CREATE CHANGEFEED FOR TABLE orders, payments INTO 'kafka://broker:9092' WITH updated, resolved = '10s', format = 'json';-- Sinkless changefeed streamed directly to the SQL client, useful for debuggingEXPERIMENTAL CHANGEFEED FOR orders WITH updated;SHOW CHANGEFEED JOBS;PAUSE JOB 123456789012345678;RESUME JOB 123456789012345678;
Backup, Restore & Point-in-Time Recovery
Take consistent cluster-wide backups to object storage with incremental support.
BACKUP DATABASE app INTO 's3://my-bucket/backups?AWS_ACCESS_KEY_ID=...&AWS_SECRET_ACCESS_KEY=...' AS OF SYSTEM TIME '-10s';-- Subsequent backups append incrementally to the same collectionBACKUP DATABASE app INTO LATEST IN 's3://my-bucket/backups?...';SHOW BACKUPS IN 's3://my-bucket/backups?...';RESTORE DATABASE app FROM LATEST IN 's3://my-bucket/backups?...' WITH new_db_name = 'app_restored';
Diagnosing Hot Ranges & Query Plans
Find contention hotspots and inspect execution stats beyond a basic EXPLAIN.
EXPLAIN ANALYZE SELECT * FROM orders WHERE customer_id = 42;-- Ranges receiving disproportionate QPS, a common cause of latency spikesSELECT range_id, lease_holder, qpsFROM crdb_internal.rangesORDER BY qps DESCLIMIT 10;-- Bulk-load without the SQL execution engine overheadIMPORT INTO orders (id, customer_id, amount, created_at) CSV DATA ('s3://my-bucket/orders.csv?AWS_ACCESS_KEY_ID=...');
Multi-Region Survival Goals
Configure table/database-level failure tolerance across regions declaratively.
ALTER DATABASE app SET PRIMARY REGION 'us-east1';ALTER DATABASE app ADD REGION 'us-west1';ALTER DATABASE app ADD REGION 'eu-west1';-- Survive an entire region outage, not just a single nodeALTER DATABASE app SURVIVE REGION FAILURE;-- Pin a table's rows to the region of the requesting clientALTER TABLE users SET LOCALITY REGIONAL BY ROW;
Advanced Operational Concepts
Terms for running CockroachDB reliably at scale beyond a single-node dev cluster.
- Lease holder- the replica currently authorized to serve reads/writes for a range; leases move automatically on node failure or rebalance
- Hot range- a range receiving disproportionate traffic, causing contention; surfaced via crdb_internal.ranges
- Changefeed- a CDC stream of row-level changes to Kafka, cloud storage, or webhook sinks, with resolved timestamps for exactly-once processing
- IMPORT INTO- bulk-loads CSV/Avro/Parquet by writing SSTables directly, bypassing per-row SQL execution overhead
- SURVIVE REGION FAILURE- a multi-region database setting that keeps the cluster available even if an entire region goes offline
- SHOW JOBS- tracks the progress of long-running backups, restores, imports, and schema changes
Use `AS OF SYSTEM TIME follower_read_timestamp()` for read-heavy, latency-sensitive queries that can tolerate a few seconds of staleness — it lets CockroachDB serve from the nearest replica instead of routing to the leaseholder, often cutting cross-region read latency dramatically.