Home Database CockroachDB: Distributed SQL for Global Scale
Advanced 3 min · July 13, 2026

CockroachDB: Distributed SQL for Global Scale

Learn CockroachDB, a distributed SQL database that combines ACID transactions with horizontal scalability.

N
Naren Founder & Principal Engineer

20+ years shipping high-throughput database systems. Everything here is grounded in real deployments.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic knowledge of SQL (SELECT, INSERT, UPDATE, DELETE).
  • Familiarity with PostgreSQL syntax is helpful but not required.
  • Understanding of distributed systems concepts (consensus, replication) is beneficial.
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • CockroachDB is a distributed SQL database that provides ACID transactions across multiple nodes and data centers.
  • It uses a consensus protocol (Raft) to ensure consistency and high availability.
  • Supports standard SQL with PostgreSQL-compatible syntax.
  • Automatically handles replication, sharding, and rebalancing.
  • Ideal for applications requiring global scale, fault tolerance, and strong consistency.
✦ Definition~90s read
What is CockroachDB?

CockroachDB is a distributed SQL database that provides ACID transactions, horizontal scalability, and high availability across multiple nodes and data centers.

Imagine a single SQL database that can automatically split its data across many servers around the world, survive any server failure, and still behave like a single, consistent database.
Plain-English First

Imagine a single SQL database that can automatically split its data across many servers around the world, survive any server failure, and still behave like a single, consistent database. That's CockroachDB—like a cockroach that can't be killed, your data survives even if parts of the system fail.

In the modern cloud-native world, applications need to serve users globally with low latency and high availability. Traditional SQL databases like PostgreSQL or MySQL are great for consistency but struggle to scale horizontally. NoSQL databases like MongoDB scale well but sacrifice ACID transactions. CockroachDB bridges this gap: it's a distributed SQL database that offers full ACID transactions, horizontal scalability, and resilience to failures. Inspired by Google's Spanner, CockroachDB uses a combination of Raft consensus and distributed transactions to provide a familiar SQL interface with PostgreSQL compatibility. In this tutorial, you'll learn how CockroachDB works under the hood, how to set it up, and how to build production-ready applications that require global scale without compromising on consistency.

What is CockroachDB?

CockroachDB is a distributed SQL database built on a transactional and strongly-consistent key-value store. It scales horizontally, survives disk, machine, rack, and even datacenter failures with minimal latency disruption and no manual intervention. CockroachDB is wire-compatible with PostgreSQL, meaning you can use existing PostgreSQL drivers and tools. It supports full SQL, including joins, subqueries, and ACID transactions. The database automatically replicates and rebalances data across nodes, ensuring high availability and consistent performance. CockroachDB is ideal for applications that require global scale, such as SaaS platforms, e-commerce, and financial services.

intro.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- Connect to CockroachDB using PostgreSQL client
-- psql -h localhost -p 26257 -d defaultdb -U root

-- Create a simple table
CREATE TABLE users (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name STRING NOT NULL,
    email STRING UNIQUE,
    created_at TIMESTAMP DEFAULT now()
);

-- Insert data
INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');

-- Query data
SELECT * FROM users;
Output
id | name | email | created_at
----------------------+-------+--------------------+----------------------------
a1b2c3d4-e5f6-... | Alice | alice@example.com | 2025-03-15 10:00:00.000000
(1 row)
🔥PostgreSQL Compatibility
📊 Production Insight
In production, always use connection pooling (e.g., pgBouncer) to manage connections efficiently, as each node can handle many concurrent connections.
🎯 Key Takeaway
CockroachDB is a distributed SQL database that provides ACID transactions and horizontal scalability with PostgreSQL compatibility.

Architecture: How CockroachDB Works

CockroachDB's architecture is based on a sorted key-value store divided into ranges (default 64 MB). Each range is replicated across multiple nodes using the Raft consensus algorithm. Writes go through a Raft leader, ensuring strong consistency. The database automatically splits and merges ranges based on size and load. SQL queries are parsed and optimized into distributed execution plans that operate on ranges in parallel. CockroachDB uses a distributed transaction protocol based on Percolator (Google) to provide serializable isolation. The cluster is managed by a gossip protocol that shares node and range metadata.

architecture.sqlSQL
1
2
3
4
5
6
7
8
-- View cluster ranges
SHOW RANGES FROM TABLE users;

-- View node status
SELECT node_id, address, locality, is_live FROM crdb_internal.gossip_nodes;

-- Check replication factor
SHOW ZONE CONFIGURATION FOR TABLE users;
Output
table_name | start_key | end_key | range_id | replicas | lease_holder
-------------+-----------+---------+----------+----------+--------------
users | NULL | NULL | 25 | {1,2,3} | 1
(1 row)
node_id | address | locality | is_live
---------+---------------+---------------------+---------
1 | localhost:26257| region=us-east | true
2 | localhost:26258| region=us-west | true
3 | localhost:26259| region=eu-west | true
(3 rows)
zone_name | config
-----------+--------
.default | num_replicas = 3
(1 row)
💡Locality and Replication
📊 Production Insight
Monitor range splits and merges. Too many small ranges can cause overhead; too few large ranges can cause hotspots. Use SHOW RANGES to track.
🎯 Key Takeaway
CockroachDB splits data into ranges, replicates them via Raft, and uses distributed transactions for consistency.

Setting Up a CockroachDB Cluster

To set up a CockroachDB cluster, download the binary or use Docker. Start multiple nodes, each with a unique store and address. Use the --join flag to connect nodes. For production, deploy across multiple data centers with locality settings. Enable encryption, authentication, and use secure connections. CockroachDB provides a built-in SQL shell and a web UI for monitoring.

setup.shBASH
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Start first node (insecure mode for demo)
cockroach start --insecure --store=node1 --listen-addr=localhost:26257 --http-addr=localhost:8080 --join=localhost:26257,localhost:26258,localhost:26259

# Start second node
cockroach start --insecure --store=node2 --listen-addr=localhost:26258 --http-addr=localhost:8081 --join=localhost:26257,localhost:26258,localhost:26259

# Start third node
cockroach start --insecure --store=node3 --listen-addr=localhost:26259 --http-addr=localhost:8082 --join=localhost:26257,localhost:26258,localhost:26259

# Initialize the cluster
cockroach init --insecure --host=localhost:26257

# Connect to SQL shell
cockroach sql --insecure --host=localhost:26257
Output
CockroachDB node starting at ...
CockroachDB node starting at ...
CockroachDB node starting at ...
Cluster successfully initialized
#
# Welcome to the CockroachDB SQL shell.
# All statements must be terminated by a semicolon.
#
root@:26257/defaultdb>
⚠ Production Security
📊 Production Insight
In production, use a load balancer (e.g., HAProxy) to distribute connections across nodes. CockroachDB nodes are symmetric, so any node can handle any request.
🎯 Key Takeaway
A CockroachDB cluster requires at least 3 nodes for fault tolerance. Use --join to connect nodes and cockroach init to initialize.

SQL Operations and Transactions

CockroachDB supports standard SQL DDL and DML operations. Transactions are fully ACID with SERIALIZABLE isolation by default. Use BEGIN and COMMIT to group statements. CockroachDB automatically retries transactions that encounter conflicts, but application code should handle retryable errors (code 40001). Use SAVEPOINT for partial rollback. CockroachDB also supports distributed transactions across ranges and even across data centers.

transactions.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
-- Start a transaction
BEGIN;

-- Insert with potential conflict
INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');

-- Update another row
UPDATE accounts SET balance = balance - 100 WHERE user_id = 'some-uuid';

-- Commit
COMMIT;

-- If retryable error occurs (40001), retry the entire transaction
-- Example retry logic in application (pseudo-code):
-- while true:
--     try:
--         BEGIN
--         ...
--         COMMIT
--         break
--     except RetryableError:
--         continue
Output
BEGIN
Time: 0.001s
INSERT 1
Time: 0.002s
UPDATE 1
Time: 0.003s
COMMIT
Time: 0.005s
💡Retry Logic
📊 Production Insight
Avoid long-running transactions as they can hold locks and cause contention. Keep transactions short and use batch operations when possible.
🎯 Key Takeaway
CockroachDB uses SERIALIZABLE isolation by default. Always implement retry logic for transaction conflicts.

Indexing and Performance Tuning

CockroachDB supports secondary indexes, including unique, composite, and partial indexes. Indexes are automatically distributed across nodes. Use EXPLAIN ANALYZE to understand query plans. CockroachDB provides automatic statistics collection for the optimizer. For performance, ensure that queries use indexes effectively. Avoid full table scans on large tables. Use SHOW INDEXES to inspect indexes. CockroachDB also supports hash-sharded indexes to reduce hotspots on sequential keys.

indexes.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
-- Create a secondary index
CREATE INDEX idx_users_email ON users (email);

-- Create a composite index
CREATE INDEX idx_users_name_created ON users (name, created_at);

-- Create a hash-sharded index to avoid hotspots
CREATE INDEX idx_users_id_hash ON users (id) USING HASH WITH BUCKET_COUNT = 8;

-- Explain a query
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'alice@example.com';
Output
tree | field | description
-------+--------------+--------------------------------------------
| distributed | true
| vectorized | true
scan | table | users@idx_users_email
| spans | 1 span
| filter | email = 'alice@example.com'
| rows | 1
(7 rows)
🔥Automatic Statistics
📊 Production Insight
Monitor index usage with crdb_internal.index_usage_statistics. Drop unused indexes to reduce write overhead.
🎯 Key Takeaway
Use indexes to speed up queries. Hash-sharded indexes prevent hotspots on sequential keys. Use EXPLAIN ANALYZE to verify query plans.

Geo-partitioning and Multi-region Deployment

CockroachDB supports geo-partitioning to keep data close to users, reducing latency. You can define zone configurations to control replication and placement. Use ALTER TABLE ... CONFIGURE ZONE to set constraints like num_replicas and constraints. For multi-region deployments, use the REGIONAL BY TABLE or REGIONAL BY ROW features. CockroachDB also supports global tables for low-latency reads across regions.

geo.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
-- Set zone configuration for a table to keep data in us-east
ALTER TABLE users CONFIGURE ZONE USING constraints = '[+region=us-east]';

-- Create a regional by row table (CockroachDB 21.1+)
CREATE TABLE orders (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    region STRING NOT NULL,
    ...
) LOCALITY REGIONAL BY ROW;

-- Set the region for a row
UPDATE orders SET crdb_region = 'us-east' WHERE id = '...';
Output
CONFIGURE ZONE 1
Time: 0.002s
CREATE TABLE
Time: 0.005s
UPDATE 1
Time: 0.003s
⚠ Licensing
📊 Production Insight
Plan your locality hierarchy carefully. Overlapping constraints can cause issues. Test with SHOW ZONE CONFIGURATIONS to verify.
🎯 Key Takeaway
Geo-partitioning allows you to control data placement for low latency and compliance. Use REGIONAL BY ROW for row-level locality.

Monitoring and Maintenance

CockroachDB provides a built-in web UI on port 8080 (by default) for monitoring cluster health, SQL metrics, and node status. Use cockroach node status and cockroach debug zip for diagnostics. Regularly back up your data using BACKUP and RESTORE commands. CockroachDB supports incremental backups and point-in-time recovery. For maintenance, you can decommission nodes gracefully with cockroach node decommission.

maintenance.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
-- Create a full backup
BACKUP DATABASE defaultdb TO 's3://bucket/backup';

-- Restore from backup
RESTORE DATABASE defaultdb FROM 's3://bucket/backup';

-- Decommission a node (run from a different node)
cockroach node decommission 1 --host=localhost:26257

-- Check node status
cockroach node status --host=localhost:26257
Output
BACKUP
Time: 1.234s
RESTORE
Time: 2.345s
id | is_live | ...
-----+---------+-----
1 | false | ...
2 | true | ...
3 | true | ...
(3 rows)
💡Backup Best Practices
📊 Production Insight
Set up alerts for node failures, high latency, and disk space. Use Prometheus and Grafana for advanced monitoring.
🎯 Key Takeaway
Use the web UI and CLI for monitoring. Regular backups and graceful node decommissioning are essential for production.
● Production incidentPOST-MORTEMseverity: high

The Phantom Read That Broke the Bank

Symptom
Users occasionally saw duplicate charges after a node failure.
Assumption
The developer assumed SERIALIZABLE isolation was enough to prevent anomalies.
Root cause
The application used READ COMMITTED isolation, which allowed phantom reads when nodes recovered.
Fix
Changed the transaction isolation level to SERIALIZABLE and added retry logic.
Key lesson
  • Always use SERIALIZABLE isolation for financial transactions.
  • Understand that CockroachDB's default isolation is SERIALIZABLE, but client drivers may default to READ COMMITTED.
  • Implement retry logic for transaction conflicts.
  • Test failure scenarios in a staging environment.
  • Monitor transaction retry rates in production.
Production debug guideSymptom to Action4 entries
Symptom · 01
High latency on reads/writes
Fix
Check network latency between nodes and disk I/O. Use SHOW STATISTICS FOR TABLE to see range distribution.
Symptom · 02
Transaction retry errors
Fix
Examine application retry logic. Use SHOW TRANSACTIONS to see active transactions and their states.
Symptom · 03
Node down or unreachable
Fix
Check node status with cockroach node status. Ensure Raft group quorum is maintained.
Symptom · 04
Data inconsistency
Fix
Run cockroach debug check-table to verify consistency. Check replication factor settings.
★ Quick Debug Cheat SheetCommon CockroachDB issues and immediate actions.
Transaction conflict error
Immediate action
Retry the transaction with exponential backoff.
Commands
SHOW TRANSACTIONS;
SELECT * FROM crdb_internal.cluster_transactions;
Fix now
Implement retry logic in application code.
Slow query+
Immediate action
Check query plan with EXPLAIN.
Commands
EXPLAIN ANALYZE SELECT ...;
SHOW STATISTICS FOR TABLE ...;
Fix now
Add index or adjust query.
Node down+
Immediate action
Check node status and logs.
Commands
cockroach node status --host=<node>
cockroach node ls
Fix now
Restart node or decommission if permanent.
FeatureCockroachDBPostgreSQLMongoDB
ConsistencyStrong (SERIALIZABLE)Strong (configurable)Eventual (default)
ScalabilityHorizontal (auto-sharding)Vertical (read replicas)Horizontal (sharding)
SQL SupportFull SQL (PostgreSQL compatible)Full SQLNo SQL (JSON queries)
TransactionsACID distributedACID single-nodeACID per document
ReplicationRaft consensusStreaming replicationReplica sets
⚙ Quick Reference
7 commands from this guide
FileCommand / CodePurpose
intro.sqlCREATE TABLE users (What is CockroachDB?
architecture.sqlSHOW RANGES FROM TABLE users;Architecture
setup.shcockroach start --insecure --store=node1 --listen-addr=localhost:26257 --http-ad...Setting Up a CockroachDB Cluster
transactions.sqlBEGIN;SQL Operations and Transactions
indexes.sqlCREATE INDEX idx_users_email ON users (email);Indexing and Performance Tuning
geo.sqlALTER TABLE users CONFIGURE ZONE USING constraints = '[+region=us-east]';Geo-partitioning and Multi-region Deployment
maintenance.sqlBACKUP DATABASE defaultdb TO 's3://bucket/backup';Monitoring and Maintenance

Key takeaways

1
CockroachDB provides ACID transactions and horizontal scalability with PostgreSQL compatibility.
2
Always implement retry logic for transaction conflicts.
3
Use hash-sharded indexes to avoid hotspots on sequential keys.
4
Geo-partitioning allows data locality for low latency and compliance.
5
Monitor cluster health and schedule regular backups.

Common mistakes to avoid

3 patterns
×

Not implementing retry logic for transactions.

×

Using READ COMMITTED isolation in production.

×

Creating indexes on sequential keys without hash sharding.

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Explain how CockroachDB achieves horizontal scalability.
Q02JUNIOR
What is the default isolation level in CockroachDB and why is it importa...
Q03SENIOR
How does CockroachDB handle transaction conflicts?
Q01 of 03SENIOR

Explain how CockroachDB achieves horizontal scalability.

ANSWER
CockroachDB automatically splits data into ranges (64 MB each) and distributes them across nodes. Each range is replicated using Raft. The cluster automatically rebalances ranges based on load and size, allowing linear scalability by adding nodes.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
Is CockroachDB compatible with PostgreSQL?
02
How does CockroachDB handle consistency?
03
Can I run CockroachDB on a single machine?
04
What is the difference between CockroachDB and YugabyteDB?
05
How do I handle schema migrations in CockroachDB?
N
Naren Founder & Principal Engineer

20+ years shipping high-throughput database systems. Everything here is grounded in real deployments.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's NoSQL. Mark it forged?

3 min read · try the examples if you haven't

Previous
Snowflake Data Warehouse Architecture
17 / 27 · NoSQL
Next
ClickHouse: Column-Oriented OLAP Database