Skip to content

Change Data Capture: Stream Database Changes from the Log

How to stream every committed row change from a database's write-ahead log to search, caches and warehouses, with no dual writes and no lost updates.

21 min readSystem pattern

Publish every committed change to a source database as an ordered event stream, read from the database's transaction log, so that downstream systems such as search indexes, caches and warehouses stay in sync without the application writing to them directly.

Change data capture (CDC) reads a database's own transaction log and turns each committed insert, update and delete into an event that other systems consume. You stop asking application code to remember to update the search index, the cache and the warehouse. The database already records every change in order, and CDC publishes that record. This guide follows one invented system. Pantrio is a grocery delivery service whose catalog lives in Postgres. Its search index drifted from the truth, and customers ordered items that were already out of stock. You will see how a logical replication slot, a connector and a Kafka topic fixed it. You will also see how to make consumers idempotent with log positions, which numbers and settings matter, and how to explain the design in an interview.

The problem

A situation where the obvious design starts to hurt.

Pantrio's catalog service owns a Postgres table, store_product, with about 3.1 million rows: one per product per store across 4,200 partner stores. Store point-of-sale systems push stock updates, which peak around 1,500 row writes per second in the evening. Shoppers search through OpenSearch, and product pages read prices from Redis.

The catalog API kept those copies fresh with dual writes. After committing to Postgres, it called OpenSearch and deleted the Redis key. If the call failed, it pushed the work onto an in-memory retry list.

Three things went wrong in the same month. First, a six-minute rolling restart of OpenSearch made the post-commit calls fail. The retry list lived in API pod memory, and a deploy recycled those pods, so about 41,000 index updates disappeared. Search went on showing those items in stock for days. Second, the weekly price job ran plain SQL against Postgres. It never passed through the API, so neither the index nor the cache ever saw the new prices. Third, two concurrent updates to the same row could reach OpenSearch in the opposite order from their commit order, which left the older stock count in place.

The result was evening orders full of items the store could not supply, followed by substitutions and refunds. The root cause was structural. Every writer had to remember to notify every reader, the notification was not atomic with the commit, and nothing guaranteed ordering.

The solution

What the pattern proposes.

Make the database log the single source of change events. Postgres already writes every committed change to its write-ahead log (WAL), in commit order. With wal_level=logical, a logical replication slot decodes that log into row-level changes. The slot also remembers how far its consumer has read, so the WAL is kept until the consumer confirms it.

Pantrio created a publication covering store_product and price_list, plus a slot named cdc_catalog using the pgoutput plugin. A Debezium connector running on Kafka Connect reads the slot. On first start it takes a consistent snapshot of existing rows, emitted as op r. It then streams inserts, updates and deletes as op c, u and d. Each event carries the before and after row images, the table, the primary key and the source LSN (log sequence number). Events go to one Kafka topic per table with 24 partitions, keyed by primary key, so all changes to one row land in one partition, in order.

Each downstream system is now an independent consumer group. The search indexer writes to OpenSearch using version_type=external with the LSN as the version, so a replayed or older event is rejected instead of overwriting newer data. The cache invalidator deletes Redis keys. The warehouse loader merges batches every minute. Consumers commit their Kafka offsets only after the sink write succeeds. Delivery is therefore at-least-once, and the LSN versioning makes duplicates harmless.

The API no longer talks to OpenSearch or Redis at all. The weekly price job, a manual psql fix and a future service written in another language all produce events automatically, because they all write to the same log. When OpenSearch restarts, events wait in Kafka for up to the 7-day retention window, and the indexer catches up afterwards.

An everyday analogy

The same idea, outside software.

Think of a busy hospital ward where nurses used to phone the pharmacy, the kitchen and the billing office every time they changed a patient's chart. Some calls were missed during shift change, and the night locum never knew to call anyone. The ward switched to a different system. Every chart change is written to one carbon-copy ledger at the nurses' station, a clerk photocopies new pages every few minutes, and each department reads its own copy at its own pace. Nobody has to remember to notify anyone. A department that was closed for an hour reads the pages it missed. Each page carries a line number, so a department that reads a page twice knows it has already acted on it.

Structure

The pieces and how they relate.

Pantrio catalog CDC: writes go only to Postgres; the connector decodes the WAL into Kafka; each sink consumes independently.Shop apps calls Catalog API (read and update). Catalog API calls Postgres primary (commit). Price and ops jobs calls Postgres primary (bulk SQL). Postgres primary sends to Debezium connector (logical decoding). Debezium connector sends to Kafka catalog.public.* (change events). Kafka catalog.public.* sends asynchronously to Search indexer. Kafka catalog.public.* sends asynchronously to Cache invalidator. Kafka catalog.public.* sends asynchronously to Warehouse loader. Search indexer calls OpenSearch (versioned upsert). Cache invalidator calls Redis (DEL key). Warehouse loader calls Analytics warehouse (MERGE). Shop apps calls OpenSearch (search).Shop appsweb and mobileshoppersCatalog APIwrites Postgres onlyPrice and opsjobsweekly SQL, POSstock syncPostgres primarywal_level=logical,slot cdc_catalogDebeziumconnectorKafka Connect,pgoutputSlot guardrailmax_slot_wal_keep_size=50GB,alert at 5GB lagKafkacatalog.public.*24 partitions, keyedby PK, 7dSearch indexerconsumer group idxCache invalidatorconsumer group cacheWarehouse loaderconsumer group dwh,60s batchesIdempotent sinksLSN used as externalversionOpenSearchproducts indexRedisprice and stockcacheAnalyticswarehouseMERGE by primary keyread and updatecommitbulk SQLlogical decodingchange eventsversioned upsertDEL keyMERGEsearch
Pantrio catalog CDC: writes go only to Postgres; the connector decodes the WAL into Kafka; each sink consumes independently.

Participants

Source database and WAL
Postgres stays the only place writers touch. Its write-ahead log already records every committed change in commit order, including changes from scripts and manual fixes that bypass the application.
Logical replication slot and publication
The publication selects which tables are captured. The slot decodes the WAL into row changes and records the confirmed position (confirmed_flush_lsn). Postgres keeps WAL until the slot confirms it, which is both the durability guarantee and the main operational risk.
CDC connector
Debezium on Kafka Connect takes the initial consistent snapshot, then streams decoded changes as structured events carrying op, before, after, table, primary key and source LSN. It acknowledges the LSN back to the slot only after Kafka has accepted the events.
Change topics
One Kafka topic per table, partitioned by primary key so changes to a single row stay ordered. Retention of 7 days lets any consumer fall behind or rebuild without touching the database.
Consumers and sinks
Independent consumer groups for search, cache and warehouse. Each applies events idempotently, using the LSN as a monotonic version, and commits its Kafka offset only after the sink write succeeds.
Schema registry
Stores the Avro or JSON schema for each table's events, so a column added in Postgres produces a compatible new schema version instead of breaking consumers silently.

Pseudocode

The solution to the scenario, language-neutral.

// Connector side (Debezium does this for you)
on start:
  if no stored offset:
    begin REPEATABLE READ snapshot, note slot LSN S
    for each row in published tables: emit {op: r, key, after: row, lsn: S}
  loop:
    changes = slot.read_from(stored_lsn)
    for change in changes in commit order:
      emit to topic(change.table), partition = hash(change.primary_key)
    when Kafka acks the batch:
      store offset; slot.confirm(last_lsn)   // lets Postgres recycle WAL

// Consumer side (you write this)
loop:
  batch = kafka.poll(partition, max = 500 events)
  latest = {}
  for e in batch:
    id = e.table + ":" + e.key
    if id not in latest or e.lsn > latest[id].lsn: latest[id] = e
  for e in latest.values():
    if e.op == d: sink.delete(id, version = e.lsn)        // keeps a tombstone version
    else:         sink.upsert(id, e.after, version = e.lsn) // rejected if version <= stored
  kafka.commit(max offset in batch + 1)   // only after all sink writes succeed
  // crash before commit means redelivery; versions make the replay a no-op

The code

The same solution in TypeScript, Python and PHP.

type Op = "c" | "u" | "d" | "r";

interface ChangeEvent {
  op: Op;
  table: string;
  key: string;
  lsn: number;
  after: Record<string, unknown> | null;
  offset: number;
}

interface VersionedSink {
  upsert(id: string, doc: Record<string, unknown>, version: number): Promise<boolean>;
  remove(id: string, version: number): Promise<boolean>;
}

interface BatchResult {
  applied: number;
  skipped: number;
  committedOffset: number;
}

// Applies one partition's batch idempotently, then commits the Kafka offset.
class ChangeApplier {
  constructor(
    private readonly sink: VersionedSink,
    private readonly commit: (nextOffset: number) => Promise<void>,
  ) {}

  async applyBatch(events: ChangeEvent[]): Promise<BatchResult | null> {
    if (events.length === 0) return null;

    const latest = new Map<string, ChangeEvent>();
    let maxOffset = -1;
    for (const e of events) {
      maxOffset = Math.max(maxOffset, e.offset);
      const id = `${e.table}:${e.key}`;
      const prev = latest.get(id);
      if (!prev || e.lsn > prev.lsn) latest.set(id, e);
    }

    let applied = 0;
    let skipped = 0;
    for (const [id, e] of latest) {
      let ok: boolean;
      if (e.op === "d") {
        ok = await this.sink.remove(id, e.lsn);
      } else {
        if (e.after === null) throw new Error(`event at offset ${e.offset} has no row image`);
        ok = await this.sink.upsert(id, e.after, e.lsn);
      }
      if (ok) applied++;
      else skipped++;
    }

    // Commit only after every sink write succeeded. A crash before this line
    // causes redelivery, and the LSN versions turn the replay into a no-op.
    await this.commit(maxOffset + 1);
    return { applied, skipped, committedOffset: maxOffset + 1 };
  }
}

// Stands in for OpenSearch with version_type=external.
class InMemoryIndex implements VersionedSink {
  readonly docs = new Map<string, { version: number; doc: Record<string, unknown> | null }>();

  async upsert(id: string, doc: Record<string, unknown>, version: number): Promise<boolean> {
    return this.write(id, doc, version);
  }

  async remove(id: string, version: number): Promise<boolean> {
    return this.write(id, null, version); // tombstone keeps the version
  }

  private write(id: string, doc: Record<string, unknown> | null, version: number): boolean {
    const current = this.docs.get(id);
    if (current && current.version >= version) return false;
    this.docs.set(id, { version, doc });
    return true;
  }
}

async function main(): Promise<void> {
  const index = new InMemoryIndex();
  const applier = new ChangeApplier(index, async (offset) => {
    console.log(`commit next offset ${offset}`);
  });

  const first = await applier.applyBatch([
    { op: "r", table: "store_product", key: "17:4401", lsn: 100, after: { stock: 12, price_cents: 349 }, offset: 0 },
    { op: "u", table: "store_product", key: "17:4401", lsn: 140, after: { stock: 0, price_cents: 349 }, offset: 1 },
    { op: "d", table: "store_product", key: "17:5120", lsn: 150, after: null, offset: 2 },
  ]);
  console.log(first);

  // An older event redelivered after a consumer rebalance is rejected.
  const replay = await applier.applyBatch([
    { op: "u", table: "store_product", key: "17:4401", lsn: 120, after: { stock: 5, price_cents: 349 }, offset: 1 },
  ]);
  console.log(replay, index.docs.get("store_product:17:4401"));
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

When to use it

Situations where it pays off.

  • Several systems hold derived copies of one database's data, such as a search index, caches, a warehouse or another service's read model, and they drift from the source.

    CDC makes the commit itself the trigger. No copy depends on application code remembering to call it, and nothing is lost when a downstream system is briefly unavailable.

  • Data is changed by paths you do not control: batch SQL jobs, migrations, admin consoles, or a legacy monolith you cannot easily modify.

    The log sees every committed change regardless of who wrote it. Polling the application or adding hooks would miss these paths.

  • You need deletes and intermediate states, not just the latest value, for example to feed an audit trail or a warehouse with history.

    Polling an updated_at column cannot see deleted rows and collapses several updates between polls into one. The log records each change individually.

  • You are migrating data to a new store or splitting a service out of a monolith and need the old and new stores kept in sync during the cutover.

    A snapshot followed by streaming gives you a copy that stays continuously current, so you can switch reads over gradually and roll back without a big-bang copy.

  • Poor fit: the consumer needs business-level events such as OrderPlaced with intent and context, rather than row diffs.

    Row changes expose your internal schema and lack meaning. Use a transactional outbox, which CDC can then relay, so the published contract is an event you designed, not a table layout.

How to implement it

Steps to introduce it in existing code.

  1. Enable logical decoding on the source: set wal_level=logical and leave headroom in max_replication_slots and max_wal_senders. Give each captured table a primary key, or the connector cannot key events or produce meaningful updates and deletes.

  2. Create a publication listing only the tables downstream systems need, then let the connector create the slot. Fewer tables means less decoding work and a smaller blast radius when schemas change.

  3. Bound the slot's disk usage with max_slot_wal_keep_size (Pantrio uses 50GB). Alert on lag from pg_replication_slots when retained WAL passes 5GB, long before the limit invalidates the slot.

  4. Run the connector with an initial snapshot, publish one topic per table keyed by primary key, register schemas in a schema registry with backward compatibility, and set topic retention long enough to cover a weekend outage (7 days).

  5. Write each consumer to be idempotent: collapse a batch to the newest event per key, write with the LSN as an external version, store delete tombstones with their version, and commit offsets only after the sink write succeeds.

  6. Remove the dual writes from the application only after the CDC consumers have run in shadow mode and a reconciliation job comparing row counts and checksums reports zero drift for several days.

  7. Rehearse the bad days: a primary failover, a connector restart mid-snapshot, a dropped column and a re-snapshot of one table. Document the runbook for each.

Pros and cons

What you gain and what you pay.

Pros

  • Writers cannot forget to notify downstream systems. Every committed change, from any path, appears in the stream.
  • Changes to one row arrive in commit order, and the source LSN gives consumers a ready-made monotonic version for idempotent writes.
  • Downstream outages no longer affect the write path. Events wait in Kafka, and consumers catch up at their own pace.
  • Adding a new consumer is a configuration change. It reads the topic from the beginning or triggers a snapshot, with no change to the catalog service.
  • Low load on the source compared with polling: decoding reads the WAL Postgres already writes instead of running repeated range queries on hot tables.

Cons

  • Consumers are coupled to your table schema. Renaming a column is now a breaking change for every downstream team unless you transform or version events.
  • Operational weight: a replication slot, Kafka Connect, a schema registry and topic retention all need monitoring, and the slot can fill the primary's disk if neglected.
  • Downstream copies are eventually consistent, typically hundreds of milliseconds behind and much more during catch-up, so read-your-own-writes through search is not guaranteed.
  • Row events lack business intent. A stock column dropping to zero does not say whether the item sold out or a store manager corrected a count.

Trade-offs

Decisions you'll have to make, each with its price.

  • Log-based CDC instead of polling an updated_at column every 30 seconds

    You gainCaptures deletes and every intermediate update, sees changes from all writers, and delivers in under a second at Pantrio's 1,500 writes per second.

    You payRequires wal_level=logical, a replication slot to monitor, and Kafka Connect plus a schema registry to operate, where polling needs only a cron job and an index.

  • REPLICA IDENTITY DEFAULT instead of FULL on store_product

    You gainWAL volume stays small, because updates log only the primary key as the before image, which is all the sinks need.

    You payConsumers do not get full before images. Unchanged TOASTed columns, such as a large description, arrive as a placeholder in updates, so the indexer must use a partial update rather than replacing the whole document.

  • 24 partitions keyed by primary key, instead of a single partition per table

    You gainOrdering is preserved per row while the indexer scales to 24 parallel consumers, enough to catch up a 6-hour backlog in roughly 20 minutes.

    You payNo global order across rows. A consumer that needs a multi-row invariant, such as a price list and its items changing together, cannot rely on seeing them in transaction order.

  • At-least-once delivery with LSN-versioned sinks instead of Kafka transactions end to end

    You gainWorks with any sink that supports conditional writes, such as OpenSearch external versions, a SQL WHERE version < ?, or Redis Lua scripts, and keeps consumers simple.

    You payEvery sink must store a version per key, including tombstones for deletes, which costs storage and needs a cleanup policy for old tombstones.

  • Initial snapshot through the connector instead of a separate bulk export

    You gainThe snapshot and the stream share one consistent LSN boundary, so there is no gap or overlap between the backfill and live changes.

    You paySnapshotting 3.1 million rows holds a long-running transaction for about 25 minutes, which delays vacuum on the primary. Pantrio schedules it off-peak or uses incremental snapshots in chunks of 10,000 rows.

How it fails

What goes wrong in production and how to prevent it.

  • The connector is down over a weekend, the slot pins WAL, and the primary's disk fills up, taking down writes.

    What to doSet max_slot_wal_keep_size=50GB so Postgres invalidates the slot instead of filling the disk. Alert when retained WAL exceeds 5GB or confirmed_flush_lsn stops advancing for 10 minutes. Have a runbook to recreate the slot and re-snapshot if it is invalidated.

  • A primary failover promotes a standby that has no copy of the logical slot, so changes made around the failover are never captured.

    What to doOn Postgres 17, create the slot with failover enabled and turn on sync_replication_slots on the standby. On older versions, treat failover as a re-snapshot event and run a reconciliation job comparing per-store row counts and checksums between Postgres and OpenSearch.

  • A column is dropped or renamed in a migration and the search indexer crashes on every event from that point, stalling the partition.

    What to doEnforce backward compatibility in the schema registry so incompatible schemas are rejected at deploy time. Route events that fail deserialisation or validation to a dead-letter topic after 3 attempts, with an alert, instead of blocking the partition.

  • After a consumer rebalance, an older update for a row is reapplied and overwrites newer data in the index.

    What to doWrite with the source LSN as an external version so the sink rejects anything not newer than what it holds. Store delete tombstones with their version so a late upsert cannot resurrect a deleted product.

  • A bulk price job updates 900,000 rows in one transaction, and the indexer floods OpenSearch with writes and triggers search latency alerts.

    What to doCollapse each poll batch to the newest event per key, cap consumer concurrency, and use the OpenSearch bulk API with batches of 500. For known bulk jobs, run them in chunks of 10,000 rows so changes arrive steadily rather than as one burst.

  • Delete events are lost because Kafka log compaction removed the tombstones before a new consumer finished reading the topic.

    What to doSet delete.retention.ms longer than the longest expected catch-up, for example 7 days. Have new consumers bootstrap from a fresh snapshot instead of relying on compacted history.

In a system design interview

When to bring it up and how to explain it.

Bring it up when a design has one source-of-truth database and several derived stores, such as search, caches, analytics or another service's read model, or when the interviewer asks how you keep them in sync. It is also the natural answer to "what happens if the call to Elasticsearch fails after you commit?"

What you could say

I wouldn't have the service write to Postgres and then to the search index and the cache. That's a dual write, and it drifts the first time the second write fails or someone runs SQL directly against the database. Instead I'd use change data capture. Postgres already writes every committed change to its WAL in order. I'd enable logical decoding, create a replication slot for just the catalog tables, and run a Debezium connector that snapshots the existing rows and then streams inserts, updates and deletes into Kafka, one topic per table, keyed by primary key so each row's changes stay ordered. Search, cache invalidation and the warehouse each become their own consumer group. Delivery is at-least-once, so each sink writes with the source LSN as an external version and rejects anything older, and consumers commit offsets only after the write succeeds. Operationally, the risk I watch is the slot: if the connector stalls, Postgres keeps WAL, so I'd cap it with max_slot_wal_keep_size and alert on lag in gigabytes. Reads from search become eventually consistent, typically sub-second.

Likely follow-ups

How do you handle a user who updates a product and immediately searches for it?

Search is eventually consistent, so I would not promise read-your-writes through it. For the editing user, I'd read the product page from Postgres, or overlay their just-saved change on the client. If it really mattered, the API could wait until the indexer's applied LSN passes the commit LSN, with a 2-second timeout.

Why not use a transactional outbox instead?

An outbox is better when consumers need business events with intent, because you design the payload. Raw CDC is better for keeping derived copies of data in sync, and it catches writes that bypass the application. I often combine them: the service writes outbox rows, and CDC on the outbox table publishes them.

How do you add a new consumer six months later?

Topic retention is 7 days, so I would not replay from Kafka. I'd trigger an incremental snapshot of the tables it needs, which interleaves chunked reads with live changes, and the new sink's version checks resolve any overlap between the snapshot rows and streamed updates.

What breaks if the database fails over?

Before Postgres 17, logical slots exist only on the primary, so a promoted standby has no slot and changes around the failover can be lost. I'd use failover slots on 17, or otherwise treat failover as a trigger to recreate the slot, re-snapshot, and run a reconciliation check.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Why not just poll for rows where updated_at is newer than the last run?

Polling misses hard deletes, collapses several updates between polls into one, and depends on every writer setting updated_at correctly. Pantrio's weekly price job did not. It also adds repeated range scans on a hot table, and rows committed late by long transactions can carry a timestamp earlier than your last watermark, so they are skipped. Log-based CDC has none of these gaps.

Is CDC exactly-once?

Not end to end. The connector and consumers can each replay events after a crash, so treat delivery as at-least-once. You get effectively-once results by making sinks idempotent: write with the LSN or a row version as an external version, and use upserts and merges keyed by primary key instead of appends.

How do I stop consumers breaking when the table schema changes?

Register schemas with backward compatibility so additive changes, such as a new nullable column, pass through. For renames or type changes, add the new column, backfill it, let consumers adopt it, then drop the old one. If many teams consume a table, publish a curated topic through a transform or an outbox instead of exposing raw rows.

Does CDC work with MySQL or other databases?

Yes. The mechanism is the same: read the database's replication log. MySQL uses the binlog in row format, and MongoDB uses change streams over the oplog. The details differ, such as how positions are stored and how snapshots lock, but the consumer design with keyed topics and idempotent versioned writes stays the same.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.