🗄️ Databases

Debezium

Change Data Capture Platform

An open-source CDC (Change Data Capture) platform. Built on Kafka Connect, it streams database changes in real time to implement data synchronization between microservices, cache invalidation, and search index updates.

📖 Detailed Explanation

Debezium is a CDC platform that reads a database's change logs (WAL, binlog, etc.) and streams change events to Kafka topics. An open-source project led by Red Hat, it enables row-level change capture without query-based polling.

How it works: It reads the database's transaction log directly (PostgreSQL's WAL, MySQL's binlog, MongoDB's oplog) to detect INSERT, UPDATE, and DELETE events. It captures changes with millisecond-level latency without putting load on the source DB.

Supported databases: Through connectors, it supports a wide range of databases including PostgreSQL, MySQL/MariaDB, MongoDB, SQL Server, Oracle, Cassandra, and Db2. Each connector natively implements that DB's replication protocol.

Use cases: (1) Data synchronization between microservices - the inventory service subscribes to order service DB changes, (2) real-time updates of Elasticsearch/Redis caches, (3) real-time ETL for data warehouses, (4) implementing event sourcing/CQRS patterns, (5) gradual migration from a legacy monolith to microservices.

Debezium events are delivered as structured JSON containing the before/after data of the change, source metadata (table name, transaction ID), and the operation type (c/u/d/r), which makes downstream processing easy.

💻 Code Example

# Debezium CDC 이벤트 Consumer - Python
from kafka import KafkaConsumer
import json

class DebeziumConsumer:
    """Debezium CDC 이벤트를 처리하는 Consumer"""

    def __init__(self, bootstrap_servers: str, topic: str):
        self.consumer = KafkaConsumer(
            topic,
            bootstrap_servers=bootstrap_servers,
            value_deserializer=lambda m: json.loads(m.decode('utf-8')),
            auto_offset_reset='earliest',
            group_id='my-cdc-consumer'
        )

    def process_events(self):
        """CDC 이벤트 처리"""
        for message in self.consumer:
            event = message.value

            # Debezium 이벤트 구조
            payload = event.get('payload', event)
            operation = payload.get('op')  # c=create, u=update, d=delete, r=read(snapshot)
            before = payload.get('before')  # 변경 전 데이터
            after = payload.get('after')    # 변경 후 데이터
            source = payload.get('source')  # 소스 메타데이터

            # 작업 타입별 처리
            if operation == 'c':
                self.handle_insert(after, source)
            elif operation == 'u':
                self.handle_update(before, after, source)
            elif operation == 'd':
                self.handle_delete(before, source)
            elif operation == 'r':
                # 스냅샷 읽기 (초기 동기화)
                self.handle_snapshot(after, source)

    def handle_insert(self, data: dict, source: dict):
        """INSERT 이벤트 처리"""
        table = source.get('table')
        print(f"INSERT on {table}: {data}")

        # 예: Elasticsearch 인덱싱
        # es.index(index=table, id=data['id'], body=data)

        # 예: Redis 캐시 업데이트
        # redis.hset(f"{table}:{data['id']}", mapping=data)

    def handle_update(self, before: dict, after: dict, source: dict):
        """UPDATE 이벤트 처리 - 변경된 필드만 추출"""
        table = source.get('table')
        changed_fields = {
            k: after[k] for k in after
            if before.get(k) != after.get(k)
        }
        print(f"UPDATE on {table}, changed: {changed_fields}")

        # 예: 주문 상태 변경 시 알림 발송
        if table == 'orders' and 'status' in changed_fields:
            self.send_order_notification(after)

    def handle_delete(self, data: dict, source: dict):
        """DELETE 이벤트 처리"""
        table = source.get('table')
        print(f"DELETE on {table}: id={data.get('id')}")

        # 예: 캐시에서 삭제
        # redis.delete(f"{table}:{data['id']}")


# Outbox 패턴 구현 (이벤트 발행 보장)
class OutboxProcessor:
    """Outbox 테이블의 CDC 이벤트를 실제 이벤트로 변환"""

    def process_outbox_event(self, payload: dict):
        """
        Outbox 테이블 구조:
        - id: UUID
        - aggregate_type: 'Order', 'User' 등
        - aggregate_id: 실제 엔티티 ID
        - event_type: 'OrderCreated', 'OrderShipped' 등
        - payload: JSON
        """
        after = payload.get('after')
        if not after:
            return

        event = {
            'type': after['event_type'],
            'aggregate_type': after['aggregate_type'],
            'aggregate_id': after['aggregate_id'],
            'data': json.loads(after['payload']),
            'timestamp': after['created_at']
        }

        # 실제 이벤트 토픽으로 발행
        self.publish_domain_event(event)


# 사용 예시
if __name__ == "__main__":
    consumer = DebeziumConsumer(
        bootstrap_servers='localhost:9092',
        topic='mydb.public.orders'  # {server}.{schema}.{table}
    )
    consumer.process_events()
// Debezium CDC 이벤트 Consumer - Node.js
const { Kafka } = require('kafkajs');

class DebeziumConsumer {
    constructor(brokers, groupId) {
        this.kafka = new Kafka({
            clientId: 'debezium-consumer',
            brokers: brokers
        });
        this.consumer = this.kafka.consumer({ groupId });
    }

    async connect(topics) {
        await this.consumer.connect();
        await this.consumer.subscribe({
            topics: topics,
            fromBeginning: false
        });
    }

    async processEvents(handlers) {
        await this.consumer.run({
            eachMessage: async ({ topic, partition, message }) => {
                const event = JSON.parse(message.value.toString());
                const payload = event.payload || event;

                const { op, before, after, source } = payload;
                const table = source?.table;

                console.log(`[${table}] Operation: ${op}`);

                // 작업 타입별 핸들러 호출
                switch (op) {
                    case 'c': // CREATE
                        await handlers.onCreate?.(table, after, source);
                        break;
                    case 'u': // UPDATE
                        await handlers.onUpdate?.(table, before, after, source);
                        break;
                    case 'd': // DELETE
                        await handlers.onDelete?.(table, before, source);
                        break;
                    case 'r': // READ (snapshot)
                        await handlers.onSnapshot?.(table, after, source);
                        break;
                }
            }
        });
    }
}

// Elasticsearch 실시간 동기화 예제
const { Client } = require('@elastic/elasticsearch');
const esClient = new Client({ node: 'http://localhost:9200' });

const handlers = {
    async onCreate(table, data, source) {
        // 새 문서 인덱싱
        await esClient.index({
            index: table,
            id: data.id.toString(),
            body: data
        });
        console.log(`Indexed new document in ${table}`);
    },

    async onUpdate(table, before, after, source) {
        // 문서 업데이트
        await esClient.update({
            index: table,
            id: after.id.toString(),
            body: { doc: after }
        });

        // 특정 필드 변경 시 추가 로직
        if (table === 'products' && before.price !== after.price) {
            console.log(`Price changed: ${before.price} -> ${after.price}`);
            // 가격 변경 알림 등
        }
    },

    async onDelete(table, data, source) {
        // 문서 삭제
        await esClient.delete({
            index: table,
            id: data.id.toString()
        });
        console.log(`Deleted document from ${table}`);
    },

    async onSnapshot(table, data, source) {
        // 초기 스냅샷 동기화
        await esClient.index({
            index: table,
            id: data.id.toString(),
            body: data
        });
    }
};

// 실행
async function main() {
    const consumer = new DebeziumConsumer(
        ['localhost:9092'],
        'es-sync-group'
    );

    await consumer.connect([
        'mydb.public.products',
        'mydb.public.orders'
    ]);

    await consumer.processEvents(handlers);
}

main().catch(console.error);
// ============================================
// PostgreSQL Debezium Connector 설정
// ============================================
{
    "name": "postgres-connector",
    "config": {
        "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
        "database.hostname": "postgres",
        "database.port": "5432",
        "database.user": "debezium",
        "database.password": "secret",
        "database.dbname": "mydb",
        "database.server.name": "mydb",

        // 캡처할 테이블 지정
        "table.include.list": "public.orders,public.products,public.users",

        // 스냅샷 모드
        // initial: 최초 전체 스냅샷 후 스트리밍
        // never: 스냅샷 없이 바로 스트리밍
        // when_needed: 필요시 스냅샷
        "snapshot.mode": "initial",

        // PostgreSQL 복제 슬롯
        "slot.name": "debezium_slot",
        "publication.name": "dbz_publication",

        // 토픽 설정
        "topic.prefix": "mydb",

        // 변환 설정
        "transforms": "unwrap",
        "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
        "transforms.unwrap.drop.tombstones": "false",

        // 스키마 레지스트리 (Avro 사용 시)
        "key.converter": "org.apache.kafka.connect.json.JsonConverter",
        "value.converter": "org.apache.kafka.connect.json.JsonConverter"
    }
}

// ============================================
// MySQL Debezium Connector 설정
// ============================================
{
    "name": "mysql-connector",
    "config": {
        "connector.class": "io.debezium.connector.mysql.MySqlConnector",
        "database.hostname": "mysql",
        "database.port": "3306",
        "database.user": "debezium",
        "database.password": "secret",
        "database.server.id": "184054",
        "database.server.name": "mydb",

        // binlog 위치 (초기 시작점)
        "database.include.list": "inventory",
        "table.include.list": "inventory.orders,inventory.products",

        // GTID 모드 (고가용성 권장)
        "include.schema.changes": "true",
        "gtid.source.includes": "",

        // 스냅샷 설정
        "snapshot.mode": "initial",
        "snapshot.locking.mode": "minimal"
    }
}

// ============================================
// Docker Compose로 Debezium 실행
// ============================================
# docker-compose.yml
version: '3'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:7.5.0
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181

  kafka:
    image: confluentinc/cp-kafka:7.5.0
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT

  connect:
    image: debezium/connect:2.4
    depends_on:
      - kafka
    ports:
      - "8083:8083"
    environment:
      BOOTSTRAP_SERVERS: kafka:29092
      GROUP_ID: 1
      CONFIG_STORAGE_TOPIC: connect_configs
      OFFSET_STORAGE_TOPIC: connect_offsets
      STATUS_STORAGE_TOPIC: connect_statuses

# 커넥터 등록
# curl -X POST http://localhost:8083/connectors \
#   -H "Content-Type: application/json" \
#   -d @postgres-connector.json

🗣️ Say It Like This in Practice

💬 In a microservice architecture design meeting
"Synchronizing data between services through API calls leads to tight coupling. If we set up CDC with Debezium, order service DB changes flow automatically into Kafka, and the inventory and shipping services can subscribe independently. The source service doesn't need to know the other services exist."
💬 In a discussion about improving search
"Syncing the product DB to Elasticsearch is a batch job, so there's up to a 1-hour delay. With Debezium, DB changes are reflected in Elasticsearch immediately, so search results update in real time. Development gets simpler too, since you just modify the DB with no separate sync logic."
💬 In responding to a data pipeline outage
"When Debezium goes down and recovers, it resumes from the last processed position, because the WAL position is managed as a Kafka Connect offset. However, PostgreSQL's replication slot has to keep retaining the WAL, so a long outage risks filling the disk. Setting up monitoring alerts is essential."

⚠️ Cautions & Best Practices

❌
Replication slot monitoring is essential

A PostgreSQL replication slot retains the WAL. If Debezium fails, the WAL is not deleted and the disk can fill up. Set up slot lag monitoring and alerts.

❌
Be careful with schema changes

On ALTER TABLE, Debezium has to recognize the new schema. Incompatible changes (dropping a column, changing a type) can cause consumer failures, so proceed gradually.

❌
Handling large snapshots

The initial snapshot of a table with hundreds of millions of rows takes hours and puts load on the source DB. Choose snapshot.mode carefully and use incremental snapshots if needed.

✅
Use the Outbox pattern

To keep business logic and event publishing atomic, use an Outbox table. Store the data and the event together in one transaction, and Debezium captures the event.

🔗 Related Terms

📚 Learn More