CockroachDB: Distributed SQL for Global Scale
Learn CockroachDB, a distributed SQL database that combines ACID transactions with horizontal scalability.
20+ years shipping high-throughput database systems. Everything here is grounded in real deployments.
- ✓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.
- 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.
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.
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.
SHOW RANGES to track.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.
--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.
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.
crdb_internal.index_usage_statistics. Drop unused indexes to reduce write overhead.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.
SHOW ZONE CONFIGURATIONS to verify.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.
The Phantom Read That Broke the Bank
- 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.
SHOW STATISTICS FOR TABLE to see range distribution.SHOW TRANSACTIONS to see active transactions and their states.cockroach node status. Ensure Raft group quorum is maintained.cockroach debug check-table to verify consistency. Check replication factor settings.SHOW TRANSACTIONS;SELECT * FROM crdb_internal.cluster_transactions;| File | Command / Code | Purpose |
|---|---|---|
| intro.sql | CREATE TABLE users ( | What is CockroachDB? |
| architecture.sql | SHOW RANGES FROM TABLE users; | Architecture |
| setup.sh | cockroach start --insecure --store=node1 --listen-addr=localhost:26257 --http-ad... | Setting Up a CockroachDB Cluster |
| transactions.sql | BEGIN; | SQL Operations and Transactions |
| indexes.sql | CREATE INDEX idx_users_email ON users (email); | Indexing and Performance Tuning |
| geo.sql | ALTER TABLE users CONFIGURE ZONE USING constraints = '[+region=us-east]'; | Geo-partitioning and Multi-region Deployment |
| maintenance.sql | BACKUP DATABASE defaultdb TO 's3://bucket/backup'; | Monitoring and Maintenance |
Key takeaways
Common mistakes to avoid
3 patternsNot implementing retry logic for transactions.
Using READ COMMITTED isolation in production.
Creating indexes on sequential keys without hash sharding.
Interview Questions on This Topic
Explain how CockroachDB achieves horizontal scalability.
Frequently Asked Questions
20+ years shipping high-throughput database systems. Everything here is grounded in real deployments.
That's NoSQL. Mark it forged?
3 min read · try the examples if you haven't