🗄️Databases

CDC

Change Data Capture - Real-time Data Synchronization

CDC (Change Data Capture) is a technology that detects and captures database changes (INSERT, UPDATE, DELETE) in real time. It is used heavily for data synchronization between systems, event sourcing, and real-time ETL through Debezium, Kafka Connect, and others.

📖 Detailed Explanation

Core Principle of CDC - CDC extracts changes by reading the database's transaction log (WAL, Binlog). Unlike the polling approach, it puts no load on the source DB and can also capture deleted data. Change order is guaranteed, so data consistency is maintained.

Role of Debezium - Debezium, an open-source CDC platform developed by Red Hat, supports a variety of databases including MySQL, PostgreSQL, MongoDB, and SQL Server. It runs on Kafka Connect and streams change events to Kafka topics. It integrates with a schema registry to manage schema evolution.

CDC Use Cases - It is used for data synchronization between microservices, updating read models in the CQRS pattern, real-time loading of data warehouses, cache invalidation, audit log generation, search index synchronization (Elasticsearch), and more. It is a core component of Event-Driven Architecture.

Log-Based vs Query-Based - Log-based CDC (Debezium) reads the transaction log, so it offers high real-time performance and low load. Query-based CDC (timestamp polling) is simple to implement, but deletes are hard to detect and there is latency. Log-based CDC is recommended for most production environments.

Combining with the Outbox Pattern - To guarantee atomicity between the transaction and event publishing, the Outbox pattern and CDC are used together. The business table change and the Outbox table insert are bundled into a single transaction, and CDC monitors the Outbox table to publish the event.

💻 Code Example

// Debezium MySQL Connector 설정 (Kafka Connect REST API)
// POST /connectors

{
  "name": "mysql-orders-connector",
  "config": {
    "connector.class": "io.debezium.connector.mysql.MySqlConnector",
    "database.hostname": "mysql-primary",
    "database.port": "3306",
    "database.user": "debezium",
    "database.password": "${secrets:mysql-password}",
    "database.server.id": "184054",
    "topic.prefix": "dbserver1",
    "database.include.list": "ecommerce",
    "table.include.list": "ecommerce.orders,ecommerce.order_items",

    // 스키마 히스토리 (DDL 변경 추적)
    "schema.history.internal.kafka.bootstrap.servers": "kafka:9092",
    "schema.history.internal.kafka.topic": "schema-changes.ecommerce",

    // 변환 설정
    "transforms": "route,unwrap",
    "transforms.route.type": "org.apache.kafka.connect.transforms.RegexRouter",
    "transforms.route.regex": "([^.]+)\\.([^.]+)\\.([^.]+)",
    "transforms.route.replacement": "cdc.$3",

    // Outbox 패턴 지원
    "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
    "transforms.unwrap.drop.tombstones": "false",
    "transforms.unwrap.delete.handling.mode": "rewrite",

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

    // 오프셋 저장
    "offset.storage.topic": "connect-offsets",
    "offset.flush.interval.ms": "10000"
  }
}

// 토픽 메시지 예시 (orders 테이블 UPDATE)
/*
{
  "before": {
    "id": 1001,
    "status": "pending",
    "total": 50000
  },
  "after": {
    "id": 1001,
    "status": "shipped",
    "total": 50000
  },
  "source": {
    "version": "2.4.0.Final",
    "connector": "mysql",
    "name": "dbserver1",
    "ts_ms": 1706277600000,
    "db": "ecommerce",
    "table": "orders",
    "server_id": 184054,
    "gtid": null,
    "file": "mysql-bin.000003",
    "pos": 12345
  },
  "op": "u",  // c=create, u=update, d=delete, r=read(snapshot)
  "ts_ms": 1706277600100
}
*/
// Kafka Consumer로 CDC 이벤트 처리 (Java)
import org.apache.kafka.clients.consumer.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class CDCEventConsumer {
    private final ObjectMapper mapper = new ObjectMapper();

    public void consumeCDCEvents() {
        Properties props = new Properties();
        props.put("bootstrap.servers", "kafka:9092");
        props.put("group.id", "order-sync-service");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("auto.offset.reset", "earliest");
        props.put("enable.auto.commit", "false");

        try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) {
            consumer.subscribe(List.of("cdc.orders"));

            while (true) {
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));

                for (ConsumerRecord<String, String> record : records) {
                    processCDCEvent(record.value());
                }

                consumer.commitSync();  // 처리 완료 후 커밋
            }
        }
    }

    private void processCDCEvent(String eventJson) throws Exception {
        JsonNode event = mapper.readTree(eventJson);
        String operation = event.get("op").asText();

        switch (operation) {
            case "c" -> handleCreate(event.get("after"));
            case "u" -> handleUpdate(event.get("before"), event.get("after"));
            case "d" -> handleDelete(event.get("before"));
            case "r" -> handleSnapshot(event.get("after"));
        }
    }

    private void handleUpdate(JsonNode before, JsonNode after) {
        Long orderId = after.get("id").asLong();
        String oldStatus = before.get("status").asText();
        String newStatus = after.get("status").asText();

        if (!oldStatus.equals(newStatus)) {
            System.out.println("Order " + orderId + ": " + oldStatus + " → " + newStatus);
            // 읽기 모델 업데이트, 알림 발송 등
            updateReadModel(orderId, after);
            sendNotification(orderId, newStatus);
        }
    }
}
# Python으로 CDC 이벤트 처리
from kafka import KafkaConsumer
from dataclasses import dataclass
from typing import Optional, Dict, Any
import json

@dataclass
class CDCEvent:
    operation: str  # c, u, d, r
    before: Optional[Dict[str, Any]]
    after: Optional[Dict[str, Any]]
    source: Dict[str, Any]
    timestamp: int

    @classmethod
    def from_json(cls, data: dict) -> "CDCEvent":
        return cls(
            operation=data.get("op"),
            before=data.get("before"),
            after=data.get("after"),
            source=data.get("source", {}),
            timestamp=data.get("ts_ms", 0)
        )


class OrderCDCProcessor:
    def __init__(self, kafka_servers: str):
        self.consumer = KafkaConsumer(
            "cdc.orders",
            bootstrap_servers=kafka_servers,
            group_id="order-analytics",
            value_deserializer=lambda m: json.loads(m.decode("utf-8")),
            auto_offset_reset="earliest",
            enable_auto_commit=False
        )

    def process_events(self):
        """CDC 이벤트 처리 루프"""
        for message in self.consumer:
            try:
                event = CDCEvent.from_json(message.value)
                self.handle_event(event)
                self.consumer.commit()
            except Exception as e:
                print(f"Error processing event: {e}")
                # Dead Letter Queue로 전송

    def handle_event(self, event: CDCEvent):
        """이벤트 타입별 처리"""
        handlers = {
            "c": self.on_create,
            "u": self.on_update,
            "d": self.on_delete,
            "r": self.on_snapshot
        }

        handler = handlers.get(event.operation)
        if handler:
            handler(event)

    def on_create(self, event: CDCEvent):
        """새 주문 생성"""
        order = event.after
        print(f"✅ New order: #{order['id']} - {order['total']}원")
        # 분석 시스템에 전송
        self.send_to_analytics("order_created", order)

    def on_update(self, event: CDCEvent):
        """주문 상태 변경"""
        before, after = event.before, event.after

        # 변경된 필드 감지
        changes = {
            k: (before.get(k), after.get(k))
            for k in after.keys()
            if before.get(k) != after.get(k)
        }

        if "status" in changes:
            old, new = changes["status"]
            print(f"📦 Order #{after['id']}: {old} → {new}")

            if new == "shipped":
                self.notify_shipping(after)
            elif new == "delivered":
                self.update_inventory(after)

    def on_delete(self, event: CDCEvent):
        """주문 삭제 (Soft delete 권장)"""
        order = event.before
        print(f"🗑️ Order deleted: #{order['id']}")
        # 인덱스에서 제거
        self.remove_from_search_index(order['id'])

    def send_to_analytics(self, event_type: str, data: dict):
        """분석 시스템으로 전송"""
        # ClickHouse, BigQuery 등으로 적재
        pass


if __name__ == "__main__":
    processor = OrderCDCProcessor("kafka:9092")
    processor.process_events()

💬 Real-world conversation examples

A data engineer in an architecture meeting

"We're synchronizing Elasticsearch by polling, but we're missing delete events. If we build a CDC pipeline with Debezium, we can capture even DELETEs from the binlog. Latency also drops to tens of milliseconds."

A backend developer in microservice design

"We need to send events from the order service to the shipping service, but we want to avoid distributed transactions. How about combining the Outbox pattern and CDC to guarantee eventual consistency? Business logic and messaging are cleanly separated."

A DBA in a performance review

"Debezium reading MySQL's binlog works the same way as replica replication, so there is almost no load on the main DB. However, binlog_format must be set to ROW, and the retention period must be set long enough to make failure recovery easier."

⚠️ Cautions

📋
Schema Change Management Is Essential

A CDC connector may stop when a table DDL changes. Version-control with a schema registry, and apply only compatible changes.

⏰
Consider the Initial Snapshot Time

The initial snapshot of a large table can take several hours. Use incremental snapshots or parallel processing options.

🔄
Prepare for Duplicate Processing

Events may be resent during failure recovery. Ensure idempotency in the consumer or implement duplicate-check logic.

💾
Check Log Retention Period

If the binlog/WAL retention period is short, data will be lost when the connector restarts. We recommend retaining them for at least 7 days.

🔗 Related Terms

📚 Learn More