Convert Figma logo to code with AI

cockroachdb logocockroach

CockroachDB — the cloud native, distributed SQL database designed for high availability, effortless scale, and control over data placement.

30,019
3,793
30,019
6,513

Top Related Projects

37,055

TiDB is an open-source, cloud-native, distributed, MySQL-Compatible database for elastic scale and real-time analytics. Try AI-powered Chat2Query free at : https://www.pingcap.com/tidb-serverless/

47,616

Distributed reliable key-value store for the most critical data of a distributed system

18,518

Vitess is a database clustering system for horizontal scaling of MySQL.

YugabyteDB - the cloud native distributed SQL database for mission-critical applications.

Apache Cassandra®

Quick Overview

CockroachDB is an open-source, distributed SQL database designed for scalability, consistency, and survivability. It aims to provide the benefits of both traditional relational databases and modern NoSQL systems, offering strong consistency, distributed transactions, and horizontal scalability.

Pros

  • Highly scalable and resilient, with automatic sharding and replication
  • ACID-compliant with distributed transactions
  • Compatible with PostgreSQL wire protocol and drivers
  • Cloud-native architecture, suitable for containerized environments

Cons

  • Higher latency compared to single-node databases
  • Resource-intensive, requiring more hardware for optimal performance
  • Steeper learning curve for advanced features and tuning
  • Limited support for certain PostgreSQL extensions and features

Code Examples

  1. Connecting to CockroachDB using the Go driver:
import (
    "database/sql"
    _ "github.com/lib/pq"
)

db, err := sql.Open("postgres", "postgresql://root@localhost:26257/defaultdb?sslmode=disable")
if err != nil {
    log.Fatal(err)
}
defer db.Close()
  1. Executing a simple query:
rows, err := db.Query("SELECT id, name FROM users WHERE active = true")
if err != nil {
    log.Fatal(err)
}
defer rows.Close()

for rows.Next() {
    var id int
    var name string
    if err := rows.Scan(&id, &name); err != nil {
        log.Fatal(err)
    }
    fmt.Printf("User %d: %s\n", id, name)
}
  1. Performing a distributed transaction:
tx, err := db.Begin()
if err != nil {
    log.Fatal(err)
}

_, err = tx.Exec("UPDATE accounts SET balance = balance - $1 WHERE id = $2", 100, 1)
if err != nil {
    tx.Rollback()
    log.Fatal(err)
}

_, err = tx.Exec("UPDATE accounts SET balance = balance + $1 WHERE id = $2", 100, 2)
if err != nil {
    tx.Rollback()
    log.Fatal(err)
}

if err := tx.Commit(); err != nil {
    log.Fatal(err)
}

Getting Started

  1. Install CockroachDB:

    brew install cockroachdb/tap/cockroach
    
  2. Start a local cluster:

    cockroach start-single-node --insecure
    
  3. Connect to the cluster:

    cockroach sql --insecure
    
  4. Create a database and table:

    CREATE DATABASE mydb;
    USE mydb;
    CREATE TABLE users (id SERIAL PRIMARY KEY, name STRING, active BOOL);
    
  5. Insert and query data:

    INSERT INTO users (name, active) VALUES ('Alice', true), ('Bob', false);
    SELECT * FROM users WHERE active = true;
    

Competitor Comparisons

37,055

TiDB is an open-source, cloud-native, distributed, MySQL-Compatible database for elastic scale and real-time analytics. Try AI-powered Chat2Query free at : https://www.pingcap.com/tidb-serverless/

Pros of TiDB

  • Better support for MySQL compatibility, making migration easier
  • Stronger focus on HTAP (Hybrid Transactional/Analytical Processing) workloads
  • More flexible scaling options, including scaling storage and compute independently

Cons of TiDB

  • Less mature distributed SQL implementation compared to CockroachDB
  • Potentially higher operational complexity due to more components
  • Smaller community and ecosystem compared to CockroachDB

Code Comparison

TiDB (SQL syntax):

CREATE TABLE users (
  id INT PRIMARY KEY,
  name VARCHAR(255),
  created_at TIMESTAMP
);

CockroachDB (SQL syntax):

CREATE TABLE users (
  id INT PRIMARY KEY,
  name STRING,
  created_at TIMESTAMP
);

Both databases use similar SQL syntax, with minor differences in data type naming conventions. TiDB aims for MySQL compatibility, while CockroachDB follows PostgreSQL conventions more closely.

TiDB and CockroachDB are both distributed SQL databases designed for scalability and resilience. TiDB offers better MySQL compatibility and HTAP capabilities, while CockroachDB provides a more mature distributed SQL implementation with a larger ecosystem. The choice between them depends on specific use cases, existing infrastructure, and required features.

47,616

Distributed reliable key-value store for the most critical data of a distributed system

Pros of etcd

  • Lightweight and focused on distributed key-value storage
  • Simpler to set up and maintain for basic distributed systems
  • Lower resource requirements, suitable for smaller-scale deployments

Cons of etcd

  • Limited scalability compared to CockroachDB's distributed SQL capabilities
  • Lacks advanced querying and transactional features
  • Not designed for handling large volumes of structured data

Code Comparison

etcd (Go):

cli, _ := clientv3.New(clientv3.Config{Endpoints: []string{"localhost:2379"}})
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
_, err := cli.Put(ctx, "key", "value")
cancel()

CockroachDB (SQL):

CREATE TABLE users (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name STRING);
INSERT INTO users (name) VALUES ('Alice');
SELECT * FROM users WHERE name = 'Alice';

etcd focuses on simple key-value operations, while CockroachDB provides full SQL functionality with distributed capabilities. etcd is better suited for configuration management and service discovery, whereas CockroachDB excels in scenarios requiring complex queries and transactions across distributed data.

18,518

Vitess is a database clustering system for horizontal scaling of MySQL.

Pros of Vitess

  • Better suited for scaling existing MySQL deployments
  • Provides advanced sharding capabilities out of the box
  • Lighter weight and easier to set up for MySQL users

Cons of Vitess

  • Limited to MySQL compatibility, less flexible than CockroachDB
  • Requires more manual configuration for complex sharding scenarios
  • Less built-in support for global, multi-region deployments

Code Comparison

Vitess (Go):

func (tsv *TabletServer) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (int64, error) {
    span, ctx := trace.NewSpan(ctx, "TabletServer.Begin")
    defer span.Finish()
    return tsv.begin(ctx, target, options)
}

CockroachDB (Go):

func (s *Session) Begin(ctx context.Context) error {
    s.mu.Lock()
    defer s.mu.Unlock()
    if s.mu.txn != nil {
        return errors.New("session already has an active transaction")
    }
    s.mu.txn = s.executor.cfg.DB.NewTxn(ctx, s.DefaultTxnPriority)
    return nil
}

Both projects use Go and implement transaction handling, but Vitess focuses on MySQL-compatible operations while CockroachDB implements its own distributed SQL engine.

YugabyteDB - the cloud native distributed SQL database for mission-critical applications.

Pros of YugabyteDB

  • Better support for ACID transactions across multiple nodes
  • More flexible deployment options, including multi-cloud and hybrid-cloud setups
  • Stronger compatibility with PostgreSQL, making migration easier for existing PostgreSQL users

Cons of YugabyteDB

  • Less mature ecosystem and community compared to CockroachDB
  • Potentially higher resource consumption in certain workloads
  • Steeper learning curve for administrators unfamiliar with distributed databases

Code Comparison

YugabyteDB:

CREATE TABLE users (
  id INT PRIMARY KEY,
  name TEXT,
  email TEXT
) SPLIT INTO 5 TABLETS;

CockroachDB:

CREATE TABLE users (
  id INT PRIMARY KEY,
  name STRING,
  email STRING
) PARTITION BY RANGE (id) (
  PARTITION p0 VALUES FROM (MINVALUE) TO (1000),
  PARTITION p1 VALUES FROM (1000) TO (MAXVALUE)
);

Both databases use SQL-like syntax for table creation, but YugabyteDB uses the SPLIT INTO clause for data distribution, while CockroachDB uses PARTITION BY for similar functionality. YugabyteDB's approach is simpler, while CockroachDB offers more granular control over data partitioning.

Apache Cassandra®

Pros of Cassandra

  • Highly scalable and designed for massive distributed deployments
  • Excellent write performance and throughput
  • Flexible data model with support for wide rows and dynamic columns

Cons of Cassandra

  • Eventual consistency model can be challenging for some use cases
  • Less intuitive query language (CQL) compared to SQL
  • Limited support for complex joins and transactions

Code Comparison

Cassandra query example:

SELECT * FROM users
WHERE user_id = 123
AND timestamp > '2023-01-01'
LIMIT 10;

CockroachDB query example:

SELECT * FROM users
WHERE user_id = 123
AND timestamp > '2023-01-01'
LIMIT 10;

Both databases use SQL-like syntax, but Cassandra's CQL has some limitations compared to CockroachDB's more comprehensive SQL support. CockroachDB offers better support for complex queries, joins, and transactions, while Cassandra focuses on high-performance, wide-column data storage and retrieval.

CockroachDB provides a more familiar SQL experience and stronger consistency guarantees, making it easier to migrate from traditional relational databases. Cassandra, on the other hand, excels in scenarios requiring extreme scalability and write performance, particularly for time-series data and large-scale distributed systems.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README


CockroachDB is a cloud-native distributed SQL database designed to build, scale, and manage modern, data-intensive applications.

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; supports strongly-consistent ACID transactions; and provides a familiar SQL API for structuring, manipulating, and querying data.

For more details, see our FAQ or architecture document.

Docs

For guidance on installation, development, deployment, and administration, see our User Documentation.

Starting with CockroachCloud

We can run CockroachDB for you, so you don't have to run your own cluster.

See our online documentation: Quickstart with CockroachCloud

Starting with CockroachDB

  1. Install CockroachDB: using a pre-built executable or build it from source.
  2. Start a local cluster and connect to it via the built-in SQL client.
  3. Learn more about CockroachDB SQL.
  4. Use a PostgreSQL-compatible driver or ORM to build an app with CockroachDB.
  5. Explore core features, such as data replication, automatic rebalancing, and fault tolerance and recovery.

Client Drivers

CockroachDB supports the PostgreSQL wire protocol, so you can use any available PostgreSQL client drivers to connect from various languages.

Deployment

  • CockroachCloud - Steps to create a free CockroachCloud cluster on your preferred Cloud platform.
  • Manual - Steps to deploy a CockroachDB cluster manually on multiple machines.
  • Cloud - Guides for deploying CockroachDB on various cloud platforms.
  • Orchestration - Guides for running CockroachDB with popular open-source orchestration systems.

Need Help?

Building from source

See our wiki for more details.

Contributing

We welcome your contributions! If you're looking for issues to work on, try looking at the good first issue list. We do our best to tag issues suitable for new external contributors with that label, so it's a great way to find something you can help with!

See our wiki for more details.

Engineering discussions take place on our public mailing list, cockroach-db@googlegroups.com. Also please join our Community Slack (there's a dedicated #contributors channel!) to ask questions, discuss your ideas, and connect with other contributors.

Design

For an in-depth discussion of the CockroachDB architecture, see our Architecture Guide. For the original design motivation, see our design doc.

Licensing

Current CockroachDB code is released under a combination of two licenses, the Business Source License (BSL) and the Cockroach Community License (CCL).

When contributing to a CockroachDB feature, you can find the relevant license in the comments at the top of each file.

For more information, see the Licensing FAQs.

Comparison with Other Databases

To see how key features of CockroachDB stack up against other databases, check out CockroachDB in Comparison.

See Also