FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Change Data Capture (CDC) & Debezium

Debezium reads committed database log changes and routes transactional outbox rows to Kafka so stored state and emitted events agree.

Freshness: current•15 min read•Data Engineering and Databases
Full Technical Reference Document

Mental model

Change data capture reads committed changes from a database log and turns them into an ordered event stream. The transactional outbox makes a business update and its event row part of the same database transaction; Debezium observes that row from the commit log and routes it to Kafka. Consumers still need idempotency because a connector can replay an event after an uncertain acknowledgement.

Theory

Consider a service that updates an order in PostgreSQL and then publishes OrderPaid to Kafka. If it commits the row and the process crashes before publishing, downstream services never hear about the payment. If it publishes first and the database transaction later rolls back, consumers act on a payment that the source of truth does not contain. The two systems do not share one atomic commit, so rearranging the two calls only changes which failure is possible.

Instead, insert the business change and an outbox row in one database transaction. If the transaction commits, both rows are visible in the write-ahead log; if it rolls back, neither is. A Debezium connector reads committed log records using a replication position such as a PostgreSQL LSN, filters changes to the outbox table, and emits an event through Kafka Connect. The outbox event router can use the aggregate type to select a topic and the aggregate ID as the Kafka key. Keying related events together preserves their order within a partition, which is the ordering guarantee Kafka provides.

This is log-based change capture, not a poller that repeatedly queries every changed row. Snapshot mode may first establish an initial table view, then the connector continues from a log position. Schema changes, connector restarts, topic compaction, and retention policy all affect what can be reconstructed, so the connector offset and database log retention must be monitored as production state.

A concrete transaction and replay

Suppose order 481 changes from authorized to paid. The application writes that new status and inserts an outbox event with a stable event ID in the same transaction. Debezium observes the committed insert at LSN 0/16B6C50 and publishes one record keyed by 481. If the connector loses its network after Kafka accepted the record but before its source offset is durable, it may publish that record again after restart. The stable event ID lets each consumer suppress the repeated delivery without losing a later, distinct OrderPaid event.

At 1,200 events per second and an average encoded event size of 1.4 KiB, the connector emits roughly 1,680 KiB/s before protocol overhead. If downstream Kafka is unavailable for 12 minutes, a first-order estimate for retained log volume is 1,680 KiB/s × 720 s = 1,209,600 KiB, about 1.15 GiB. The sizing relation is:

VWAL≈λWAL×ToutageV_{WAL} \approx \lambda_{WAL} \times T_{outage}

V_WAL is retained write-ahead-log volume in KiB, lambda_WAL is the database log generation rate in KiB/s, and T_outage is the period without log consumption in seconds. The real WAL budget must include unrelated database writes, replication slot behavior, bursts, and safety headroom. A stalled logical replication slot can retain WAL and consume disk even if the connector's Kafka lag looks like the primary symptom.

Consumers should commit their own state change and a processed-event marker atomically. A unique constraint on the event ID can make a replay a no-op. This gives one business effect despite at-least-once transport; it does not mean the connector delivers exactly one physical Kafka record.

Trade-offs

Log-based capture reads the database's committed change stream and avoids repeated table scans, but a connector outage can retain database log segments and requires careful slot and schema-history operations. Polling an outbox table gives the application explicit query ownership but adds polling delay, indexes, and cleanup coordination. The transactional outbox makes the database commit reliable; it does not remove Kafka duplicates, cross-system transactions, or consumer-side ordering decisions.

Failure modes and misconceptions

Monitor the connector's source lag, last committed source offset, error and retry counts, schema history, Kafka producer health, database WAL growth, and outbox retention. Alert on the age of the oldest unprocessed log position and on disk bytes held by replication slots. An outbox table that is never cleaned up grows indefinitely; deleting rows before the connector has durably advanced can instead destroy recoverable events. Use a cleanup policy tied to connector progress or a retention window that exceeds the recovery objective.

FailureDurable evidence to inspectRecovery action
Connector restarts after publish but before offset commitEvent ID and connector source offsetReplay, then deduplicate at the consumer
Database log grows during a sink outageReplication slot restart LSN and filesystem free spaceRestore the sink or deliberately advance the slot only after accepting data loss
An outbox row changes after insertionConnector error and row historyTreat rows as append-only; represent corrections as new events

Decision scenario

A connector is 11 minutes behind after a Kafka outage, and PostgreSQL still has 14 GiB of free disk. The team should estimate WAL growth from the measured database log rate and remaining disk, restore the Kafka sink, and verify source-position advancement before cleaning outbox rows. Advancing the replication slot to recover disk is a data-loss decision, not a routine lag fix; preserve the affected LSN and reconcile downstream state if that choice is unavoidable.

The outbox payload is a versioned event contract. Keep it small enough to avoid turning every consumer into a replica of the entire database row, and include only data the downstream domain needs. If a payload schema evolves, publish a compatible version and retain the event ID, aggregate key, and event type needed for routing and idempotency.

Learning outcomes

  • Explain how a transactional outbox prevents the business row and event row from committing separately.
  • Trace the connector's source position through Kafka publication and replay.
  • Design a consumer inbox key and outbox retention policy for at-least-once delivery.

Implementation pattern

The transaction below writes a versioned order state and an immutable event row together. In a real service, the order update should verify the expected prior version so concurrent writers cannot emit an event for a transition that did not occur.

sql
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
status text NOT NULL,
version bigint NOT NULL
);
CREATE TABLE outbox_event (
id uuid PRIMARY KEY,
aggregatetype text NOT NULL,
aggregateid text NOT NULL,
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders VALUES (481, 'authorized', 7);
BEGIN;
UPDATE orders
SET status = 'paid', version = version + 1
WHERE order_id = 481 AND version = 7;
INSERT INTO outbox_event (id, aggregatetype, aggregateid, type, payload)
SELECT gen_random_uuid(), 'orders', order_id::text, 'OrderPaid',
jsonb_build_object('orderId', order_id, 'version', version, 'status', status)
FROM orders
WHERE order_id = 481 AND status = 'paid' AND version = 8;
COMMIT;

The update and insert must affect the expected number of rows in application code; if the version predicate matches nothing, roll back rather than emitting an event. Configure the connector to read only the outbox table and route by aggregate type. Give consumers an inbox table keyed by event ID when their side effect is a database update that must be atomic with deduplication.

Business row and outbox row commit together
Database WAL records the committed transaction
Debezium advances the source log position
Outbox router selects topic and aggregate key
Consumer deduplicates by immutable event ID
Conceptual teaching model synthesized from:debezium-docs,apache-kafka-docs
Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next