๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Kafka CDC: Debezium, Outboxes and Exactly-Once Sinks

Apache KafkaCDCโญ Premium

Kafka CDC: Debezium, Outboxes and Exactly-Once Sinks

Senior level ยท Two proven patterns for getting database truth onto the log, and what breaks in production.

Prerequisites

  • !Database write-ahead logs and binlog basics
  • !Kafka Connect distributed mode

What You'll Learn

  • 1Compare Debezium CDC against the transactional outbox pattern
  • 2Configure a Debezium connector with the right snapshot and offset behavior
  • 3Handle schema evolution without breaking downstream consumers
  • 4Achieve effectively-once delivery into a non-transactional sink

Two patterns, one goal

Change data capture moves database changes onto a log so downstream systems never poll the source again. There are two patterns that survive production. Debezium reads the database write-ahead log directly, so the application needs no changes and ordering follows the database commit order. The transactional outbox pattern has the application write the change into an outbox table inside the same transaction as the business row, then a relay publishes to Kafka.

ConcernDebezium on the WALTransactional outbox
Application changesNoneWrite outbox row in same transaction
OrderingCommit order from the logCommit order from the shared table
Capture completenessEverything in the log, including DDLOnly what the application chooses to emit
OperationsLog retention, connector state, upgradesRelay process or connector plus table growth
Multi-tenant databasesOne connector per databasePer-service ownership, easier to shard

Debezium is the right default when the database is third-party or shared and you cannot touch application code. The outbox wins when you own the application and want explicit control over what leaves the database, because it captures only domain events and never leaks an internal column rename into the pipeline.

Configuring a Debezium connector

{
  "name": "orders-connector",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "orders-db.internal",
    "database.port": "5432",
    "database.user": "debezium",
    "database.password": "${DB_PASSWORD}",
    "database.dbname": "orders",
    "database.server.name": "ordersdb",
    "table.include.list": "public.orders,public.order_items",
    "slot.name": "debezium_orders",
    "publication.name": "debezium_pub",
    "plugin.name": "pgoutput",
    "snapshot.mode": "initial",
    "offset.storage.topic": "connect-offsets",
    "offset.flush.interval.ms": "5000",
    "tombstones.on.delete": "true",
    "transforms": "unwrap",
    "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
    "transforms.unwrap.add.fields": "op,ts_ms,source.ts_ms"
  }
}

The slot and publication names are persistent server-side objects. Deleting connector state without dropping the replication slot leaves a slot that never advances, and Postgres will eventually fill the disk with WAL segments that the dead slot still holds. The cleanup procedure is part of the runbook, not an afterthought.

snapshot.mode=initial takes a consistent snapshot on first start and then tails the log. Once offsets are flushed, subsequent restarts skip the snapshot. snapshot.mode=never is appropriate for replicas where another snapshot has already been taken, and schema_only for very large tables where only structure matters downstream.

The outbox relay, and why it is simpler than it looks

-- Application writes the business row and the event atomically
BEGIN;
  INSERT INTO orders (id, customer_id, total) VALUES (42, 7, 99.50);
  INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload, created_at)
  VALUES (gen_random_uuid(), 'order', '42', 'OrderCreated',
          '{"orderId":42,"total":99.50}', now());
COMMIT;
// Relay polls the outbox and publishes, then deletes or marks rows
@Transactional
public void relayBatch() {
    List rows = outboxRepository.findUnpublished(500);
    for (OutboxRow row : rows) {
        producer.send(new ProducerRecord(
            "orders.events",
            row.getAggregateId(),
            row.getPayload(),
            headersFor(row)
        )).get(5, TimeUnit.SECONDS);
        outboxRepository.markPublished(row.getId());
    }
}

The atomicity is the entire point: the event cannot exist without the row, and the row cannot exist without the event, because they share a transaction. The relay then turns that guarantee into at-least-once delivery, and idempotent consumers on the other side close the gap. Debezium can also read the outbox table as a connector, which removes the custom relay but keeps the atomicity benefit.

Ordering, keys and the per-partition rule

Ordering is guaranteed per partition and nowhere else. Key CDC events by the natural aggregate id so all changes to one order land on the same partition and are written in commit order. If the key is null, Kafka picks a partition and the downstream consumer can observe an update before the insert that preceded it.

โš ๏ธSchema changes are the real production risk

A column rename or type change flows through Debezium as a schema change event. Consumers pinned to an older schema version fail on the first matching record. Use a Schema Registry with compatibility modes and a dead-letter path for records that no longer deserialize, and test schema changes against consumers before promoting them.

Exactly-once into a transactional sink

// Effectively-once into a transactional sink
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
props.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "orders-sink-" + instanceId);
props.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, "read_committed");

producer.initTransactions();
while (true) {
    ConsumerRecords records = consumer.poll(Duration.ofMillis(500));
    producer.beginTransaction();
    try {
        for (ConsumerRecord r : records) {
            jdbc.upsert(r.topic(), r.key(), r.value());
        }
        producer.sendOffsetsToTransaction(offsetsFor(records), consumer.groupMetadata());
        producer.commitTransaction();
    } catch (Exception e) {
        producer.abortTransaction();
        consumer.seekToBeginning(records.partitions());
    }
}

read_committed on the consumer matters as much as idempotence on the producer. Without it, a consumer can read records from an aborted transaction that was written to the topic and then rolled back, and no amount of sink-side idempotency undoes processing a write that never officially happened.

Schema evolution in a CDC pipeline

Change data capture surfaces every schema change the database makes, including the ones nobody thought to announce. A column added by a DBA for a one-off report, a type widened from integer to bigint, a nullable constraint relaxed during a migration: all of these flow through Debezium as schema change events and land in the same topic as the domain records. Without a registry and an explicit compatibility policy, the first downstream consumer to deserialize the new shape fails, and the failure surfaces as a deserialization error on a record that was, from the database's point of view, perfectly ordinary.

The defense is a schema registry with a compatibility mode set per subject before the first CDC record is ever written. BACKWARD is the usual choice for a topic with consumers that upgrade on their own schedule, because it guarantees that a consumer holding the previous schema can still read records written by the new one. When consumers cannot be upgraded in lockstep, transitive backward compatibility covers a consumer that is more than one version behind, at the cost of restricting what changes are allowed in any single version.

The operational discipline that makes this work is treating schema changes as deployments. A migration script that adds a column should also register the new schema version against the subject and run the compatibility check before the migration is applied to production. Teams that separate the database migration from the schema registration inevitably ship a column that the registry rejects, or worse, a column the registry accepts but a consumer cannot parse because the compatibility level was checked after the fact.

Failure modes that only appear under load

CDC pipelines behave differently under peak load than under a demo, and the differences follow a predictable pattern. The replication slot advances slower than the database writes when the connector cannot keep up, which shows up first as rising slot lag and only later as consumer lag downstream. By the time consumer lag is visible, the slot may already be hours behind and the disk may be filling with retained WAL segments, so slot lag is the metric to alert on, not consumer lag.

The second load-dependent failure is the outbox relay falling behind because it polls too infrequently or in batches too small to absorb a traffic spike. A relay tuned for a steady trickle of events will fall behind during a flash sale, and because the outbox table keeps growing while it does, the next poll takes longer as the table scan widens, which makes the backlog worse in a feedback loop. The fix is to make the relay's batch size adaptive and to alert on outbox table age, not just on relay throughput.

The third failure is ordering under partitioned writes. When a CDC source writes to multiple partitions of the outbox or the source table has concurrent writers, commit order within a partition holds but cross-partition order does not, and a consumer that assumed global order will occasionally observe an update before the insert that preceded it. Keying by aggregate id confines the ordering guarantee to what Kafka actually provides, and the consumer design should assume per-key order and nothing more.

Common Mistakes

Deleting connector state without dropping the replication slot

Fix: Drop the slot explicitly before recreating an instance. An orphaned slot holds WAL segments until the disk fills, and the database will eventually reject writes.

Producing CDC events with a null key

Fix: Key by the aggregate id so every change for one entity lands on the same partition and preserves commit order.

Running the sink without read_committed isolation

Fix: Set the consumer isolation level to read_committed, otherwise records from aborted transactions are processed as if they had committed.

Letting outbox tables grow without a retention policy

Fix: Mark rows published and delete them on a schedule, or compact the outbox with a tombstone policy. An unbounded outbox table becomes a database incident.

Best Practices

  • Choose Debezium when you cannot change the application; choose the outbox when you can
  • Key every CDC topic by aggregate id and document the per-partition ordering guarantee downstream
  • Register Avro or Protobuf schemas with the registry and pick an explicit compatibility mode per subject
  • Version and test connector configuration through the same review process as application code
  • Alert on replication slot lag and outbox table age; both fail silently until they are critical

Interview Questions

Q1: Debezium or transactional outbox: how do you decide?

Debezium when the application cannot be changed or the database is shared; it reads the write-ahead log and captures everything. The outbox when you own the code, because it writes the event in the same transaction as the business row and emits only domain events.

Q2: Why is keying CDC events important?

Ordering is per partition only. Keying by aggregate id keeps all changes for one entity on the same partition in commit order; a null key scatters them and consumers can see an update before its insert.

Q3: What goes wrong if the replication slot is orphaned?

Postgres retains WAL segments for the dead slot, so the disk fills and the database eventually rejects writes. Cleanup means dropping the slot explicitly before recreating connector state.

Q4: How do you get effectively-once delivery into a non-transactional sink?

Use an idempotent producer with a transactional id, wrap the sink write and offset commit in a producer transaction, and abort and re-seek on failure. The sink upsert must be idempotent on the key as well.

Q5: What does tombstones.on.delete control?

Whether a delete produces a tombstone record after the key value. Compacted topics need the tombstone to actually remove the key, so leave it enabled whenever the topic is compacted.

Key Takeaways

  • Debezium reads the database log with no application change; the outbox writes events in the same transaction as the row
  • Key by aggregate id, because only per-partition ordering is guaranteed
  • Schema evolution with a registry and a compatibility mode is what keeps CDC pipelines alive through a column rename
  • Effectively-once sinks pair an idempotent transactional producer with a read_committed consumer
  • Replication slots and outbox tables are the two things that fail silently and then become outages
๐Ÿ”’

Premium Content

Kafka CDC: Debezium, Outboxes and Exactly-Once Sinks

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement