Change Data Capture (CDC) Pattern

Change Data Capture (CDC) is a data integration pattern that identifies and captures changes made to a source database and makes those changes available to downstream systems.

Overview

Change Data Capture (CDC) is an architectural and data integration pattern used to detect changes in a database and propagate them to other systems. Instead of repeatedly copying entire tables, CDC captures only the data that has changed, such as inserted, updated, or deleted records.

CDC is commonly used in data synchronization, event-driven architectures, data replication, analytics pipelines, search indexing, and migration between databases. It is not a traditional Gang of Four object-oriented design pattern; it is better classified as an architectural integration pattern.

Change Detection

Identifies INSERT, UPDATE, and DELETE operations performed against source data. Depending on the implementation, changes may be read from transaction logs, detected by database triggers, or found through periodic queries.

Change Capture

Converts detected database changes into change records or events. A record may include the affected table, operation type, primary key, changed values, and source metadata.

Change Propagation

Delivers captured changes to downstream consumers, such as another database, a message broker, a search index, or an analytics platform.

How Does CDC Work?

The following diagram illustrates how Change Data Capture (CDC) captures database changes from transaction logs and propagates them to downstream systems through a message broker.

Change Data Capture (CDC) Architecture Diagram

CDC Processing Flow

In a typical log-based CDC pipeline, a connector reads the database transaction log, converts relevant operations into change events, and publishes them for downstream applications to process.

Source Database
→
Transaction Log
→
CDC Connector

CDC Events
→
Message Broker
→
Downstream Systems

The connector also tracks its reading position, commonly called an offset, log sequence number (LSN), or binlog position, depending on the database and connector. After a restart, it uses the saved position to resume reading. Correct checkpoint management is essential to avoid missing changes; duplicate delivery may still occur and should be handled safely.

Components and Responsibilities

Component Responsibilities
Source Database Stores application data and records committed transactions. Its transaction log provides the change history used by log-based CDC.
Transaction Log Records database changes for recovery and durability. A CDC connector can read relevant log entries without repeatedly querying every source table.
CDC Connector Reads changes, interprets database-specific log records, converts them into structured events, and manages its progress through the source log.
Offset / Checkpoint Stores the connector's last successfully processed source position so it can resume after a restart or failure.
Message Broker Distributes change events to consumers and can buffer events between producers and downstream applications. It is optional; CDC events can also be delivered directly to a target.
Consumers / Targets Apply changes to target databases, update search indexes, trigger workflows, or feed analytics and reporting systems.

CDC Implementation Approaches

1. Log-Based CDC

Reads the database's transaction log, such as a write-ahead log, redo log, or binary log. It can capture committed changes with relatively low impact on application queries. This is a widely used approach for continuous, near-real-time data integration.

2. Trigger-Based CDC

Uses database triggers that execute when rows are inserted, updated, or deleted. The triggers typically write change information into separate audit or change tables, which another process reads and forwards.

3. Query-Based CDC (Polling)

Periodically queries source tables using a timestamp, version column, or another change indicator. This approach is relatively straightforward, but it may not reliably detect hard deletes unless additional tracking is implemented. Its latency depends on the polling interval.

Approach How It Works Considerations
Log-Based Reads database transaction logs. Efficient for continuous capture, but depends on database log access, retention, and connector support.
Trigger-Based Database triggers write changes to capture tables. Can add write overhead and operational complexity to the source database.
Query-Based Polls tables for rows with newer timestamps or versions. Simple to implement, but can add query load and may miss deletes or intermediate changes.

Simple Java CDC Event Processing Example

The following simplified example illustrates how an application might represent and process a CDC event after a connector has captured it. It is not a database log reader or a complete CDC connector implementation.

CDC Event

public class ChangeEvent {

    private String operation;
    private int recordId;
    private String newValue;

    public ChangeEvent(String operation, int recordId, String newValue) {
        this.operation = operation;
        this.recordId = recordId;
        this.newValue = newValue;
    }

    public String getOperation() {
        return operation;
    }

    public int getRecordId() {
        return recordId;
    }

    public String getNewValue() {
        return newValue;
    }
}

Change Event Consumer

public class ChangeEventConsumer {

    public void process(ChangeEvent event) {

        switch (event.getOperation()) {

            case "INSERT":
                System.out.println(
                    "Insert record: " + event.getRecordId());
                break;

            case "UPDATE":
                System.out.println(
                    "Update record: " + event.getRecordId()
                    + ", value: " + event.getNewValue());
                break;

            case "DELETE":
                System.out.println(
                    "Delete record: " + event.getRecordId());
                break;

            default:
                throw new IllegalArgumentException(
                    "Unsupported operation: " + event.getOperation());
        }
    }
}

Using the Consumer

public class CDCExample {

    public static void main(String[] args) {

        ChangeEventConsumer consumer = new ChangeEventConsumer();

        ChangeEvent event =
            new ChangeEvent("UPDATE", 101, "Updated Value");

        consumer.process(event);
    }
}

In a production system, the event would normally be supplied by a CDC connector or message broker. The consumer would also need error handling, schema management, retry policies, and idempotent processing.

Offsets, Checkpoints, and Reliability

A CDC connector must remember how far it has read in the source transaction log. This position is stored as an offset or checkpoint. For example, a database may expose a log sequence number (LSN) or binary log file and position.

Concept Explanation
Offset / Log Position Identifies a position in the source log from which the connector can continue reading.
Checkpoint Persists progress so a connector can recover after a restart.
At-Least-Once Delivery Events may be delivered more than once, so consumers should be designed to handle duplicates.
Idempotency Processing the same event again does not create an unintended additional effect.
Ordering Consumers may need to preserve the order of changes for the same record or partition.
Log Retention Source logs must remain available long enough for the connector to catch up after downtime.

A key design consideration is coordinating event delivery and checkpoint advancement. If a connector advances its checkpoint before changes are safely delivered, events could be lost. If it delivers events and fails before saving progress, some events may be delivered again. This is why duplicate-safe consumers and carefully designed recovery behavior are important.

Advantages of CDC

Disadvantages and Challenges of CDC

Where CDC is Used

Technology / System Usage
Debezium Open-source CDC platform that captures database changes and commonly publishes them to Apache Kafka.
Apache Kafka Distributes CDC events to multiple consumers through topics.
Oracle Database Redo-log-based change capture can be used by supported CDC tools and integrations.
MySQL Binary-log-based capture can stream row-level changes to downstream systems.
PostgreSQL Logical decoding and replication slots expose database changes to CDC consumers.
Data Warehouses / Analytics Incrementally propagates operational database changes into analytical systems.
Search Platforms Keeps search indexes synchronized with changes in application databases.