
It is 3 am and a whole cloud region has gone dark. For a team on a classic primary and replica setup, the next hour is a checklist: confirm the primary is really gone, promote a replica, repoint the applications, and work out which of the last few seconds of writes never made it across.
A team on a well-planned CockroachDB cluster reads about the outage at breakfast. Their database had copies of every piece of data in three regions. Two of the three were still there, so the cluster kept accepting reads and writes without anyone being paged.
That is the promise in the name: a database that is very hard to kill. It is a real promise, and it has a real price in latency, cost and a few habits you must change. This guide covers both sides.
What CockroachDB is
CockroachDB is a distributed SQL database made by Cockroach Labs. "Distributed SQL" means it gives you ordinary relational tables, joins, foreign keys and ACID transactions, but stores the data across many servers that act as one database.
It speaks the PostgreSQL wire protocol, so PostgreSQL drivers, psql and most tools connect to it. Under the SQL layer it works very differently from Postgres:
| Term | Meaning |
|---|---|
| Node | One CockroachDB server. All nodes are equal and any of them can take a query |
| Range | A chunk of a table's rows, kept in key order. Tables are split into ranges automatically as they grow |
| Replica | A copy of a range. There are three by default, on different nodes |
| Raft | The consensus protocol the replicas use to agree. A write is committed once a majority has it |
| Leaseholder | The replica that coordinates reads and writes for a range |
Because a write needs a majority, a three-replica cluster survives the loss of one node, one zone or one region, depending on how you spread the replicas. No data is lost and nothing has to be promoted by hand.
Why teams choose it
- It survives failures by design. Losing a machine or a data centre is a non-event, not a failover drill.
- It grows by adding nodes. Ranges rebalance onto new nodes while the cluster stays online. You do not have to shard tables in your application.
- Strong consistency. Transactions are
SERIALIZABLEby default, the strictest standard isolation level. There is no "eventually". - It can place data by region. A row for a European customer can live in Europe, close to that user and inside that jurisdiction.
- Maintenance without downtime. Version upgrades roll through the nodes one at a time, and schema changes such as adding a column or an index run online.
- Familiar SQL. If you know PostgreSQL, most of what you write will work.
Where CockroachDB fits, and where it does not
A strong choice for:
- Systems that must stay up through a zone or region outage: payments, orders, identity, inventory
- Applications with users on several continents
- Transactional data that has outgrown what one server can write
- Teams that would otherwise build and operate their own sharding
Look elsewhere when:
- One PostgreSQL server is enough. For most applications it is. Postgres will be faster for each single query, cheaper and simpler, with a far larger set of extensions.
- You need the lowest possible latency in one location. Every write waits for a majority of replicas to agree, which adds a little time compared with a single node, and more when replicas are far apart.
- The workload is analytics. Scanning billions of rows for reports belongs in a column store such as ClickHouse, Snowflake or BigQuery.
- You depend on a specific PostgreSQL extension or an unusual feature. Compatibility is broad but not complete. Check the feature you need before committing.
- You cannot run at least three nodes. A single node works for development, but it gives you none of the resilience you came for.
Using it the right way
Try it locally with one node, then open the SQL shell:
docker run -d --name roach -p 26257:26257 -p 8080:8080 \
cockroachdb/cockroach:latest start-single-node --insecure
docker exec -it roach ./cockroach sql --insecure
Port 26257 is for SQL. Port 8080 serves the DB Console, a web page with metrics and slow statements. --insecure turns off TLS and passwords, so use it only on your own machine.
Do not use sequential primary keys
This is the habit that matters most. Ranges are sorted by primary key. If every new row gets the next number, every insert lands in the same last range, and one part of the cluster does all the work while the rest watches. This is called a hot spot.
Use random UUIDs so that inserts spread out:
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id UUID NOT NULL REFERENCES customers (id),
total_cents INT8 NOT NULL CHECK (total_cents >= 0),
status STRING NOT NULL DEFAULT 'pending',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
The same problem applies to an index on a timestamp that always increases. A hash-sharded index spreads those writes (v22.1 or later for this short form):
CREATE INDEX orders_created_idx ON orders (created_at) USING HASH;
Note that SERIAL in CockroachDB does not produce 1, 2, 3. By default it generates large unique numbers based on time, so do not rely on them being small or gap-free.
Retry transactions
With SERIALIZABLE isolation, when two transactions conflict the database may ask one of them to try again. It reports this with SQLSTATE 40001. This is normal behaviour, not a failure, and your application must handle it.
Many drivers and frameworks have helpers. The pattern is simple, shown here with Python and psycopg 3:
import time
import psycopg
def run_transaction(conn, work, max_retries=5):
for attempt in range(max_retries):
try:
with conn.transaction():
return work(conn)
except psycopg.errors.SerializationFailure:
time.sleep(0.1 * 2 ** attempt)
raise RuntimeError("transaction did not succeed after retries")
Two things reduce retries. Keep transactions short, and never wait on a user or an external API inside one. When you read a row in order to change it, lock it first with SELECT ... FOR UPDATE so that others queue instead of colliding:
BEGIN;
SELECT stock FROM products WHERE id = '7f1c0e52-5a0b-4b1e-9a57-0d2f6c1b8e11' FOR UPDATE;
UPDATE products SET stock = stock - 1 WHERE id = '7f1c0e52-5a0b-4b1e-9a57-0d2f6c1b8e11';
COMMIT;
Recent versions also offer READ COMMITTED isolation for applications ported from PostgreSQL that cannot add retry logic easily.
Read slightly old data when you can
SELECT count(*) FROM orders AS OF SYSTEM TIME '-10s';
A query "as of ten seconds ago" does not conflict with current writes, and CockroachDB can answer it from the nearest replica. It suits reports, exports and backups.
Change large tables in batches
A single statement that touches millions of rows is one huge transaction. Delete in pieces and repeat until no rows are affected:
DELETE FROM events WHERE created_at < '2025-01-01' LIMIT 5000;
Better still, let the database expire rows itself with row-level TTL (v22.2 or later):
ALTER TABLE events SET (ttl_expire_after = '90 days');
Tell it where data should live
On a cluster that spans regions, a few statements control placement:
ALTER DATABASE shop SET PRIMARY REGION "us-east1";
ALTER DATABASE shop ADD REGION "europe-west1";
ALTER DATABASE shop ADD REGION "asia-southeast1";
ALTER DATABASE shop SURVIVE REGION FAILURE;
ALTER TABLE customers SET LOCALITY REGIONAL BY ROW;
ALTER TABLE currencies SET LOCALITY GLOBAL;
REGIONAL BY ROW keeps each row near its home region, using a hidden region column. GLOBAL suits small reference tables that are read everywhere and rarely change. Surviving a region failure needs at least three regions.
Back up anyway
Replication protects against hardware failure. It does not protect against a wrong DELETE, which is faithfully replicated everywhere.
BACKUP INTO 's3://my-backups/shop?AUTH=implicit' AS OF SYSTEM TIME '-10s';
Schedule it, and practise a restore.
How the pricing shapes your choices
There are two ways to run CockroachDB.
Self-hosted. You run the nodes. The software is source-available under Cockroach Labs' own licence, not an open-source one. At the time of writing there is a free licence for individuals and small companies and a paid one for larger organisations, so read the current terms. Your main cost is infrastructure: at least three nodes, plus network traffic between zones or regions, which cloud providers charge for.
CockroachDB Cloud. Cockroach Labs runs it. The entry plan bills by usage, measured in request units (a blend of the reads, writes and compute your queries consume) plus storage, and costs little when idle. The higher plans bill for provisioned compute.
On a usage-billed plan, cost follows work done. Full table scans, missing indexes and chatty applications that run many small queries cost money directly, so EXPLAIN is a budgeting tool as well as a tuning tool. On self-hosted clusters, more regions mean more resilience and also more nodes, more network cost and slower writes. Choose the smallest survival goal that the business really needs.
Common mistakes
- Sequential keys. Auto-increment ids and time-ordered keys create hot spots.
- No retry logic. The first busy day produces a wave of
40001errors that reach users. - Treating it as a drop-in Postgres. Most things work. Test the rest before you migrate.
- Long transactions. They conflict more and retry more.
- One enormous
UPDATEorDELETE. Batch it. - Spreading three nodes over two regions. Lose the region with two nodes and the cluster has no majority. Use three locations.
- Skipping backups because "it is replicated". Replication copies mistakes too.
- Running a production cluster with
--insecure. It disables encryption and authentication entirely.
Quick reference
| Task | Command |
|---|---|
| Connect | cockroach sql --url "postgresql://user@host:26257/shop?sslmode=verify-full" |
| Version | SELECT version(); |
| List tables | SHOW TABLES; |
| Table definition | SHOW CREATE TABLE orders; |
| Running statements | SHOW STATEMENTS; |
| Cancel one | CANCEL QUERY '<query_id>'; |
| Background jobs (schema changes, backups) | SHOW JOBS; |
| How a table is split | SHOW RANGES FROM TABLE orders; |
| Real execution plan | EXPLAIN ANALYZE SELECT ...; |
| Regions of a database | SHOW REGIONS FROM DATABASE shop; |
CockroachDB earns its place when downtime is the thing you fear most. Give it random keys, short transactions that can retry, and three real locations, and it will keep its promise.
Exploring CockroachDB with CreamDB
Because CockroachDB speaks the PostgreSQL protocol, CreamDB connects to it from a browser tab, with nothing to install. Paste the connection string your cluster gives you, or fill in host, port 26257, user and database.
- Browse databases, schemas, tables, views and functions in a tree, with each table's columns, indexes and definition. Open a table in a grid where paging, sorting and filtering run in the database.
- Write SQL in an editor with autocomplete, formatting and history, and export results to CSV, JSON or Excel.
- See the schema as an ER diagram, watch sessions in the Status panel, and read users and roles on a read-only page.
- Ask in plain English and get the SQL, a result table and a chart.
The assistant only reads on its own. Any change waits as an approval card that you answer, and read-only mode on the server blocks writes. A self-hosted cluster on a private network can be reached through an SSH tunnel.
It is free to start.
About the author
- CreamDB is a web-based database explorer with an AI assistant. Connect your databases, ask questions in plain English and get answers, tables and charts from any browser. Product news and tips here.
Comments
Join the discussionNo comments yet. Be the first to comment.




