# CockroachDB Cluster

> CockroachDB distributed SQL database cluster.

- Category: Database Stacks
- Difficulty: advanced
- Components: cockroachdb, haproxy
- Tags: cockroachdb, distributed, sql, cluster
- Source: https://docker.recipes/databases/cockroachdb-cluster

## Overview

CockroachDB is a distributed SQL database designed to survive data center failures while maintaining ACID guarantees and horizontal scalability. Developed by Cockroach Labs and built on Google's Spanner paper, it combines the familiar SQL interface with automatic sharding, replication, and fault tolerance. The database uses a multi-version concurrency control system and implements the Raft consensus algorithm to ensure data consistency across nodes.

This deployment creates a three-node CockroachDB cluster with HAProxy as the load balancer and connection multiplexer. The HAProxy instance distributes SQL connections across all healthy CockroachDB nodes while providing a single endpoint for applications. Each CockroachDB node automatically replicates data using a default replication factor of 3, ensuring that the cluster can survive the loss of any single node without data loss or service interruption.

This configuration targets organizations requiring a PostgreSQL-compatible database with built-in horizontal scaling and high availability. Ideal for teams transitioning from traditional SQL databases who need geographic distribution, automatic failover, and the ability to scale beyond single-machine limitations without application rewrites.

## Features

- Multi-active cluster with automatic leader election using Raft consensus
- PostgreSQL wire protocol compatibility for existing application integration
- Automatic range-based sharding with configurable replication zones
- Distributed ACID transactions with serializable snapshot isolation
- Built-in SQL optimizer with cost-based query planning
- HAProxy TCP load balancing with health checks for connection distribution
- Gossip protocol for cluster membership and metadata synchronization
- Time-travel queries and point-in-time recovery capabilities

## Use cases

- Multi-region financial applications requiring strong consistency guarantees
- E-commerce platforms needing automatic scaling during traffic spikes
- SaaS applications with tenant data isolation and geographic distribution
- Gaming backends requiring low-latency writes with global read replicas
- IoT data collection systems processing high-volume time-series data
- Microservices architectures needing distributed transaction coordination
- Disaster recovery setups with automated cross-datacenter replication

## Prerequisites

- Minimum 2GB RAM per CockroachDB node (6GB total for cluster)
- Available ports 26257 (SQL) and 8080 (Admin UI) on Docker host
- HAProxy configuration file (haproxy.cfg) with CockroachDB backend definitions
- Understanding of distributed systems concepts and CAP theorem tradeoffs
- Familiarity with PostgreSQL syntax and connection parameters
- Network connectivity between nodes for gossip protocol communication

## docker-compose.yml

```yaml
services:
  roach-1:
    image: cockroachdb/cockroach:latest
    container_name: roach-1
    restart: unless-stopped
    command: start --insecure --join=roach-1,roach-2,roach-3
    volumes:
      - roach1_data:/cockroach/cockroach-data

  roach-2:
    image: cockroachdb/cockroach:latest
    container_name: roach-2
    restart: unless-stopped
    command: start --insecure --join=roach-1,roach-2,roach-3
    volumes:
      - roach2_data:/cockroach/cockroach-data

  roach-3:
    image: cockroachdb/cockroach:latest
    container_name: roach-3
    restart: unless-stopped
    command: start --insecure --join=roach-1,roach-2,roach-3
    volumes:
      - roach3_data:/cockroach/cockroach-data

  roach-init:
    image: cockroachdb/cockroach:latest
    container_name: roach-init
    command: init --insecure --host=roach-1
    depends_on:
      - roach-1
      - roach-2
      - roach-3

  haproxy:
    image: haproxy:lts-alpine
    container_name: roach-haproxy
    restart: unless-stopped
    ports:
      - "${SQL_PORT:-26257}:26257"
      - "${UI_PORT:-8080}:8080"
    volumes:
      - ./haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
    depends_on:
      - roach-1
      - roach-2
      - roach-3

volumes:
  roach1_data:
  roach2_data:
  roach3_data:
```

## .env

```bash
# CockroachDB
SQL_PORT=26257
UI_PORT=8080
```

## Usage notes

- CockroachDB UI at http://localhost:8080
- SQL at localhost:26257
- PostgreSQL wire protocol
- Automatic replication

## Troubleshooting

- Clock synchronization failed: Ensure Docker host system time is synchronized via NTP
- Node won't join cluster: Verify --join parameter includes all node names exactly as defined
- Connection refused on port 26257: Check if roach-init container completed cluster initialization
- Range unavailable errors: Wait for cluster to achieve quorum, may take 2-3 minutes after startup
- HAProxy 503 errors: Verify CockroachDB nodes are healthy using admin UI health endpoints
- Persistent volume mounting issues: Ensure Docker daemon has sufficient permissions for volume creation

