CockroachDB
Distributed SQL Database
A PostgreSQL-compatible distributed SQL database. It provides automatic sharding, global distribution, and Serializable isolation by default, realizing a "survivable" database.
Distributed SQL Database
A PostgreSQL-compatible distributed SQL database. It provides automatic sharding, global distribution, and Serializable isolation by default, realizing a "survivable" database.
CockroachDB is a distributed SQL database developed with inspiration from Google Spanner. Aiming for the survivability of a "cockroach" as its name suggests, it preserves data and keeps serving through node failures, data center failures, and even region failures.
Automatic sharding and rebalancing: Data is automatically split into units called Ranges and distributed across multiple nodes. When nodes are added or removed, data is rebalanced automatically. Developers do not need to manage sharding themselves.
Strong consistency: CockroachDB provides the Serializable isolation level by default. You get the same ACID guarantees as a single node even in a distributed environment, making it suitable for services where consistency is critical, such as finance and payments.
PostgreSQL compatible: It supports the PostgreSQL wire protocol, so you can use existing PostgreSQL drivers and ORMs (Prisma, Sequelize, TypeORM, etc.) as they are. Migration cost is low.
Multi-region features: It provides geo-distribution features such as pinning data to specific regions (Region Survival), Global Tables for fast reads worldwide, and placing data based on user location.
-- CockroachDB SQL 예제 (PostgreSQL 호환)
-- ============================================
-- 데이터베이스 및 테이블 생성
-- ============================================
CREATE DATABASE ecommerce;
USE ecommerce;
-- 사용자 테이블 (UUID 기본키 권장)
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email STRING UNIQUE NOT NULL,
name STRING NOT NULL,
region STRING DEFAULT 'ap-northeast-2',
created_at TIMESTAMPTZ DEFAULT now()
);
-- 주문 테이블 (해시 샤딩 인덱스)
CREATE TABLE orders (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID REFERENCES users(id),
total_amount DECIMAL(15,2) NOT NULL,
status STRING DEFAULT 'pending',
created_at TIMESTAMPTZ DEFAULT now(),
-- 샤딩 힌트: user_id로 데이터 분산
INDEX orders_by_user (user_id) USING HASH
);
-- ============================================
-- 멀티 리전 설정
-- ============================================
-- 데이터베이스 리전 설정
ALTER DATABASE ecommerce PRIMARY REGION "ap-northeast-2";
ALTER DATABASE ecommerce ADD REGION "us-east-1";
ALTER DATABASE ecommerce ADD REGION "eu-west-1";
-- 리전별 생존 설정 (리전 장애에도 복구)
ALTER DATABASE ecommerce SURVIVE REGION FAILURE;
-- 글로벌 테이블 (전 세계에서 빠른 읽기)
CREATE TABLE config (
key STRING PRIMARY KEY,
value JSONB
) LOCALITY GLOBAL;
-- 리전 고정 테이블 (GDPR 준수 - 유럽 데이터는 유럽에)
CREATE TABLE eu_users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email STRING,
data JSONB
) LOCALITY REGIONAL BY TABLE IN "eu-west-1";
-- ============================================
-- 트랜잭션 (Serializable 기본)
-- ============================================
BEGIN;
-- 계좌 이체 (분산 트랜잭션도 ACID 보장)
UPDATE accounts SET balance = balance - 100
WHERE id = 'acc-001';
UPDATE accounts SET balance = balance + 100
WHERE id = 'acc-002';
-- 이체 기록
INSERT INTO transfers (from_account, to_account, amount)
VALUES ('acc-001', 'acc-002', 100);
COMMIT;
-- ============================================
-- 유용한 시스템 쿼리
-- ============================================
-- 클러스터 노드 상태 확인
SELECT node_id, address, is_live, locality
FROM crdb_internal.gossip_nodes;
-- Range 분포 확인
SELECT * FROM [SHOW RANGES FROM TABLE orders];
-- 실행 계획 (분산 쿼리 확인)
EXPLAIN ANALYZE SELECT * FROM orders
WHERE user_id = 'some-uuid';
-- 느린 쿼리 확인
SELECT * FROM crdb_internal.node_queries
ORDER BY elapsed DESC LIMIT 10;
// CockroachDB + Node.js (pg 드라이버)
const { Pool } = require('pg');
// CockroachDB 연결 (PostgreSQL 호환)
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
// CockroachDB Serverless 연결 시
ssl: {
rejectUnauthorized: true,
},
max: 20, // 커넥션 풀 크기
});
// ============================================
// 기본 CRUD
// ============================================
class OrderService {
// 주문 생성
async createOrder(userId, items) {
const client = await pool.connect();
try {
await client.query('BEGIN');
// 총액 계산
const total = items.reduce((sum, item) =>
sum + item.price * item.quantity, 0);
// 주문 생성
const { rows: [order] } = await client.query(`
INSERT INTO orders (user_id, total_amount, status)
VALUES ($1, $2, 'pending')
RETURNING *
`, [userId, total]);
// 주문 아이템 생성
for (const item of items) {
await client.query(`
INSERT INTO order_items (order_id, product_id, quantity, price)
VALUES ($1, $2, $3, $4)
`, [order.id, item.productId, item.quantity, item.price]);
}
// 재고 차감
for (const item of items) {
const { rowCount } = await client.query(`
UPDATE products
SET stock = stock - $1
WHERE id = $2 AND stock >= $1
`, [item.quantity, item.productId]);
if (rowCount === 0) {
throw new Error(`재고 부족: ${item.productId}`);
}
}
await client.query('COMMIT');
return order;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
// 사용자별 주문 조회
async getOrdersByUser(userId, limit = 10) {
const { rows } = await pool.query(`
SELECT o.*,
json_agg(json_build_object(
'product_id', oi.product_id,
'quantity', oi.quantity,
'price', oi.price
)) as items
FROM orders o
JOIN order_items oi ON o.id = oi.order_id
WHERE o.user_id = $1
GROUP BY o.id
ORDER BY o.created_at DESC
LIMIT $2
`, [userId, limit]);
return rows;
}
}
// ============================================
// 재시도 로직 (분산 DB 필수)
// ============================================
async function executeWithRetry(fn, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
// CockroachDB 직렬화 실패 에러 (40001)
if (error.code === '40001' && attempt < maxRetries) {
console.log(`재시도 ${attempt}/${maxRetries}: 트랜잭션 충돌`);
// 지수 백오프
await new Promise(r => setTimeout(r, 100 * Math.pow(2, attempt)));
continue;
}
throw error;
}
}
}
// 사용 예시
const orderService = new OrderService();
await executeWithRetry(async () => {
return orderService.createOrder('user-123', [
{ productId: 'prod-1', quantity: 2, price: 10000 },
{ productId: 'prod-2', quantity: 1, price: 25000 }
]);
});
// ============================================
// Prisma에서 CockroachDB 사용
// ============================================
// schema.prisma
/*
datasource db {
provider = "cockroachdb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
email String @unique
orders Order[]
}
*/
# CockroachDB CLI 및 운영 명령어
# ============================================
# 설치 및 로컬 실행
# ============================================
# macOS 설치
brew install cockroachdb/tap/cockroach
# 로컬 단일 노드 실행 (개발용)
cockroach start-single-node --insecure --listen-addr=localhost:26257
# SQL 쉘 접속
cockroach sql --insecure --host=localhost:26257
# ============================================
# 클러스터 구성 (프로덕션)
# ============================================
# 노드 1 시작
cockroach start \
--insecure \
--store=node1 \
--listen-addr=localhost:26257 \
--http-addr=localhost:8080 \
--join=localhost:26257,localhost:26258,localhost:26259
# 노드 2 시작
cockroach start \
--insecure \
--store=node2 \
--listen-addr=localhost:26258 \
--http-addr=localhost:8081 \
--join=localhost:26257,localhost:26258,localhost:26259
# 노드 3 시작
cockroach start \
--insecure \
--store=node3 \
--listen-addr=localhost:26259 \
--http-addr=localhost:8082 \
--join=localhost:26257,localhost:26258,localhost:26259
# 클러스터 초기화 (최초 1회)
cockroach init --insecure --host=localhost:26257
# ============================================
# 클러스터 관리
# ============================================
# 클러스터 상태 확인
cockroach node status --insecure --host=localhost:26257
# 노드 decommission (제거)
cockroach node decommission 3 --insecure --host=localhost:26257
# DB Admin UI 접속 (브라우저)
# http://localhost:8080
# ============================================
# 백업 및 복구
# ============================================
# 전체 클러스터 백업 (S3)
BACKUP INTO 's3://bucket/backup?AUTH=implicit'
AS OF SYSTEM TIME '-10s';
# 특정 데이터베이스 백업
BACKUP DATABASE ecommerce INTO 's3://bucket/backup';
# 복구
RESTORE DATABASE ecommerce FROM LATEST IN 's3://bucket/backup';
# Point-in-Time 복구
RESTORE DATABASE ecommerce FROM LATEST IN 's3://bucket/backup'
AS OF SYSTEM TIME '2024-01-15 10:00:00';
# ============================================
# CockroachDB Cloud (서버리스)
# ============================================
# CLI로 클라우드 접속
cockroach sql --url "postgresql://user:password@host:26257/defaultdb?sslmode=verify-full"
# 연결 문자열 예시 (Node.js)
# DATABASE_URL="postgresql://user:pass@free-tier.gcp-asia-southeast1.cockroachlabs.cloud:26257/defaultdb?sslmode=verify-full"
# ============================================
# 성능 진단
# ============================================
# 실행 중인 쿼리 확인
cockroach sql --insecure -e "SELECT * FROM [SHOW QUERIES]"
# 세션 확인
cockroach sql --insecure -e "SELECT * FROM [SHOW SESSIONS]"
# 통계 수집
cockroach sql --insecure -e "ANALYZE orders"
"We're a global service, so multi-region is a must. With CockroachDB you keep using PostgreSQL syntax and still get automatic sharding and region survival. I'm worried about vendor lock-in with Spanner, but CockroachDB also has an open-source core."
"Moving from PostgreSQL to CockroachDB is easier than you'd think. Extract the schema with pg_dump and load it with IMPORT. But I recommend using UUIDs instead of sequences, and some PostgreSQL-specific features may not be compatible, so check in advance."
"One node died but the service is fine. CockroachDB automatically elected a leader on another node and rerouted traffic. However, that node's data is now under-replicated, so we need to recover it quickly or add a new node."
UUIDs are recommended instead of AUTO_INCREMENT or SERIAL. Sequential IDs cause hotspots, concentrating writes on specific nodes.
Because of Serializable isolation, transaction conflicts (error 40001) can occur. You must implement retry logic in the application.
In a multi-region environment, queries across regions incur network latency. Use REGIONAL BY ROW to optimize data locality.
Use UUID primary keys, prevent hotspots with hash indexes, implement retry logic, place data close to the region, and run ANALYZE regularly.