Arquitectura de Datos

Data Mesh: Apache Kafka and Change Data Capture, How to Build Real-Time Cross-Domain Data Pipelines

Learn how to build real-time data pipelines using Apache Kafka in KRaft mode, Kafka Connect, and Debezium on MySQL, distinguishing technical Change Data Capture (CDC) from decoupled business event publication via the Transactional Outbox pattern.

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

The Dilemma of Publishing Real-Time Changes Without Breaking Consistency or Leaking Database Schemas

At CommerceFlow, the transactional microservice of the Sales domain persists orders in a relational MySQL database (sales_db.orders). To feed real-time updates both into its own analytical data products and across other mesh domains, the team first attempted the seemingly simplest approach: having the application code run COMMIT in MySQL and immediately publish an event to Apache Kafka (dual write).

During the first week of load testing, two classic distributed-systems failures surfaced:

  1. Silent Event Loss: The application committed order ORD-5001 in MySQL, but experienced a 2-second network timeout before publishing to Kafka. The order existed in the database, yet never reached the event stream.
  2. Phantom Events: When the team reversed the order (publishing to Kafka before committing in MySQL) and the database transaction rolled back due to a lock or constraint violation, downstream consumers received an OrderConfirmed event for an order that never existed in MySQL.

To eliminate dual writes, the team attached Debezium to MySQL's transaction log (binlog) and exposed the generated topic (commerceflow_sales.sales_db.orders) directly to every domain in the company. The dual-write bug disappeared, but a new architectural problem emerged: every time Sales developers renamed an internal column or ran a database migration in MySQL, they broke consumers in Inventory and Finance.

In this article, you will learn how Apache Kafka and Change Data Capture (CDC) work from the ground up, how to build a reproducible local laboratory using MySQL, Kafka in KRaft mode, Kafka Connect with Debezium, and Python, and how to combine internal CDC or the Transactional Outbox pattern to publish real-time streams without coupling the mesh to your internal operational schema.


Core Mechanics of Apache Kafka in a Streaming Data Mesh

Apache Kafka is a distributed event streaming platform built around an append-only commit log. Designing reliable pipelines on Kafka requires understanding how its foundational components interact:

                      APACHE KAFKA CLUSTER (KRaft Mode)
+---------------------------------------------------------------------------+
| Topic: sales.order-events.v1 (Split across 3 ordered partitions)          |
|                                                                           |
| Partition 0 (hash(key) % 3 == 0):  [offset 0] -> [offset 1] -> [offset 2] |
| Partition 1 (hash(key) % 3 == 1):  [offset 0] -> [offset 1]               |
| Partition 2 (hash(key) % 3 == 2):  [offset 0] -> [offset 1] -> [offset 2] |
+---------------------------------------------------------------------------+
                  |                                         |
                  v (Independent consumption)               v (Independent consumption)
   [Consumer Group: cg-inventory]             [Consumer Group: cg-analytics]
   (Instance A reads P0, P1; B reads P2)      (Instance C reads P0, P1, P2)
  1. Brokers and KRaft Mode (Kafka Raft Metadata Mode): A Kafka cluster consists of one or more servers called brokers. Modern Kafka versions manage cluster metadata consensus (topics, partition leaders, configurations) internally via the KRaft protocol, removing the historical dependency on Apache ZooKeeper.
  2. Topics and Partitions: A topic is a named logical channel to which records are published. For horizontal scalability, each topic is divided into one or more partitions. Each partition is an ordered, immutable sequence of records stored on disk and replicated across multiple brokers for fault tolerance (replication factor).
  3. Partition Keys and the Truth About Ordering: When a producer publishes an event with a key (for example, key = "ORD-5001"), Kafka computes a deterministic hash of that key so all records with the same key land in the exact same partition.
    • Fundamental Boundary: Kafka guarantees event ordering only within a single partition, never globally across multiple partitions of a topic. By using order_id as the partition key, OrderCreated, OrderConfirmed, and OrderCancelled for ORD-5001 always land in the same partition and are read in strict sequence.
  4. Offsets: Every record within a partition is assigned a sequential integer called an offset (0, 1, 2, ...).
    • Critical Caveat: An offset is not a business identifier and is not unique across a topic. offset = 5 exists simultaneously in Partition 0, Partition 1, and Partition 2; a record's position in Kafka is uniquely identified only by the tuple (topic, partition, offset).
  5. Consumers and Consumer Groups:
    • Within a single Consumer Group, Kafka distributes partitions across the active consumer instances in that group to parallelize processing (at most one consumer instance within a group reads a given partition at a time).
    • Separate Consumer Groups (for example, cg-inventory-stock and cg-finance-audit) read the same topic completely independently, each tracking its own committed offsets.
  6. Time Retention vs. Log Compaction:
    • Time/Size Retention (delete): Retains all events for a configured window (e.g., 7 days), enabling full replay over that window, though it is not permanent historical storage once segments expire.
    • Log Compaction (compact): Retains at least the latest known record for each key in the background. It is useful for snapshotting current entity state, but it does not preserve every historical state transition.

Capturing Changes from the MySQL binlog with Debezium and Kafka Connect

To extract changes from an operational database without fragile application dual writes, we use log-based Change Data Capture (CDC):

[MySQL 8.0 (sales_db.orders)]
       |
       | 1. Writes committed transactions to the Binary Log (binlog_format=ROW)
       v
[Kafka Connect + Debezium MySQL Connector]
       |
       | 2. Runs initial snapshot ('r') and then tails the binlog continuously ('c','u','d')
       | 3. Tracks binlog position and publishes each change keyed by order_id
       v
[Apache Kafka: Topic commerceflow_sales.sales_db.orders]
       |
       v
[Sales Domain Consumer / State Materializer (Python)]

How the End-to-End Mechanism Works

  1. MySQL binlog in ROW Format: When configured with binlog_format = ROW and binlog_row_image = FULL, MySQL records the exact state of every row before (before) and after (after) each committed INSERT, UPDATE, or DELETE.
  2. Initial Snapshot vs. Continuous Streaming: The first time the Debezium connector starts, it performs a consistent read of existing table rows (emitting records with op = "r" for read), records the exact binlog coordinates (file and pos or GTID), and seamlessly transitions to streaming new row mutations in milliseconds without locking operational tables.
  3. Crash Recovery and Resumption: Kafka Connect periodically flushes the latest processed binlog coordinates to an internal topic (cf_connect_offsets). If the connector restarts, it resumes reading from the last committed coordinate. Because a few events immediately preceding a crash may be re-sent (at-least-once delivery), downstream consumers must be idempotent.

Reproducible Hands-On Lab: MySQL + Kafka KRaft + Debezium + Python

Let us build a complete local laboratory for the Sales domain of CommerceFlow.

Security Warning: The passwords (lab_root_pwd_only, lab_repl_pwd_only) and unencrypted local listeners in this docker-compose.yml are strictly for local laboratory use. In production (for example, on Amazon MSK and Amazon RDS), always enforce TLS in transit, SASL/SCRAM or IAM authentication, private subnets, and secret rotation in AWS Secrets Manager.

Step 1: Local Infrastructure in docker-compose.yml

We use explicit, verified container versions (mysql:8.0.36, apache/kafka:3.7.0 in ZooKeeper-less KRaft mode, and quay.io/debezium/connect:2.6):

# docker-compose.yml (Reproducible local lab for CommerceFlow Sales)
services:
  mysql:
    image: mysql:8.0.36
    container_name: cf-sales-mysql
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: lab_root_pwd_only
      MYSQL_DATABASE: sales_db
    command:
      - --server-id=1001
      - --log-bin=mysql-bin
      - --binlog-format=ROW
      - --binlog-row-image=FULL
      - --expire-logs-days=3
    volumes:
      - ./init_sales.sql:/docker-entrypoint-initdb.d/init_sales.sql:ro

  kafka:
    image: apache/kafka:3.7.0
    container_name: cf-kafka-kraft
    ports:
      - "9092:9092"
    environment:
      KAFKA_NODE_ID: 1
      KAFKA_PROCESS_ROLES: broker,controller
      KAFKA_LISTENERS: PLAINTEXT://:29092,CONTROLLER://:29093,EXTERNAL://:9092
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,EXTERNAL://localhost:9092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT,EXTERNAL:PLAINTEXT
      KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:29093
      KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
      KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1

  kafka-connect:
    image: quay.io/debezium/connect:2.6
    container_name: cf-debezium-connect
    depends_on:
      - kafka
      - mysql
    ports:
      - "8083:8083"
    environment:
      BOOTSTRAP_SERVERS: kafka:29092
      GROUP_ID: cf-connect-cluster
      CONFIG_STORAGE_TOPIC: cf_connect_configs
      OFFSET_STORAGE_TOPIC: cf_connect_offsets
      STATUS_STORAGE_TOPIC: cf_connect_status
      CONFIG_STORAGE_REPLICATION_FACTOR: 1
      OFFSET_STORAGE_REPLICATION_FACTOR: 1
      STATUS_STORAGE_REPLICATION_FACTOR: 1

Step 2: Initializing MySQL with a Least-Privilege Replication User (init_sales.sql)

Rather than connecting Debezium as root, we create a dedicated replication user (debezium_sales_reader) granted only the permissions required to read the binlog and the authorized Sales tables:

-- init_sales.sql: Operational tables and least-privilege CDC replication user
CREATE USER IF NOT EXISTS 'debezium_sales_reader'@'%' IDENTIFIED BY 'lab_repl_pwd_only';

GRANT SELECT, RELOAD, SHOW DATABASES, REPLICATION SLAVE, REPLICATION CLIENT
ON *.* TO 'debezium_sales_reader'@'%';
FLUSH PRIVILEGES;

USE sales_db;

-- 1. Internal operational orders table
CREATE TABLE orders (
    order_id VARCHAR(32) NOT NULL PRIMARY KEY,
    customer_id VARCHAR(32) NOT NULL,
    order_status VARCHAR(24) NOT NULL,
    total_amount DECIMAL(12,2) NOT NULL,
    currency CHAR(3) NOT NULL DEFAULT 'USD',
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- 2. Table for the Transactional Outbox pattern (decoupled business events)
CREATE TABLE outbox_events (
    event_id VARCHAR(64) NOT NULL PRIMARY KEY,
    aggregate_type VARCHAR(32) NOT NULL,
    aggregate_id VARCHAR(32) NOT NULL,
    event_type VARCHAR(64) NOT NULL,
    payload JSON NOT NULL,
    occurred_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- Seed record inserted before connector startup (will be captured via snapshot 'r')
INSERT INTO orders (order_id, customer_id, order_status, total_amount, currency)
VALUES ('ORD-6001', 'CUST-501', 'PENDING', 120.00, 'USD');

Step 3: Registering the Debezium MySQL Connector (sales-mysql-connector.json)

Once the containers are running (docker compose up -d), we register the connector by posting its JSON configuration to the Kafka Connect REST API (POST http://localhost:8083/connectors):

{
  "name": "sales-orders-mysql-cdc",
  "config": {
    "connector.class": "io.debezium.connector.mysql.MySqlConnector",
    "tasks.max": "1",
    "database.hostname": "mysql",
    "database.port": "3306",
    "database.user": "debezium_sales_reader",
    "database.password": "lab_repl_pwd_only",
    "database.server.id": "2001",
    "topic.prefix": "commerceflow_sales",
    "database.include.list": "sales_db",
    "table.include.list": "sales_db.orders,sales_db.outbox_events",
    "schema.history.internal.kafka.bootstrap.servers": "kafka:29092",
    "schema.history.internal.kafka.topic": "internal.schema_history.sales",
    "include.schema.changes": "false",
    "decimal.handling.mode": "double"
  }
}

Debezium Topic Naming Convention: By default, the connector names each topic using <topic.prefix>.<databaseName>.<tableName>. Thus, row changes on orders are published to commerceflow_sales.sales_db.orders using the table's primary key (order_id) as the Kafka message key.


Step 4: Executing INSERT, UPDATE, and DELETE and Inspecting the Debezium Event Structure

Let us open a MySQL client session and execute the three lifecycle operations on sales_db.orders:

-- 1. INSERT a second order
INSERT INTO sales_db.orders (order_id, customer_id, order_status, total_amount, currency)
VALUES ('ORD-6002', 'CUST-502', 'PENDING', 75.50, 'USD');

-- 2. UPDATE the first order to PAID status
UPDATE sales_db.orders
SET order_status = 'PAID', total_amount = 125.00
WHERE order_id = 'ORD-6001';

-- 3. DELETE a cancelled test order
DELETE FROM sales_db.orders
WHERE order_id = 'ORD-6002';

Below is the exact JSON payload Debezium publishes to commerceflow_sales.sales_db.orders for the UPDATE operation (op = "u"):

{
  "before": {
    "order_id": "ORD-6001",
    "customer_id": "CUST-501",
    "order_status": "PENDING",
    "total_amount": 120.0,
    "currency": "USD",
    "updated_at": "2026-05-10T15:00:00Z"
  },
  "after": {
    "order_id": "ORD-6001",
    "customer_id": "CUST-501",
    "order_status": "PAID",
    "total_amount": 125.0,
    "currency": "USD",
    "updated_at": "2026-05-10T15:02:10Z"
  },
  "source": {
    "version": "2.6.0.Final",
    "connector": "mysql",
    "name": "commerceflow_sales",
    "ts_ms": 1778425330000,
    "snapshot": "false",
    "db": "sales_db",
    "table": "orders",
    "server_id": 1001,
    "file": "mysql-bin.000003",
    "pos": 894
  },
  "op": "u",
  "ts_ms": 1778425330145
}

Meaning of Each Field and What Happens on a DELETE

  • op: The captured operation code: "r" (read during initial snapshot), "c" (create / INSERT), "u" (update / UPDATE), or "d" (delete / DELETE).
  • before and after: Full row images before and after the change.
    • On "c" or "r", before is null and after holds the new row.
    • On "u", both hold the pre-update and post-update row states.
    • On "d", before holds the row that was just deleted and after is null.
  • The Tombstone Record Following a DELETE: Immediately after emitting the op = "d" record, Debezium emits a second Kafka message with the same key (order_id = "ORD-6002") and a null payload. This special tombstone marker tells Kafka's Log Compaction cleaner that it can eventually purge all historical records for that key from disk. Consumers must handle value is None gracefully without throwing a NullPointerException or AttributeError.
  • source.ts_ms vs. top-level ts_ms: source.ts_ms is the timestamp when the change occurred in the MySQL binlog (Event Time), whereas the top-level ts_ms is the timestamp when Debezium processed the record (Processing Time).

Useful Console Commands to Inspect Topics, Messages, and Consumer Groups

# 1. List topics created in the Kafka broker
docker exec -it cf-kafka-kraft /opt/kafka/bin/kafka-topics.sh \
  --bootstrap-server localhost:9092 --list

# 2. Read all messages from the CDC topic from the beginning, printing keys
docker exec -it cf-kafka-kraft /opt/kafka/bin/kafka-console-consumer.sh \
  --bootstrap-server localhost:9092 \
  --topic commerceflow_sales.sales_db.orders \
  --from-beginning \
  --property print.key=true

# 3. Inspect committed offsets and lag for a consumer group
docker exec -it cf-kafka-kraft /opt/kafka/bin/kafka-consumer-groups.sh \
  --bootstrap-server localhost:9092 \
  --group cg-sales-state-materializer \
  --describe

Step 5: Self-Contained Python Consumer and State Materializer

To consolidate a CDC stream into an up-to-date analytical state dictionary or table, a consumer must handle:

  1. All four operations (r, c, u, d).
  2. Tombstone records (value is None).
  3. Duplicate redeliveries after restarts by comparing the binlog coordinate (source.file, source.pos).

The following self-contained Python module processes Debezium CDC events and verifies the exact state transitions with automated assertions:

from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple


@dataclass
class MaterializedOrder:
    order_id: str
    customer_id: str
    order_status: str
    total_amount: float
    currency: str
    last_binlog_pos: Tuple[str, int]
    source_ts_ms: int


class DebeziumOrderStateMaterializer:
    """
    Maintains the current materialized state of orders from a Debezium CDC stream,
    handling snapshots ('r'), inserts ('c'), updates ('u'), deletes ('d'),
    tombstone records (None), and duplicate deliveries.
    """

    def __init__(self) -> None:
        self.orders_by_id: Dict[str, MaterializedOrder] = {}
        self.last_position_by_id: Dict[str, Tuple[str, int]] = {}

    def apply_cdc_record(self, key: Dict[str, Any], value: Optional[Dict[str, Any]]) -> str:
        order_id = key["order_id"]

        # 1. Safely ignore tombstone records emitted after a DELETE
        if value is None:
            return "TOMBSTONE_IGNORED"

        source = value.get("source", {})
        binlog_pos: Tuple[str, int] = (
            str(source.get("file", "")),
            int(source.get("pos", 0)),
        )

        # 2. Idempotency check against redeliveries or repeated binlog reads
        prev_pos = self.last_position_by_id.get(order_id)
        if prev_pos is not None and binlog_pos <= prev_pos and source.get("snapshot") != "true":
            return "STALE_OR_DUPLICATE_IGNORED"

        op = value.get("op")
        if op in {"r", "c", "u"}:
            after = value["after"]
            self.orders_by_id[order_id] = MaterializedOrder(
                order_id=after["order_id"],
                customer_id=after["customer_id"],
                order_status=after["order_status"],
                total_amount=float(after["total_amount"]),
                currency=after["currency"],
                last_binlog_pos=binlog_pos,
                source_ts_ms=int(source.get("ts_ms", 0)),
            )
            self.last_position_by_id[order_id] = binlog_pos
            return f"UPSERTED_{op.upper()}"

        if op == "d":
            self.orders_by_id.pop(order_id, None)
            self.last_position_by_id[order_id] = binlog_pos
            return "DELETED"

        raise ValueError(f"Unknown Debezium operation: '{op}'")


if __name__ == "__main__":
    materializer = DebeziumOrderStateMaterializer()

    # Realistic sequence of records delivered from commerceflow_sales.sales_db.orders
    cdc_stream: List[Tuple[Dict[str, Any], Optional[Dict[str, Any]]]] = [
        # 1. Initial snapshot ('r') of ORD-6001
        (
            {"order_id": "ORD-6001"},
            {
                "before": None,
                "after": {
                    "order_id": "ORD-6001",
                    "customer_id": "CUST-501",
                    "order_status": "PENDING",
                    "total_amount": 120.0,
                    "currency": "USD",
                },
                "source": {"file": "mysql-bin.000003", "pos": 154, "ts_ms": 1778425200000, "snapshot": "true"},
                "op": "r",
            },
        ),
        # 2. Insert ('c') of ORD-6002
        (
            {"order_id": "ORD-6002"},
            {
                "before": None,
                "after": {
                    "order_id": "ORD-6002",
                    "customer_id": "CUST-502",
                    "order_status": "PENDING",
                    "total_amount": 75.5,
                    "currency": "USD",
                },
                "source": {"file": "mysql-bin.000003", "pos": 512, "ts_ms": 1778425300000, "snapshot": "false"},
                "op": "c",
            },
        ),
        # 3. Update ('u') of ORD-6001 to PAID ($125.00)
        (
            {"order_id": "ORD-6001"},
            {
                "before": {"order_id": "ORD-6001", "order_status": "PENDING", "total_amount": 120.0},
                "after": {
                    "order_id": "ORD-6001",
                    "customer_id": "CUST-501",
                    "order_status": "PAID",
                    "total_amount": 125.0,
                    "currency": "USD",
                },
                "source": {"file": "mysql-bin.000003", "pos": 894, "ts_ms": 1778425330000, "snapshot": "false"},
                "op": "u",
            },
        ),
        # 4. Duplicate redelivery of the previous update (pos 894) after a network retry
        (
            {"order_id": "ORD-6001"},
            {
                "before": {"order_id": "ORD-6001", "order_status": "PENDING", "total_amount": 120.0},
                "after": {
                    "order_id": "ORD-6001",
                    "customer_id": "CUST-501",
                    "order_status": "PAID",
                    "total_amount": 125.0,
                    "currency": "USD",
                },
                "source": {"file": "mysql-bin.000003", "pos": 894, "ts_ms": 1778425330000, "snapshot": "false"},
                "op": "u",
            },
        ),
        # 5. Delete ('d') of ORD-6002 followed by its Tombstone record (None)
        (
            {"order_id": "ORD-6002"},
            {
                "before": {"order_id": "ORD-6002", "order_status": "PENDING", "total_amount": 75.5},
                "after": None,
                "source": {"file": "mysql-bin.000003", "pos": 1240, "ts_ms": 1778425360000, "snapshot": "false"},
                "op": "d",
            },
        ),
        (
            {"order_id": "ORD-6002"},
            None,
        ),
    ]

    outcomes = [materializer.apply_cdc_record(k, v) for k, v in cdc_stream]
    assert outcomes == [
        "UPSERTED_R",
        "UPSERTED_C",
        "UPSERTED_U",
        "STALE_OR_DUPLICATE_IGNORED",
        "DELETED",
        "TOMBSTONE_IGNORED",
    ]
    assert list(materializer.orders_by_id.keys()) == ["ORD-6001"]
    assert materializer.orders_by_id["ORD-6001"].order_status == "PAID"
    assert materializer.orders_by_id["ORD-6001"].total_amount == 125.0
    print("Materialized state from CDC verified successfully:", materializer.orders_by_id)

From Technical CDC to a Decoupled Streaming Data Product: The Transactional Outbox Pattern

As we saw at the start of the article, the topic commerceflow_sales.sales_db.orders mirrors the physical columns of the internal orders table in MySQL. It is ideal for the Sales domain's own internal ingestion pipeline, but it should not be exposed directly to other domains as a cross-domain business event stream.

How, then, does the Sales domain publish a clean semantic event (OrderConfirmed) to the rest of the mesh without falling back into fragile dual writes? Through the Transactional Outbox pattern:

-- Atomic transaction inside the Sales microservice when confirming an order
START TRANSACTION;

-- 1. Update the domain's private operational table
UPDATE sales_db.orders
SET order_status = 'CONFIRMED', updated_at = UTC_TIMESTAMP()
WHERE order_id = 'ORD-6001';

-- 2. Insert the contracted business event inside the exact same local transaction
INSERT INTO sales_db.outbox_events (
    event_id,
    aggregate_type,
    aggregate_id,
    event_type,
    payload,
    occurred_at
) VALUES (
    'evt_9001_order_confirmed',
    'Order',
    'ORD-6001',
    'OrderConfirmed',
    JSON_OBJECT(
        'order_id', 'ORD-6001',
        'customer_id_hash', 'cust_hash_501',
        'total_amount', 125.00,
        'currency', 'USD'
    ),
    UTC_TIMESTAMP()
);

COMMIT;

Why Transactional Outbox Works (and What Not to Confuse It With)

  1. Atomic Consistency with the Operational Database: Because orders and outbox_events live in the same MySQL database, either both changes commit together on COMMIT or both roll back on ROLLBACK. It is impossible to confirm the order without recording the outbound event in outbox_events.
  2. Semantic Decoupling: Debezium tails the binlog of outbox_events (optionally applying Debezium's Outbox Event Router transformation) and routes only the clean business JSON to the public product topic (sales.order-events.v1), keeping the internal orders table completely hidden.
  3. Do Not Confuse Transactional Outbox with Event Sourcing:
    • In Transactional Outbox, the orders table still stores the mutable current state of the order, while outbox_events acts as a transactional staging table for outbound integration events.
    • In Event Sourcing, there is no mutable current-state table as the primary store: the append-only sequence of domain events is itself the system's primary source of truth.
  4. Do Not Confuse Transactional Outbox with Automatic End-to-End Exactly-Once Delivery: If Kafka Connect crashes right after publishing an outbox event to Kafka but before flushing its internal offset, it will re-read the binlog entry on startup and publish evt_9001_order_confirmed a second time. Downstream consumers must still deduplicate by event_id.

Three Scenarios with Different CDC and Kafka Decisions in the Mesh

Scenario 1: Internal Analytical Replication Within the Owning Domain (Sales)

  • Context: The Sales data engineering team needs to sync its operational MySQL database into its own sales-orders S3/Iceberg analytical table with a latency of a few minutes.
  • Decision: Use Debezium CDC directly on sales_db.orders writing to a private internal topic (internal.sales.cdc.orders) and consolidate c, u, d operations inside the Sales boundary before publishing the analytical table.
  • Why: Because the CDC topic never crosses domain boundaries, the Sales team owns both the MySQL table and the CDC consumer; when a column changes in MySQL, the same team updates its internal consolidator in Lockstep.

Scenario 2: Cross-Domain Business Event Publication (Sales -> Inventory and Fraud)

  • Context: The Inventory and Fraud domains need to react within seconds whenever an order is confirmed or cancelled in Sales.
  • Decision: Implement Transactional Outbox in MySQL (sales_db.outbox_events) captured by Debezium into the governed public topic sales.order-events.v1, registered in the catalog as a Streaming Data Product with an explicit owner, contract, and ACLs.
  • Why: Insulates Inventory and Fraud from any internal refactoring of MySQL tables inside Sales.

Scenario 3: When a Simpler Alternative Is Sufficient (Nightly Store Directory Sync)

  • Context: The Store Operations domain maintains a MySQL table of 150 physical retail locations that changes once or twice a month and feeds weekly reports.
  • Decision: Run a simple daily batch export to S3 Parquet, without configuring binlog streaming, Debezium connectors, or Kafka topics.
  • Why: Operating 24/7 Kafka Connect tasks and binlog monitoring for 150 nearly static rows adds operational complexity with zero business return.

Responsibility Boundaries and Moving from Lab to Production (Amazon MSK)

In a production Data Mesh environment (for example, running on Amazon Managed Streaming for Apache Kafka — Amazon MSK and MSK Connect), responsibilities split cleanly across three roles:

  • Self-Serve Data Platform Team: Manages broker clusters, connector templates, authentication (IAM / mTLS), encryption in transit and at rest, and catalog/monitoring integration.
  • Producer Domain Team (Sales): Owns its outbox_events table (or internal CDC consolidation), guarantees the semantics and quality of published events, and maintains its contract.
  • Consumer Teams (Inventory, BI): Operate their own Consumer Groups, manage their committed offsets, and enforce idempotent deduplication by event_id.

Always remember: a Kafka topic by itself is only a transport pipe. Turning it into a governed Streaming Data Product requires formal schema validation, versioned event contracts, and automated compatibility enforcement—which we will build in the next article using Schema Registry and AsyncAPI.


Using AI Assistants to Configure and Troubleshoot Kafka and Debezium Pipelines

AI assistants can help configure connector transforms and diagnose partitioning issues, provided a human engineer verifies database privileges and ordering guarantees.

Prompt 1: Generating Debezium Configuration with the Outbox Event Router SMT

Context: In the Sales domain of CommerceFlow, we have a MySQL table "sales_db.outbox_events" with columns: event_id (VARCHAR PK), aggregate_type (VARCHAR), aggregate_id (VARCHAR), event_type (VARCHAR), payload (JSON), occurred_at (TIMESTAMP).
We want to use Debezium MySQL Connector 2.6 in Kafka Connect to capture inserts on "sales_db.outbox_events" and route them to the topic "sales.order-events.v1" using "aggregate_id" (order_id) as the Kafka partition key.

Task: Generate the JSON configuration for the Debezium connector including the Single Message Transform (SMT) "io.debezium.transforms.outbox.EventRouter". Explain what each SMT property does and how to purge old rows from "outbox_events" in MySQL without causing Debezium to emit delete events ("op": "d") to downstream consumers.
  • What a human must verify: Confirm that the housekeeping strategy for deleting processed rows from outbox_events aligns with the connector configuration so DELETE operations on the outbox table are ignored rather than forwarded.

Prompt 2: Diagnosing Out-of-Order Events for the Same Order in Apache Kafka

Context: Our Kafka topic "sales.order-events.v1" has 6 partitions. A consumer in the Inventory domain reports that for several orders it receives "OrderCancelled" before "OrderCreated", even though they occurred in the correct order 2 seconds apart in the source database.

Task: Analyze the 3 most likely technical root causes in the producer or connector configuration (covering null/random partition keys, changing the topic's partition count on the fly, or retries without enable.idempotence / max.in.flight.requests.per.connection) and provide the exact CLI commands or tests to verify which cause is occurring.
  • What a human must verify: Inspect the live topic with kafka-console-consumer --property print.key=true --property print.partition=true to confirm whether all events for the same order_id are landing in the exact same partition number.

Practical Exercises

Exercise 1: Consumer Group Partition Assignment and Parallelism

The topic sales.order-events.v1 has 4 partitions (P0, P1, P2, P3). Two different domain teams subscribe to it:

  • The Inventory team starts 4 consumer instances configured with group.id = "cg-inventory-reservations".
  • The Analytics team starts 2 consumer instances configured with group.id = "cg-analytics-live-sales".

When the Sales domain publishes an OrderConfirmed event to partition P2:

  1. How many instances inside cg-inventory-reservations receive that event?
  2. How many instances inside cg-analytics-live-sales receive that same event?
  3. What happens if Inventory starts a fifth consumer instance inside cg-inventory-reservations while the topic still has 4 partitions?

Exercise 2: The Pitfall of Using offset as a Primary Key or Global Ordering Attribute

A developer writes a consumer that reads from all 4 partitions of commerceflow_sales.sales_db.orders and inserts each message into an analytical table using record.offset as the primary key (PRIMARY KEY (kafka_offset)). The developer also assumes that if message A has offset = 105 and message B has offset = 106, message B occurred after message A in the business.

Explain the two severe bugs that will occur in production and how the primary key and temporal ordering must be designed instead.

Exercise 3: Handling DELETE Operations and Tombstone Records in the Consumer

Look at events 5 and 6 in the Python materializer test stream (op = "d" for ORD-6002 followed by a message with value = None). Explain:

  1. Why Debezium emits a record with op = "d" and before = {...} first, followed immediately by a second record with the same key and value = None.
  2. What would happen to the materialized state if the consumer ignored op = "d" events and only processed records where after is non-null.

Solutions to the Exercises

Solution to Exercise 1

  1. In cg-inventory-reservations: Exactly 1 instance receives the event (the instance assigned partition P2).
  2. In cg-analytics-live-sales: Exactly 1 instance receives the event (in that 2-instance group, each instance is assigned 2 partitions, and the one holding P2 processes it). Both consumer groups receive a complete independent copy of the stream.
  3. If a 5th instance joins cg-inventory-reservations: Because the topic has only 4 partitions and a single partition cannot be read concurrently by two consumers within the same group, the 5th instance remains idle as a warm standby in case one of the other four instances fails.

Solution to Exercise 2

  1. Primary key collisions (offset is not globally unique): Offsets are independent counters per partition. Partition P0, P1, P2, and P3 will each have a record with offset = 105. Using offset alone as a primary key overwrites or rejects records from other partitions.
  2. Invalid cross-partition ordering assumption: offset = 106 on Partition P1 may have occurred three hours ago (if P1 had low traffic), whereas offset = 5000 on Partition P0 occurred one second ago. Offsets are comparable only within the same (topic, partition). To order business facts or resolve state conflicts, use the source Event Time (source.ts_ms / occurred_at) or the transaction log coordinates (file, pos) for the same entity key.

Solution to Exercise 3

  1. Why two records are emitted when a row is deleted:
    • The first record (op = "d", before = {...}, after = null) notifies live consumers that the entity was deleted while providing its final known attributes in before for auditing or metric reversal.
    • The second record (tombstone: same key, value = null) is a marker for Kafka's Log Compaction cleaner, signaling that all prior records for that key can be permanently removed once the delete retention period (delete.retention.ms) expires.
  2. What happens if the consumer ignores op = "d": Deleted orders remain forever as active "ghost" records inside the consumer's materialized state dictionary or table, inflating counts and causing permanent drift against the operational database.

Key Takeaways and Decision Criteria

When building real-time pipelines with Apache Kafka and Change Data Capture (CDC) in a Data Mesh architecture, apply these core criteria:

  • Always key messages by the domain entity ID: Use the aggregate identifier (order_id) as the Kafka partition key so all events for the same order land in the same partition and preserve strict ordering.
  • Never expose raw internal CDC topics across domains: Use Debezium on operational tables as an internal domain ingestion mechanism, or pair it with the Transactional Outbox pattern when publishing stable business events (OrderConfirmed) to other domains in the mesh.
  • Build idempotent, delete-aware consumers: Explicitly handle r, c, u, and d operations, filter out null tombstones safely, and deduplicate by event_id or binlog position.
  • Remember that Kafka transports bytes, while contracts define the product: A topic in Kafka or Amazon MSK is the transport layer; in the next article we will add formal schemas and event contracts to guarantee safe evolution across domains.

Loading conversation…

Keep learning