🗄️ Databases

Cassandra

Apache Cassandra

Apache Cassandra is a distributed NoSQL database that provides high availability and linear scalability. Developed at Facebook and donated to the Apache Foundation, it is optimized for large-scale time series data, IoT, and log storage.

📖 Detailed Explanation

Distributed Architecture: Cassandra operates in a peer-to-peer fashion in which all nodes are equal, with no master-slave structure. It distributes data in a ring structure and allocates data based on the partition key through Consistent Hashing. Because there is no single point of failure (SPOF), it ensures high availability.

Data Model: It uses the Wide Column Store model. Data is stored in a Keyspace > Table > Partition > Row > Column structure. The partition key is the core of data distribution, and the clustering key defines the sort order within a partition. You can query it in a way similar to SQL using CQL (Cassandra Query Language).

Consistency Levels: It supports Tunable Consistency. Various consistency levels such as ONE, QUORUM, and ALL can be set per query, so you can adjust the trade-off between consistency and availability. Writes are fast, and eventual consistency is ensured through Read Repair, which compares replicas during reads.

Replication and Fault Tolerance: Data is replicated across multiple nodes by setting the Replication Factor. NetworkTopologyStrategy lets you set a different replication strategy for each data center, which is effective for cross-region disaster recovery (DR). Hinted Handoff prevents data loss even during temporary failures.

Major Use Cases: It is suitable for large-scale write workloads such as Netflix (streaming metadata), Apple (clusters of 100,000+ nodes), Instagram (message storage), Discord (chat messages), IoT sensor data, time-series analysis, and log storage.

💻 Code Example

# Cassandra Python 예제 - cassandra-driver
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra.policies import DCAwareRoundRobinPolicy
from cassandra.query import SimpleStatement, ConsistencyLevel
from datetime import datetime
import uuid

class CassandraService:
    """Cassandra 데이터베이스 서비스"""

    def __init__(self, contact_points: list, keyspace: str):
        # 인증 설정 (선택적)
        auth_provider = PlainTextAuthProvider(
            username='cassandra',
            password='cassandra'
        )

        # 클러스터 연결 (로드 밸런싱 정책 포함)
        self.cluster = Cluster(
            contact_points=contact_points,
            auth_provider=auth_provider,
            load_balancing_policy=DCAwareRoundRobinPolicy(local_dc='datacenter1')
        )
        self.session = self.cluster.connect(keyspace)

    def create_schema(self):
        """키스페이스 및 테이블 생성"""
        # 키스페이스 생성 (복제 계수 3)
        self.session.execute("""
            CREATE KEYSPACE IF NOT EXISTS iot_data
            WITH replication = {
                'class': 'NetworkTopologyStrategy',
                'datacenter1': 3
            }
        """)

        # 시계열 테이블 생성 (파티션 키 + 클러스터링 키)
        self.session.execute("""
            CREATE TABLE IF NOT EXISTS iot_data.sensor_readings (
                device_id UUID,
                reading_date DATE,
                reading_time TIMESTAMP,
                temperature FLOAT,
                humidity FLOAT,
                PRIMARY KEY ((device_id, reading_date), reading_time)
            ) WITH CLUSTERING ORDER BY (reading_time DESC)
        """)
        print("스키마 생성 완료")

    def insert_sensor_data(self, device_id: uuid.UUID, temp: float, humidity: float):
        """센서 데이터 삽입 (배치 처리)"""
        now = datetime.now()

        # Prepared Statement 사용 (성능 향상)
        insert_stmt = self.session.prepare("""
            INSERT INTO sensor_readings
            (device_id, reading_date, reading_time, temperature, humidity)
            VALUES (?, ?, ?, ?, ?)
        """)

        # 일관성 레벨 설정
        bound_stmt = insert_stmt.bind([
            device_id,
            now.date(),
            now,
            temp,
            humidity
        ])
        bound_stmt.consistency_level = ConsistencyLevel.QUORUM

        self.session.execute(bound_stmt)
        print(f"데이터 삽입: device={device_id}, temp={temp}")

    def get_recent_readings(self, device_id: uuid.UUID, date, limit: int = 100):
        """최근 센서 데이터 조회"""
        query = SimpleStatement(
            """
            SELECT reading_time, temperature, humidity
            FROM sensor_readings
            WHERE device_id = %s AND reading_date = %s
            LIMIT %s
            """,
            consistency_level=ConsistencyLevel.LOCAL_QUORUM
        )

        rows = self.session.execute(query, [device_id, date, limit])
        return list(rows)

    def batch_insert(self, readings: list):
        """배치 삽입 (대량 데이터)"""
        from cassandra.query import BatchStatement, BatchType

        batch = BatchStatement(batch_type=BatchType.UNLOGGED)
        insert_stmt = self.session.prepare("""
            INSERT INTO sensor_readings
            (device_id, reading_date, reading_time, temperature, humidity)
            VALUES (?, ?, ?, ?, ?)
        """)

        for reading in readings:
            batch.add(insert_stmt, reading)

        self.session.execute(batch)
        print(f"{len(readings)}건 배치 삽입 완료")

    def close(self):
        """연결 종료"""
        self.cluster.shutdown()


# 사용 예시
if __name__ == "__main__":
    # 클러스터 연결
    cassandra = CassandraService(
        contact_points=['127.0.0.1', '127.0.0.2', '127.0.0.3'],
        keyspace='iot_data'
    )

    # 스키마 생성
    cassandra.create_schema()

    # 데이터 삽입
    device_id = uuid.uuid4()
    cassandra.insert_sensor_data(device_id, 25.5, 60.0)

    # 데이터 조회
    from datetime import date
    readings = cassandra.get_recent_readings(device_id, date.today())
    for row in readings:
        print(f"시간: {row.reading_time}, 온도: {row.temperature}°C")

    cassandra.close()
// Cassandra Node.js 예제 - cassandra-driver
const cassandra = require('cassandra-driver');

class CassandraService {
    constructor(contactPoints, keyspace) {
        // 클러스터 연결
        this.client = new cassandra.Client({
            contactPoints: contactPoints,
            localDataCenter: 'datacenter1',
            keyspace: keyspace,
            credentials: {
                username: 'cassandra',
                password: 'cassandra'
            },
            pooling: {
                coreConnectionsPerHost: {
                    [cassandra.types.distance.local]: 2,
                    [cassandra.types.distance.remote]: 1
                }
            }
        });
    }

    async connect() {
        await this.client.connect();
        console.log('Cassandra 연결 성공');
    }

    async createSchema() {
        // 키스페이스 생성
        await this.client.execute(`
            CREATE KEYSPACE IF NOT EXISTS iot_data
            WITH replication = {
                'class': 'NetworkTopologyStrategy',
                'datacenter1': 3
            }
        `);

        // 테이블 생성
        await this.client.execute(`
            CREATE TABLE IF NOT EXISTS iot_data.sensor_readings (
                device_id UUID,
                reading_date DATE,
                reading_time TIMESTAMP,
                temperature FLOAT,
                humidity FLOAT,
                PRIMARY KEY ((device_id, reading_date), reading_time)
            ) WITH CLUSTERING ORDER BY (reading_time DESC)
        `);

        console.log('스키마 생성 완료');
    }

    async insertSensorData(deviceId, temperature, humidity) {
        const query = `
            INSERT INTO sensor_readings
            (device_id, reading_date, reading_time, temperature, humidity)
            VALUES (?, ?, ?, ?, ?)
        `;

        const now = new Date();
        const params = [
            deviceId,
            cassandra.types.LocalDate.fromDate(now),
            now,
            temperature,
            humidity
        ];

        // Prepared Statement + 일관성 레벨
        await this.client.execute(query, params, {
            prepare: true,
            consistency: cassandra.types.consistencies.quorum
        });

        console.log(`데이터 삽입: device=${deviceId}, temp=${temperature}`);
    }

    async getRecentReadings(deviceId, date, limit = 100) {
        const query = `
            SELECT reading_time, temperature, humidity
            FROM sensor_readings
            WHERE device_id = ? AND reading_date = ?
            LIMIT ?
        `;

        const result = await this.client.execute(query, [deviceId, date, limit], {
            prepare: true,
            consistency: cassandra.types.consistencies.localQuorum
        });

        return result.rows;
    }

    async batchInsert(readings) {
        // 배치 쿼리 생성
        const queries = readings.map(reading => ({
            query: `
                INSERT INTO sensor_readings
                (device_id, reading_date, reading_time, temperature, humidity)
                VALUES (?, ?, ?, ?, ?)
            `,
            params: reading
        }));

        await this.client.batch(queries, { prepare: true });
        console.log(`${readings.length}건 배치 삽입 완료`);
    }

    async streamLargeData(deviceId, date) {
        // 대용량 데이터 스트리밍
        const query = `
            SELECT * FROM sensor_readings
            WHERE device_id = ? AND reading_date = ?
        `;

        return this.client.stream(query, [deviceId, date], {
            prepare: true,
            fetchSize: 1000
        });
    }

    async shutdown() {
        await this.client.shutdown();
        console.log('연결 종료');
    }
}

// 사용 예시
async function main() {
    const service = new CassandraService(
        ['127.0.0.1', '127.0.0.2'],
        'iot_data'
    );

    await service.connect();
    await service.createSchema();

    // 데이터 삽입
    const deviceId = cassandra.types.Uuid.random();
    await service.insertSensorData(deviceId, 25.5, 60.0);

    // 데이터 조회
    const today = cassandra.types.LocalDate.now();
    const readings = await service.getRecentReadings(deviceId, today);
    readings.forEach(row => {
        console.log(`시간: ${row.reading_time}, 온도: ${row.temperature}°C`);
    });

    // 스트리밍 조회 (대용량)
    const stream = await service.streamLargeData(deviceId, today);
    stream.on('readable', function() {
        let row;
        while ((row = this.read()) !== null) {
            console.log('스트림:', row.temperature);
        }
    });

    await service.shutdown();
}

main().catch(console.error);
-- Cassandra CQL 예제

-- ============================================
-- 1. 키스페이스 생성 (복제 전략 설정)
-- ============================================
-- 단일 데이터센터
CREATE KEYSPACE IF NOT EXISTS my_app
WITH replication = {
    'class': 'SimpleStrategy',
    'replication_factor': 3
};

-- 멀티 데이터센터 (운영 환경 권장)
CREATE KEYSPACE IF NOT EXISTS production_app
WITH replication = {
    'class': 'NetworkTopologyStrategy',
    'dc-east': 3,
    'dc-west': 3
};

USE my_app;


-- ============================================
-- 2. 테이블 설계 (파티션 키가 핵심!)
-- ============================================
-- 시계열 데이터 테이블
-- 파티션 키: (user_id, event_date) - 하루 단위로 파티션
-- 클러스터링 키: event_time - 시간순 정렬
CREATE TABLE user_events (
    user_id UUID,
    event_date DATE,
    event_time TIMESTAMP,
    event_type TEXT,
    event_data MAP,
    PRIMARY KEY ((user_id, event_date), event_time)
) WITH CLUSTERING ORDER BY (event_time DESC)
  AND compaction = {'class': 'TimeWindowCompactionStrategy',
                    'compaction_window_unit': 'DAYS',
                    'compaction_window_size': 1};

-- 채팅 메시지 테이블 (Discord 패턴)
CREATE TABLE messages (
    channel_id UUID,
    bucket INT,  -- 버킷팅으로 파티션 크기 제한
    message_id TIMEUUID,
    author_id UUID,
    content TEXT,
    PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);


-- ============================================
-- 3. 데이터 삽입
-- ============================================
INSERT INTO user_events (user_id, event_date, event_time, event_type, event_data)
VALUES (
    uuid(),
    '2024-01-15',
    toTimestamp(now()),
    'page_view',
    {'page': '/home', 'duration': '30s'}
);

-- TTL 설정 (30일 후 자동 삭제)
INSERT INTO user_events (user_id, event_date, event_time, event_type, event_data)
VALUES (uuid(), '2024-01-15', toTimestamp(now()), 'click', {'button': 'signup'})
USING TTL 2592000;


-- ============================================
-- 4. 데이터 조회 (파티션 키 필수!)
-- ============================================
-- 특정 사용자의 특정 날짜 이벤트 조회
SELECT * FROM user_events
WHERE user_id = 123e4567-e89b-12d3-a456-426614174000
  AND event_date = '2024-01-15'
LIMIT 100;

-- 시간 범위 조회
SELECT * FROM user_events
WHERE user_id = 123e4567-e89b-12d3-a456-426614174000
  AND event_date = '2024-01-15'
  AND event_time >= '2024-01-15 09:00:00'
  AND event_time < '2024-01-15 18:00:00';

-- 특정 이벤트 타입 필터링 (ALLOW FILTERING 주의!)
SELECT * FROM user_events
WHERE user_id = 123e4567-e89b-12d3-a456-426614174000
  AND event_date = '2024-01-15'
  AND event_type = 'click'
ALLOW FILTERING;  -- 대용량에서는 피해야 함


-- ============================================
-- 5. 인덱스 (신중하게 사용)
-- ============================================
-- Secondary Index (카디널리티 낮은 컬럼에만)
CREATE INDEX ON user_events (event_type);

-- SASI Index (텍스트 검색)
CREATE CUSTOM INDEX ON user_events (content)
USING 'org.apache.cassandra.index.sasi.SASIIndex'
WITH OPTIONS = {'mode': 'CONTAINS'};


-- ============================================
-- 6. 배치 작업 (같은 파티션에서만!)
-- ============================================
BEGIN BATCH
    INSERT INTO user_events (user_id, event_date, event_time, event_type)
    VALUES (123e4567-e89b-12d3-a456-426614174000, '2024-01-15', toTimestamp(now()), 'view');

    INSERT INTO user_events (user_id, event_date, event_time, event_type)
    VALUES (123e4567-e89b-12d3-a456-426614174000, '2024-01-15', toTimestamp(now()), 'click');
APPLY BATCH;


-- ============================================
-- 7. 운영 명령어
-- ============================================
-- 테이블 통계
DESCRIBE TABLE user_events;

-- 파티션 크기 확인 (nodetool)
-- nodetool tablehistograms my_app user_events

-- 압축 상태 확인
-- nodetool compactionstats

-- 복구 실행
-- nodetool repair my_app user_events

🗣️ Say It Like This in Practice

💬 In a Database Selection Discussion
"We need to store tens of thousands of IoT sensor data records per second, so Cassandra seems like a good fit. It has excellent write performance and is optimized for time-series data. If we design the partition key as a combination of device_id and date, the data will be distributed evenly."
💬 In a Performance Tuning Meeting
"ALLOW FILTERING queries are being used far too often. In Cassandra, querying without a partition key scans the entire cluster. We should create separate tables that match the query patterns, or consider Materialized Views."
💬 In an incident response meeting
"1 of our 3 nodes went down, but the service is running normally. Cassandra is set to a replication factor of 3 and QUORUM consistency, so only 2 nodes need to respond. However, if it stays down for a long time, we need to run nodetool repair to bring data consistency back in line."

⚠️ Cautions & Best Practices

❌
Preventing Partition Hotspots

If data is concentrated on a single partition key, only certain nodes get overloaded. Use a composite partition key (e.g., user_id + date) or bucketing to distribute data evenly.

❌
Do Not Overuse ALLOW FILTERING

Queries without a partition key trigger a full scan. Design a separate table for each query pattern. "The query determines the data model" is the Cassandra philosophy.

❌
Large Partition Limits

Design partitions so they do not exceed 100MB or 100,000 rows. Split time-series data into partitions by time unit, and apply bucketing to data such as messages.

✅
Best Practices

Use Prepared Statements, clean up data with appropriate TTL settings, run nodetool repair regularly, and improve read performance with LeveledCompactionStrategy.

🔗 Related Terms

📚 Learn More