A relational table is already a sequence of committed states, but batch extraction observes only the snapshot available at query time. Change data capture (CDC) observes committed row changes. The two methods solve different reliability and latency problems, and a robust pipeline usually combines them: snapshot or incremental batch for the base, then CDC for continuous change.

Debezium reads a database transaction log and publishes change envelopes to Kafka topics. Amazon MSK provides the durable transport, but neither layer knows whether a downstream lake table, warehouse, or index is correct.

Choose the source and acquisition mode

Use incremental batch when:

  • the source does not expose reliable log CDC;
  • a bounded extraction is acceptable;
  • a monotonic update watermark exists;
  • tables are mutable and the loader can re-read overlap safely.

Use CDC when:

  • committed inserts, updates, and deletes are material;
  • latency measured in seconds is required;
  • the source log has sufficient retention;
  • the schema and transaction-log privileges can be operated securely.

An incremental query needs an overlap because a timestamp is not a transaction key:

SELECT id, account_id, status, updated_at
FROM orders
WHERE updated_at >= :last_high_watermark - INTERVAL '5 minutes'
  AND updated_at < :batch_end
ORDER BY updated_at, id;

Upsert by primary key in the sink. The overlap intentionally produces duplicates so the loader can recover from a crash and avoid a committed-row gap. Do not use only updated_at if equal timestamps are possible.

Connector deployment

Deploy Kafka Connect in at least two worker tasks, with a distributed configuration that persists offsets, connector configuration, and status in internal Kafka topics. On MSK, MSK Connect can host the Debezium plugin where the desired database/version is supported. A self-managed Connect fleet is useful when plugin versioning, custom converters, networking, or release control cannot fit the managed connector.

A PostgreSQL connector configuration is conceptually:

{
  "name": "orders-postgres-cdc",
  "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
  "tasks.max": "1",
  "database.hostname": "orders-db.internal",
  "database.port": "5432",
  "database.user": "${file:/etc/connect/secrets:db_user}",
  "database.password": "${file:/etc/connect/secrets:db_password}",
  "database.dbname": "orders",
  "database.server.name": "orders-prod",
  "topic.prefix": "orders-prod",
  "plugin.name": "pgoutput",
  "slot.name": "orders_msk_cdc",
  "table.include.list": "public.orders,public.order_items",
  "publication.autocreate.mode": "filtered",
  "snapshot.mode": "initial",
  "snapshot.max.threads": "4",
  "decimal.handling.mode": "precise",
  "tombstones.on.delete": "true",
  "schema.history.internal.kafka.bootstrap.servers": "BROKER_LIST",
  "schema.history.internal.kafka.topic": "orders.schema.history",
  "key.converter": "org.apache.kafka.connect.json.JsonConverter",
  "value.converter": "org.apache.kafka.connect.json.JsonConverter",
  "key.converter.schemas.enable": "false",
  "value.converter.schemas.enable": "false"
}

Use Avro or another governed schema when the platform supports it; JSON is shown for an inspectable example. Store secrets in a Connect secret provider rather than committing them. Debezium’s source-task count for one database log is typically one, because task parallelism cannot split one ordered logical log arbitrarily.

The initial snapshot and live log are coordinated so that the connector can transition without an unobserved hole. Choose initial, no_data, or a specialized mode deliberately. A very large table can require an incremental snapshot mechanism while ordinary CDC continues, so test disk, log retention, and database load before production.

Topics and change envelopes

A conventional topic is:

orders-prod.public.orders
orders-prod.public.order_items
orders.schema.history

A simplified Debezium event is:

{
  "before": {"id": 1842, "status": "PENDING", "total_cents": 12900},
  "after": {"id": 1842, "status": "PAID", "total_cents": 12900},
  "source": {
    "version": "2.6.0",
    "connector": "postgresql",
    "name": "orders-prod",
    "db": "orders",
    "schema": "public",
    "table": "orders",
    "txId": 481902,
    "lsn": 482910034
  },
  "op": "u",
  "ts_ms": 1618574400211,
  "transaction": null
}

The key identifies the row, usually the primary key. The before and after payloads are not enough to make a cross-table product consistent: the sink needs transaction IDs or a different consistency protocol. Debezium transaction metadata can group table changes when the database and connector configuration support it. Preserve log sequence numbers for debugging and deduplication.

Deletes may produce a delete envelope followed by a null tombstone. A consumer must apply the delete, not cast the null to an ordinary empty row.

Snapshot, transaction log, Debezium, MSK, and replayable Spark or Flink consumers

Spark Structured Streaming is often appropriate for compacted micro-batch lake updates:

changes = (
    spark.readStream.format("kafka")
    .option("kafka.bootstrap.servers", BROKERS)
    .option("subscribe", "orders-prod.public.orders")
    .option("startingOffsets", "latest")
    .load()
)

def merge_batch(batch, batch_id):
    rows = parse_debezium(batch)
    (DeltaTable.forName(spark, "silver.orders")
      .alias("target")
      .merge(rows.alias("source"),
             "target.id = source.id")
      .whenMatchedUpdateAll()
      .whenNotMatchedInsertAll()
      .execute())

query = (
    changes.writeStream
    .foreachBatch(merge_batch)
    .option("checkpointLocation", "s3://checkpoint/orders")
    .start()
)

This sample omits delete handling and transaction grouping intentionally; add a predicate for tombstones and deletes before production. Spark checkpoints hold consumer progress. The target commit must be idempotent across a repeated micro-batch, or a failed checkpoint can duplicate side effects.

Flink is appropriate for low-latency transformations and transaction-aware joins:

CREATE TABLE order_changes (
  `key` BYTES,
  `value` STRING,
  topic STRING METADATA VIRTUAL,
  `partition` INT METADATA VIRTUAL,
  `offset` BIGINT METADATA VIRTUAL
) WITH (
  'connector' = 'kafka',
  'topic' = 'orders-prod.public.orders',
  'properties.bootstrap.servers' = 'BROKER_LIST',
  'format' = 'raw'
);

Parse the envelope with a deterministic UDF or a proper Debezium format, preserve source lsn, and use Flink checkpoints plus a two-phase-committing sink where exact sink semantics require it.

Replay, deduplication, and consistency

A source event can be replayed because:

  • a producer did not learn that its send completed;
  • a connector restarts before storing its new offset;
  • a consumer checkpoint is older than a sink commit;
  • an operator deliberately resets to an earlier offset.

The sink therefore stores the source identity:

CREATE TABLE cdc_seen (
  source_name STRING,
  log_sequence BIGINT,
  transaction_id BIGINT,
  event_kind STRING,
  first_seen_at TIMESTAMP,
  PRIMARY KEY (source_name, log_sequence)
);

For row tables, sequence-aware upsert is also useful: never apply an older LSN after a newer row state. For at-least-once sinks, commit business rows and processed source positions in one transaction where possible. For object storage, write deterministic output paths or a manifest keyed by source offsets.

Replay is not equivalent to snapshot recovery. Before resetting consumer offsets:

  1. determine the requested source boundary and transaction semantics;
  2. verify that source topic retention still contains it;
  3. back up or version the current sink state;
  4. reset the consumer group to the saved offsets, not earliest by habit;
  5. replay at controlled throughput;
  6. compare row counts and checksums over a fixed source boundary.

If Kafka retention is shorter than the required recovery horizon, restore a raw archive or re-snapshot. Never ask the database log to act as an indefinite archive.

Failure behavior

Failure Immediate behavior Recovery
Connect worker loss Other workers reassign tasks Restart from stored Kafka Connect offsets
Database log deleted Connector fails at missing position Restore slot/log or re-snapshot; reconcile duplicates
Schema change Connector may reject or evolve topic contract Pause, register compatible schema, resume
Consumer failure Lag grows, database log remains independent Restore checkpoint/state; replay retained events
Sink duplicate Same change applied twice Source-ID uniqueness or sequence-aware upsert

A common hidden hazard is a replication slot whose consumer is paused: PostgreSQL retains WAL until it fills disk. Alert on slot lag, free disk, and connector restart loops together. Alerting only on Kafka consumer lag misses the source pressure.

Operational guidance

Measure at least:

  • source log lag and retained size;
  • Connect task state, restart count, and records by operation;
  • Kafka topic lag by consumer group and partition;
  • invalid-schema and dead-letter rate;
  • end-to-end freshness from source commit timestamp;
  • reconciliation difference over a rolling table checksum sample.

Useful initial targets are end-to-end p95 freshness under 60 seconds for online consumers, connector task failure recovered within 10 minutes, zero unowned internal Connect partitions, and a replay that completes inside the next batch outage window. Size those targets from the source transaction rate, record width, and required replay horizon.

The architectural rule is straightforward: the source database is authoritative, the database log is the ordered capture surface, MSK is a replayable transport, and the sink is independently verified. Treating any one of them as a substitute for the others turns a transient infrastructure fault into a silent data correctness problem.