The usual way to get data out of a database and into everything else is to poll it. Run SELECT * FROM orders WHERE updated_at > :last_seen every few seconds, publish what you find, remember the high-water mark, repeat. It works until it does not, and it fails in ways that are hard to see: it misses hard deletes entirely (a deleted row has no updated_at to find), it misses intermediate states (a row updated three times between polls shows up once, so you lose the two it passed through), it hammers the primary with scan load, and it adds latency equal to the poll interval. The moment you need deletes, full change history, and sub-second freshness, polling is finished.

Change data capture replaces the poll by reading the one place that already records every change in order: the database’s write-ahead log. Every committed insert, update, and delete is in the WAL, in commit order, because that is how the database makes itself durable and recoverable. Tail that log, turn each logged row change into an event, and stream it. The hard part is not reading the WAL - a replication connection hands it to you. The hard part is everything after: keeping per-primary-key ordering intact while fanning changes out across a partitioned bus read by many sinks at different speeds, and delivering each change exactly once even though the WAL reader, the bus, and every sink can each crash and restart independently. This post builds that pipeline end to end.

The core problem stated once: a change event for a given row must reach every sink exactly once and in the same order the database committed it, through a pipeline of independently failing stages that each want to parallelize for throughput - and parallelism is the natural enemy of ordering. Everything below is a consequence of resolving that tension.

Functional Requirements (FR)

In scope:

  • Capture every committed row change from the source. Inserts, updates, and deletes on tracked tables, in commit order, including hard deletes. Each change event carries the table, the operation, the primary key, and the row image (new values for insert/update, old values for delete, and ideally both before and after for updates).
  • Tail the write-ahead log, not the tables. Read changes from the database’s replication stream (the WAL / binlog / redo log), so capture is low-overhead, complete, and ordered, with no application code publishing events.
  • Snapshot plus stream. On first connect to a table (or a newly tracked table), take a consistent initial snapshot of existing rows, then switch to streaming incremental changes from the exact WAL position the snapshot corresponds to, with no gap and no overlap.
  • Deliver to heterogeneous sinks. A data warehouse, a search index, a cache, another microservice’s database, an analytics stream - each consuming the same change stream independently, at its own pace, with its own schema and write semantics.
  • Preserve per-primary-key ordering end to end. For a single row, consumers must see insert -> update -> update -> delete in exactly that order. Ordering across unrelated keys does not need to be global.
  • Exactly-once delivery semantics. Each change is applied to each sink exactly once - no duplicates, no drops - even across crashes of the reader, the bus, or a sink.
  • Schema change handling. When a tracked table’s schema changes (add column, change type), the pipeline must carry that change through so downstream consumers can adapt rather than break.

Explicitly out of scope (name it so you own the scope):

  • Transforming / enriching data. Joins, aggregations, and business logic over the change stream are a downstream stream-processing concern; we deliver faithful row-level change events and stop there.
  • The message bus internals. We build on a partitioned, replicated, append-only log (Kafka-shaped) and treat its durability and ordering as given; designing that log is its own problem.
  • Bidirectional / multi-master sync. We capture from a source and fan out to sinks one way. Conflict resolution for writes flowing both directions is a different (much harder) design.
  • The sink databases themselves. We define how we write to a sink and what the sink must support (idempotency), but we do not design the warehouse or the search engine.
  • Querying the change history. Retaining and serving change events as a queryable event store is an event-sourcing feature adjacent to this; we note where it hooks in but do not build the query layer.

The decision that drives everything: the WAL is an ordered, durable, replayable record of every committed change, identified by a monotonic log position (LSN). The whole pipeline is a machine for moving that ordered record outward without losing its order or its exactly-once-ness, using the LSN as the one offset that ties capture, transport, and delivery progress together.

Non-Functional Requirements (NFR)

  • Scale: a busy source cluster committing ~50,000 row changes/sec sustained (bursts to 200K/sec during batch jobs and backfills), across hundreds of tables, feeding tens of heterogeneous sinks each re-reading the full relevant stream. Reads exceed writes because every change is consumed by many sinks and re-read on sink rebuilds.
  • Latency: end-to-end (source commit to visible at a caught-up sink) in the low hundreds of milliseconds to low single-digit seconds. This is near-real-time, not batch. Capture lag (WAL head minus reader position) is the primary health metric and must stay bounded.
  • Availability: 99.9%+ on capture. A reader, bus broker, or sink failure must not lose a single committed change and must not stall capture for more than the few seconds it takes to fail over. The source database’s own availability is sacred - CDC must never threaten it.
  • Consistency: per-primary-key total order preserved from source commit to every sink. Within a sink, the applied state for a row converges to the source’s state. Across unrelated keys, ordering is not guaranteed and does not need to be.
  • Durability: very high. Once the source commits a change, the pipeline must deliver it even through crashes. No acknowledged change is ever lost. The reader’s committed WAL position is itself durable, so a restart never re-reads from zero or skips ahead.
  • Low source impact: reading the WAL must add minimal load to the primary - no table scans on the hot path, bounded replication slot retention, and backpressure that never blocks the source’s own commits.

The tension to state up front: ordering wants a single serial stream; throughput and independent sinks want parallelism and partitioning; and a partitioned bus does not preserve order across partitions. We resolve it by making the primary key the partition key everywhere, so all changes for one row travel one ordered partition from reader to sink, while different rows parallelize freely. Exactly-once is then bought with the LSN as an idempotency token plus a transactional or idempotent sink write - never with a distributed commit per event.

Back-of-the-Envelope Estimation (BoE)

Real numbers with the arithmetic, because they set the partition count, the slot retention, and the storage budget.

Change throughput and bandwidth:

Sustained change rate:   50,000 changes/sec (peak 200K/sec on backfills)
Average change event:    ~1 KB (key + before/after row image + metadata)
Write bandwidth into bus: 50K/sec * 1 KB = 50 MB/sec sustained (200 MB/sec peak)

Fan-out on read: ~10 sinks each read the full relevant stream + occasional rebuilds
Read bandwidth:  50 MB/sec * ~10 = ~500 MB/sec outbound from the bus

Reads dominate writes by the fan-out factor. Size the bus network and page cache for ~500 MB/sec, not 50.

Bus partition count (the ordering + parallelism unit):

Per-partition sustainable throughput ~ 10K-30K changes/sec (append + replicate + fetch).
To absorb 50K/sec (and 200K peak):  200K / ~20K = ~10 partitions minimum per hot topic.
Add headroom + parallel sink consumers -> pick ~24-48 partitions per high-volume table.
One partition -> one ordered sink task, so partition count caps per-table sink parallelism.
Ordering is per-partition, and we route by primary key, so this is also the key-order unit.

WAL / replication slot retention (the source-side risk):

The source retains WAL from the reader's confirmed position to the head.
If the reader lags by L seconds at 50K/sec * 1 KB = 50 MB/sec:
   L = 60s  -> 3 GB of WAL retained on the primary
   L = 1 hour -> 180 GB retained   (disk-fills-the-primary territory)
=> Lag is not just a latency metric; unbounded lag fills the source's disk and
   can take the primary down. Bounding reader lag is a hard safety requirement.

Change-event storage in the bus (the replay window):

Write volume:   50 MB/sec = 86,400 * 50 MB ≈ 4.3 TB/day of change events.
Retention:      7-day replay window (sink rebuilds) -> 4.3 * 7 = ~30 TB (one copy).
Replication factor 3: 30 TB * 3 = ~90 TB raw in the bus for the change stream.
Compacted "latest state per key" topics are far smaller: ~ one row image per live key.

Snapshot cost (one-time per table, but it dominates on day one):

A 500M-row table at ~1 KB/row = ~500 GB to read once for the initial snapshot.
At a throttled ~50K rows/sec snapshot rate: 500M / 50K = 10,000s ≈ 2.8 hours.
Snapshot must run WITHOUT blocking live commits and WITHOUT a long-held table lock,
and must hand off to streaming at an exact LSN. This is a first-class design concern.

The headline shape: ~50 MB/sec of ordered change events in, ~500 MB/sec out after fan-out, tens of TB of replayable history in the bus, and two source-side dangers that a plain queue does not have - unbounded replication-slot retention filling the primary’s disk, and a multi-hour initial snapshot that must not lock the source. Size for fan-out, per-key partitioning, bounded lag, and a safe snapshot.

High-Level Design (HLD)

Four stages in a line, each independently scalable and independently failing, tied together by the LSN. The capture stage is a connector that holds a replication slot on the source and tails its WAL, decoding each logged row change into a structured change event. The transport stage is a partitioned, replicated, append-only bus (Kafka-shaped) that the capture stage produces into, partitioned by primary key so per-key order survives. The delivery stage is a set of per-sink consumers that read their partitions in order and write to their sink idempotently. A coordination layer stores connector offsets (committed LSN), partition leadership, and sink consumer offsets durably.

  SOURCE DB                 CAPTURE (connector)            TRANSPORT (partitioned bus)         DELIVERY (per-sink)
 ┌──────────┐              ┌─────────────────────┐        ┌──────────────────────────┐        ┌──────────────┐
 │ primary  │  logical     │  WAL reader thread   │ produce│  topic: orders           │  read  │ warehouse    │
 │ ┌──────┐ │  replication │  - hold repl slot    │ key=PK │  ┌ p0 ┐┌ p1 ┐┌ p2 ┐┌ p3 ┐│  group │  sink task   │
 │ │ WAL  │─┼─ slot/stream▶│  - decode row change │───────▶│  │PK%N││PK%N││PK%N││PK%N││───────▶│ (idempotent) │
 │ │(LSN) │ │              │  - emit change event │        │  └────┘└────┘└────┘└────┘│        └──────────────┘
 │ └──────┘ │              │  - track LSN         │        │  (append-only, RF=3, ISR)│        ┌──────────────┐
 │  tables  │              └──────────┬──────────┘        └───────────┬──────────────┘  read  │ search index │
 └──────────┘                         │                               │                  group │  sink task   │
      ▲  snapshot (consistent         │ commit confirmed LSN          │                 ───────▶│ (idempotent) │
      │  read at LSN=S, no lock)      ▼ back to source (advance slot)  │                        └──────────────┘
      └──────────────────────┐  ┌──────────────────┐                  │                        ┌──────────────┐
                             │  │ OFFSET STORE      │                  │                  read  │ cache / other│
   ┌─────────────────────────┼──┤ (connector LSN,   │                  │                 group │  microservice│
   │  COORDINATION (Raft)     │  │  snapshot marker) │                  │                ───────▶│ (idempotent) │
   │  - bus partition leaders │  └──────────────────┘   ┌──────────────┴──────────────┐         └──────────────┘
   │  - sink consumer offsets │  ┌───────────────────── │ SCHEMA REGISTRY / HISTORY   │         dead-letter topic
   │  - connector assignment  │  │ table schema per LSN, │ emits schema-change events  │◀─ poison events
   └──────────────────────────┘  └───────────────────────────────────────────────────┘

Capture flow (a committed change becomes an event):

  1. A transaction commits on the primary. The database durably appends its row changes to the WAL at a monotonically increasing log sequence number (LSN) - this already happened for the database’s own durability; CDC piggybacks on it.
  2. The connector holds a logical replication slot on the source and receives the committed changes over a streaming replication connection, in commit order, each tagged with its LSN. A slot is a server-side cursor: the source retains WAL from the slot’s confirmed position forward and will not recycle it until the connector confirms.
  3. The connector decodes each logged change into a structured change event: {table, op (c/u/d), primary_key, before, after, source_lsn, source_ts, tx_id}. It does not touch the tables - all of this comes from the log.
  4. The connector produces each event to the bus topic for that table, using the primary key as the partition key (partition = hash(pk) % N), so every change for one row lands on one partition in LSN order.
  5. Once the bus has durably accepted events up to LSN L, the connector confirms L back to the source, which advances the slot and frees WAL up to L. This is the backpressure valve and the source-safety mechanism in one.

Delivery flow (an event reaches a sink):

  1. Each sink runs a consumer group; the bus assigns partitions across the group’s members, one partition to one member at a time, so each partition is consumed in order by exactly one task.
  2. A sink task reads events from its partition in offset order (which is LSN order for that key), batches them, and applies them to the sink idempotently - keyed by primary key, using the source LSN as a version/idempotency token so a replayed event is a no-op.
  3. The sink task commits its consumer offset only after the sink write is durable, so a crash resumes from the last durably applied position.

Snapshot flow (bootstrapping a table): on first tracking a table, the connector takes a consistent snapshot - it reads existing rows as of a specific LSN S (using a repeatable-read transaction or a watermark technique, not a long table lock), emits them as synthetic read events keyed by primary key, then begins streaming the WAL from exactly S. Snapshot and stream meet at S with no gap and no duplicate.

The structural insight: the LSN is the single thread running through the whole system. It orders changes at the source, it is the partition-ordering within the bus (per key), it is the idempotency token at the sink, and the connector’s confirmed LSN is both the recovery point and the source-safety valve. Build everything around that one number.

Component Deep Dive

Four hard parts, naive-first then evolved: (1) tailing the WAL safely without threatening the source; (2) preserving per-primary-key ordering across a parallel, partitioned bus; (3) the consistent initial snapshot that hands off to streaming with no gap; (4) exactly-once delivery across independently crashing stages - the stated headline.

1. Capture: polling the tables -> tailing the WAL with a replication slot

We need every committed change, in order, including deletes, at low source cost. Where do the changes come from?

Naive approach: poll the tables on a timer

Run a query every few seconds against each table for rows changed since the last high-water mark, publish them, advance the mark.

every 5s:
   rows = SELECT * FROM orders WHERE updated_at > :last_seen ORDER BY updated_at
   for r in rows: publish(r); last_seen = max(last_seen, r.updated_at)

Where it breaks:

  • Deletes vanish. A deleted row has no updated_at and is not in the result set, so hard deletes are simply never captured. You would need soft deletes (a deleted_at flag) everywhere, which changes the application’s data model just to make CDC possible.
  • Intermediate states are lost. A row updated three times within one poll interval is read once, at its final value. The two intermediate states - which a change stream is supposed to carry - are gone. CDC that silently collapses history is not CDC.
  • Table-scan load on the primary. Every poll scans (or index-seeks and reads) changed rows on the hot primary. At scale across hundreds of tables, this is continuous query load competing with production traffic.
  • Latency floor and clock skew. Freshness is capped at the poll interval, and updated_at relies on wall-clock timestamps that can tie or go backwards, causing missed or duplicated rows at boundaries.

Polling reconstructs changes from table state and therefore loses exactly what a change stream exists to preserve: deletes and intermediate versions.

Evolved approach: logical replication slot tailing the write-ahead log

Every committed change is already written, in commit order, to the database’s write-ahead log - that is how the database guarantees durability and crash recovery. Read that. Open a logical replication slot (Postgres logical decoding, MySQL binlog with row format, Oracle LogMiner / redo), receive a stream of decoded row changes tagged with LSNs, and emit them as events.

connector:
   slot = create_logical_replication_slot("cdc_orders")   # once; durable on source
   stream = start_replication(slot, from_lsn = confirmed_lsn)
   for change in stream:                 # ordered by commit LSN, includes INSERT/UPDATE/DELETE
      evt = decode(change)               # {op, table, pk, before, after, lsn, ts, tx_id}
      bus.produce(topic=evt.table, key=evt.pk, value=evt)
      if bus_durable_up_to(L): slot.confirm(L)   # advance slot -> source frees WAL <= L

Why this is right:

  • Complete and ordered by construction. The WAL contains every committed change in commit order, so inserts, updates, and deletes are all captured, with every intermediate version, in the exact order the database committed them. Nothing is reconstructed from table state.
  • Near-zero query load on the source. Reading the WAL is a streaming replication connection - the same mechanism physical replicas use. There are no table scans, no competition with production queries on the hot path. The source barely notices a reader.
  • The slot is the durable recovery point. The slot’s confirmed LSN is stored on the source. On connector restart, streaming resumes from exactly that LSN - never re-reading from zero, never skipping ahead. The confirmed LSN is also what the connector persists in its own offset store, so the two agree.
  • Before and after images. Logical decoding (with REPLICA IDENTITY FULL on Postgres, or full row image in MySQL binlog) gives the old and new row for updates and the old row for deletes - so sinks can do keyed upserts and deletes correctly.

The danger this introduces (and must contain): the slot makes the source retain WAL from the confirmed LSN to the head. If the connector stalls (bus down, connector crashed and not restarted), WAL piles up and fills the primary’s disk - a CDC outage can take down the production database. This is the single most important operational hazard. Fixes: monitor slot lag as a page-worthy alert, set a bounded retention cap so the slot is dropped before the disk fills (accepting a re-snapshot over a dead primary), and run the connector highly available so a crashed reader fails over in seconds rather than lagging for hours. The WAL reader is cheap to run but expensive to neglect.

2. Ordering: one parallel firehose -> per-primary-key partitioning

The bus is partitioned for throughput, and sinks consume partitions in parallel. But a partitioned log only orders within a partition, and multiple reader threads and parallel producers can reorder changes. How do we keep a single row’s insert -> update -> delete in order?

Naive approach: round-robin events across partitions for maximum throughput

To spread load evenly, the connector (or multiple reader threads) produces each change to the next partition round-robin, and sinks consume all partitions in parallel.

produce(evt): partition = next_round_robin()     # balanced, fast

Where it breaks:

  • Per-key order is destroyed. An INSERT order#42 goes to partition 1, its UPDATE order#42 to partition 3, its DELETE order#42 to partition 0. Three partitions, three parallel sink tasks, no coordination - the sink can apply the delete before the insert, or the old update after the new one. The row’s final state is wrong and non-deterministic.
  • Multiple reader threads amplify it. If several threads decode and produce the WAL in parallel for throughput, even events for the same key can be produced out of commit order before they ever reach a partition.
  • No sink can recover ordering. Once events for one key are scattered across partitions consumed independently, there is no offset the sink can use to re-serialize them - the ordering information (which partition got which first) is lost.

Round-robin maximizes throughput and guarantees incorrect state for any row that changes more than once. For a change stream, ordering is not optional.

Evolved approach: partition by primary key, single-writer per key, order carried by LSN

Make the primary key the partition key: partition = hash(primary_key) % N. Every change for one row deterministically lands on the same partition, appended in the order the connector produces them. Make the connector’s production ordered per key (a single logical writer per partition, preserving commit/LSN order), and let the sink consume each partition in offset order. Different keys hash to different partitions and parallelize freely.

produce(evt): partition = hash(evt.primary_key) % N      # same key -> same partition
   within a partition, events are appended in LSN order and read in offset order.

sink task owns partition p (all keys where hash(pk)%N == p):
   for evt in read(p) in offset order:        # = LSN order for each key on p
      apply_in_order(evt)                      # insert/update/delete applied as committed

Why this is right:

  • Per-key order is preserved end to end. All changes for a row travel one partition, appended and read in LSN order, so the sink always sees insert -> update -> update -> delete in commit order. That is exactly the ordering guarantee the FR demands, and nothing weaker (global order) is needed.
  • Parallelism is retained across keys. Unrelated rows hash to different partitions, so N partitions give N-way parallel throughput and N parallel sink tasks. We get parallelism between keys and strict order within a key - the only combination that is both fast and correct.
  • Multiple WAL reader threads are tamed. If throughput needs several decode threads, they must still produce each key’s events in LSN order to its partition. The clean way: a single connector produces in commit order (the WAL is already serial), or, if sharded, shard the decode/produce work by key range so each key has exactly one producer - never round-robin, never key-crossing threads. The partition key and the producer sharding key must be the same key.
  • The LSN disambiguates within a partition. Even on the partition, each event carries its source_lsn, so a sink can detect and drop any out-of-order or replayed event by comparing against the last LSN it applied for that key (this doubles as the idempotency check in deep dive 4).

The hot-key caveat: if one key (a popular product, a hot aggregate row) takes a disproportionate share of changes, its partition hotspots one sink task. Unlike a stateless workload you cannot just salt the key, because salting would split that key’s changes across partitions and break its ordering. The honest options: keep the hot key on one partition and ensure that one sink task is fast enough (batch its writes), or, if the sink’s semantics allow collapsing (only the latest value per key matters), compact aggressively so the task processes fewer net events. Ordering for a single key is fundamentally serial - you cannot parallelize one row’s history without losing it.

3. Snapshot: lock the table -> consistent snapshot with a clean LSN handoff

A new sink, or a newly tracked table, needs the existing rows, not just future changes. The connector must read the current table contents and then switch to streaming, with no row missed and none applied twice. The subtlety is doing it on a live database without a long lock and without a gap.

Naive approach: lock the table, dump it, then start streaming

Take a table lock so nothing changes, SELECT * the whole table, publish every row, release the lock, and begin reading the WAL from “now.”

LOCK TABLE orders IN SHARE MODE       # block writes so the dump is consistent
for r in SELECT * FROM orders: publish(snapshot_event(r))
UNLOCK
start_streaming(from_lsn = current_lsn())

Where it breaks:

  • A long lock stalls the application. Snapshotting a 500M-row table takes hours (BoE: ~2.8h). Holding a table lock that long blocks production writes for hours - completely unacceptable on a live primary.
  • The gap/overlap problem at handoff. If you release the lock and then read current_lsn(), any change committed between unlock and that read is lost. If you start streaming from before the snapshot’s consistent point, changes are applied twice and may be mis-ordered against the snapshot rows. Getting the handoff off by one LSN silently corrupts the sink.
  • No concurrent streaming during the dump. While the multi-hour dump runs, live changes pile up in the WAL (slot retention grows, source disk risk from deep dive 1), and the sink is stale until the dump finishes.

A locking snapshot trades the application’s availability for a consistency it does not even achieve cleanly at the boundary.

Evolved approach: consistent read at a known LSN, or incremental watermark-based snapshot

Two evolutions, used together depending on table size.

(a) Transactional consistent snapshot (smaller tables). Open a repeatable-read / snapshot-isolation transaction, record the LSN S at which that transaction’s view is consistent, SELECT the rows inside it (readers do not block writers under MVCC), emit them as read events keyed by primary key, then stream the WAL from exactly S.

tx = begin(isolation = REPEATABLE_READ)      # MVCC snapshot, no writer blocking
S  = snapshot_lsn(tx)                         # the exact consistent point
for r in tx.query("SELECT * FROM orders"):
   bus.produce(topic="orders", key=r.pk, value=read_event(r, lsn=S))
commit(tx)
start_streaming(from_lsn = S)                 # no gap, no overlap: snapshot == state at S

Because the snapshot is the table’s state as of S and streaming begins at S, a change committed at S+1 is streamed (never missed), and a row in the snapshot is at its S value (a later streamed update supersedes it by LSN). The boundary is exact.

(b) Incremental watermark-based snapshot (huge tables, zero lock). For tables too big to snapshot in one transaction, snapshot in chunks interleaved with live streaming, using watermarks to dedupe the overlap. The connector emits a low watermark, reads a chunk by primary-key range, emits a high watermark, and while streaming it drops any streamed event for a key that was in the chunk window but whose snapshot row is older. (This is the DBLog / Debezium incremental snapshot technique.)

for chunk in primary_key_ranges(orders):      # e.g. pk in [0,10000), [10000,20000), ...
   emit_low_watermark(chunk)
   rows = SELECT * WHERE pk IN chunk           # short, bounded query - no long lock
   emit_high_watermark(chunk)
   # reconcile: within [low,high], a streamed change for a key supersedes the chunk read;
   # the LSN comparison decides the winner, so snapshot and stream never conflict.

Why this is right:

  • No long lock, source stays available. MVCC snapshots and short chunk reads never block production writes for more than a moment. A multi-hour snapshot runs concurrently with live streaming, so the sink is being fed changes the whole time rather than waiting hours.
  • Exact, gap-free handoff. The consistent snapshot LSN S (variant a) or the per-chunk watermark reconciliation (variant b) guarantees every row is captured exactly once across the snapshot/stream boundary - the off-by-one that corrupts the sink is designed out.
  • Resumable. Chunked snapshots checkpoint which key range they have reached, so a connector restart mid-snapshot resumes at the next chunk instead of restarting the multi-hour dump.
  • The same event shape. Snapshot rows are emitted as read events keyed by primary key through the same partitioning and the same sink apply path, so sinks need no special snapshot logic - a read is just an upsert.

The consistent snapshot is what makes CDC usable for bootstrapping a sink, not only for ongoing changes - and getting its LSN handoff exact is the difference between a correct sink and a silently corrupted one.

4. Exactly-once delivery: at-least-once and pray -> idempotent sink keyed by LSN

The pipeline is capture -> bus -> sink, three stages that crash independently. A change could be produced to the bus but not confirmed to the source (reader crash), or delivered to a sink but not offset-committed (sink crash). Exactly-once means each change lands in each sink once - no dup, no drop - despite all of that. This is the headline requirement.

Naive approach: at-least-once, commit the offset after the sink write

The connector produces to the bus and confirms the slot after; the sink writes to its target and commits its consumer offset after. On any crash, resume from the last committed point and reprocess.

sink task:
   evt = read(partition)
   sink.apply(evt)            # (1) write to warehouse / index / cache
   consumer.commit(evt.offset) # (2) after (1)

Where it breaks:

  • Crash between (1) and (2) double-applies. If the task dies after writing to the sink but before committing the offset, recovery re-reads the event and applies it again. A blind re-apply of an UPDATE may be harmless, but a re-applied INSERT into a non-idempotent sink duplicates the row, and a re-applied counter increment double-counts.
  • Duplicates from upstream too. The connector itself can re-produce a change on restart (it crashed after producing but before confirming the slot), so the bus may legitimately contain the same change twice. At-least-once is the correct behavior for a durable pipeline - the duplicates are unavoidable at the transport level.
  • Exactly-once-in-transit is a mirage. You cannot make three independent systems commit atomically without a distributed transaction per event, which at 50K/sec is far too slow and couples the stages’ availability together.

At-least-once will duplicate on every crash. The question is not how to prevent duplicates in transit - it is how to make them harmless at the sink.

Evolved approach: accept at-least-once in transit, make the sink idempotent on (key, LSN)

Stop fighting duplicates in the pipe. Guarantee at-least-once delivery in transit (durable bus, slot confirmed only after bus-durable, offset committed after sink-durable - so nothing is ever lost), and make the sink write idempotent so a re-delivered change is a no-op. The LSN is the idempotency token: it is monotonic per key, so the sink applies a change only if its LSN is newer than what it has already applied for that key.

sink apply (idempotent upsert keyed by primary key, versioned by LSN):
   on change evt for key K at lsn L:
      if L <= applied_lsn[K]:  skip            # already applied (duplicate / replay) -> no-op
      else:
         apply(evt)                            # upsert row / delete row
         applied_lsn[K] = L                    # advance the per-key high-water mark
      (apply + applied_lsn update in ONE sink transaction where the sink supports it)

Three concrete shapes of idempotent sink, because sinks are heterogeneous:

Sink typeIdempotency mechanism
SQL warehouse / RDBMSUPSERT ... WHERE incoming_lsn > stored_lsn; store _lsn column per row; delete by PK. Apply + offset in one DB transaction
Search index (Elastic-like)Use the LSN as the document version (external versioning); the engine drops an update with an older version. Delete by doc id
Key-value cacheConditional set keyed by PK, compare-and-set on a stored version; or just last-writer-wins since order is already preserved on the partition
Another serviceDedup table on (source_table, pk, lsn) or an idempotency key; write inside that service’s transaction

Why this is right:

  • Duplicates are provably harmless. Any re-delivered change has L <= applied_lsn[K] and is skipped. So at-least-once transport plus an idempotent, LSN-versioned sink gives effectively-exactly-once at the sink without any distributed transaction across stages. Each stage stays independently available.
  • Ordering and idempotency share the LSN. Because the partition already delivers a key’s changes in LSN order (deep dive 2), the applied_lsn[K] check is also a cheap out-of-order guard - a stale event (older LSN) is dropped the same way a duplicate is. One mechanism covers both.
  • Atomic apply-and-advance where possible. For a transactional sink, writing the row change and the consumer offset (or the applied_lsn) in one sink-side transaction makes the apply point and the progress point a single commit - the (1)/(2) gap is closed, so there is no window to double-apply. For a non-transactional sink, the LSN version check is the fallback that makes a re-apply idempotent anyway.
  • No change is ever lost. The slot advances only after the bus is durable, and the consumer offset advances only after the sink write is durable, so every crash resumes with the change still available to redeliver. Combined with idempotency, that is no-drop and no-dup.

The honest caveat. True end-to-end exactly-once requires the sink to cooperate - either a transaction that bundles the write with the progress marker, or an idempotency key it dedupes on. A sink that supports neither (a fire-and-forget external API with no dedup) can only ever be at-least-once; the best the pipeline can do is hand it a stable idempotency key (table:pk:lsn) and document that the sink owns the dedup. State plainly which half each side guarantees: the pipeline guarantees durable, ordered, at-least-once delivery with a stable dedup key; the sink turns that into exactly-once by being idempotent.

Exactly-once in CDC is not a flag on the bus - it is at-least-once transport plus a sink that treats the per-key LSN as a version and refuses to go backwards, so every duplicate and every out-of-order straggler collapses to a no-op.

API Design & Data Schema

Connector control API (manage capture)

POST /connectors                       # register a CDC connector
  { "name": "orders-cdc",
    "source": { "type": "postgres", "host": "...", "database": "shop",
                "slot_name": "cdc_orders", "publication": "cdc_pub" },
    "tables": ["public.orders", "public.order_items"],
    "snapshot_mode": "incremental",     # initial | incremental | never
    "bus": { "topic_prefix": "cdc", "partitions": 48, "replication_factor": 3 } }
  -> { "connector_id": "conn-12", "state": "SNAPSHOTTING", "snapshot_lsn": null }

GET  /connectors/{id}                   # status
  -> { "state": "STREAMING", "confirmed_lsn": "16/B374D848",
       "slot_lag_bytes": 2_100_000, "capture_lag_ms": 320, "tables": [...] }

POST /connectors/{id}/snapshot          # trigger an ad-hoc / resnapshot of tables
  { "tables": ["public.orders"], "mode": "incremental" }

POST /connectors/{id}/pause             # pause (slot still retained - watch disk!)
POST /connectors/{id}/resume

Change event (the payload on the bus)

topic: cdc.public.orders    key: <primary_key>    partition: hash(pk) % N
{
  "op": "u",                            # c=create, u=update, d=delete, r=read(snapshot)
  "table": "public.orders",
  "primary_key": { "id": 42 },
  "before": { "id": 42, "status": "placed",  "total": 1200 },   # null for inserts
  "after":  { "id": 42, "status": "shipped", "total": 1200 },   # null for deletes
  "source": { "lsn": "16/B374D848", "tx_id": 91823, "ts_ms": 1763836800123,
              "db": "shop", "schema_version": 7 },
  "ts_ms": 1763836800140                # when the connector emitted it
}

Sink consumer API (read plane)

SUBSCRIBE  subscribe(group_id="warehouse-sink", topics=["cdc.public.orders"])
FETCH      poll(max_bytes=4MB, max_wait_ms=200)
           -> batch ordered by offset (= LSN order per key on the partition)
COMMIT     commit(offsets={ "cdc.public.orders-7": 4_880_201 })  # after sink durable
SEEK       seek(partition, offset|beginning)      # replay for a sink rebuild

Data model: offsets, schema history, sink state

The hot path is not a relational table - it is the source’s WAL (append-only log, read as a stream) and the bus’s partitioned append-only log. These are deliberately not general SQL stores: the workload is sequential, ordered, append-and-scan, which a random-access, index-per-row RDBMS is the wrong tool for. The small coordination stores are relational / strongly-consistent because they are tiny and need correctness over throughput.

Connector offset store (durable, strongly consistent - the recovery anchor):

table connector_offsets (NoSQL doc or small SQL row, read/written rarely):
   connector_id  PK
   confirmed_lsn            # resume point on restart; also confirmed to the source slot
   snapshot_state          # { mode, last_chunk_pk, completed_tables[] }
   updated_at
   INDEX: PK only (point lookup on restart)

Schema history (what each table looked like at each LSN):

topic cdc.schema.history   (append-only, compacted by table):
   { table, lsn, ddl, columns:[{name,type,nullable}], schema_version }
   -> lets a restarting connector decode old WAL records with the schema
      that was in effect at that LSN, and lets sinks evolve with the data.

Sink apply state (per sink, for idempotency):

In the SQL warehouse: every target row carries a _source_lsn column.
   orders(id PK, status, total, _source_lsn)    # UPSERT only if new lsn > stored
In a search index: doc _version = lsn (external versioning), engine enforces monotonicity.
   A separate consumer_offsets store maps (group, topic, partition) -> committed offset,
   committed in the SAME transaction as the sink write where the sink is transactional.

Why SQL vs NoSQL, stated: the change log (source WAL, bus topics) is a purpose-built append-only log, not SQL or document - sequential throughput and replay are the whole point. The offset / schema-history stores are small and correctness-critical, so they live in a strongly-consistent store (a compacted bus topic or a small SQL table). The sink choice is whatever the consumer is; CDC only requires it expose an idempotent, PK-keyed, LSN-versioned write.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. Replication slot retention fills the source disk. The single most dangerous failure: a stalled or lagging connector makes the source retain unbounded WAL, filling the primary’s disk and risking a production outage. Fix: page-worthy slot-lag alerting, a bounded retention cap (drop the slot and re-snapshot rather than kill the primary), and a highly available connector (standby that takes over the slot in seconds) so a crashed reader never lags for hours. Capture lag is the top-line SLO.

2. A single connector caps capture throughput. One decode-and-produce thread caps at its CPU and the source’s single logical-decoding stream, below the 200K/sec peak. Fix: shard capture by table or by primary-key range, each shard on its own slot/stream, each a single ordered producer for its key space - never split one key across shards. Produce in batches with an idempotent producer so the bus dedupes retries.

3. Per-key ordering versus parallelism. The central tension: partitioning for throughput while a single row’s changes stay ordered. Fix: partition by primary key (deep dive 2). N partitions give N-way parallelism across keys and strict order within a key. The partition key, the connector’s producer-sharding key, and the sink’s consumer assignment all key on the primary key - that single alignment is the whole ordering guarantee.

4. Hot key / hot partition (skew). A single very-hot row (a popular aggregate, a celebrity account) overloads one partition and one sink task, and you cannot salt it without breaking its order. Fix: ensure the one sink task for a hot key is fast (large batched writes); compact the topic so only the latest value per key survives if the sink only needs current state (collapses many changes into few net applies); accept that one row’s history is serial and size that single lane to keep up.

5. A slow sink lags and backpressures. A sink that writes slowly (a warehouse doing synchronous commits) falls behind the bus tail; unbounded buffering blows up memory. Fix: sinks are decoupled by the bus - a slow sink just lags its own consumer offset without affecting capture or other sinks (the key reason the bus sits in the middle). Add more sink tasks (up to the partition count), batch sink writes, and autoscale sinks on consumer lag. Capture never blocks on a slow sink; it blocks only on the bus being full, which is sized generously.

6. Connector or broker failure loses/stalls changes. A single-copy connector offset or a single-copy partition dies with its node. Fix: RF 3 with ISR, acks=all, min.insync.replicas=2 on the bus so an acked change survives a broker loss; store the connector offset durably (compacted topic / replicated store) so a restarted connector resumes from the confirmed LSN; run the connector with a standby. No committed change is ever lost.

7. Exactly-once coordination overhead. A distributed transaction per change across source, bus, and sink would be far too slow at 50K/sec. Fix: at-least-once transport + idempotent LSN-versioned sink (deep dive 4). Correctness is a cheap per-key version check at the sink, not a cross-stage commit per event. Stages stay independently available.

8. Schema changes break decoding or sinks. A DDL on a tracked table (new column, type change) can make old WAL records undecodable or break a sink expecting the old shape. Fix: a schema history topic keyed by LSN so the connector decodes each record with the schema in effect at that LSN; propagate schema-change events so sinks evolve (additive changes are safe; breaking changes route to a dead-letter path and alert). Carry a schema_version on every event.

9. Poison events stall a partition. One un-applyable event (a value the sink rejects, a constraint violation) blocks that partition’s consumer and, because order matters, you cannot just skip it blindly. Fix: bounded retries, then route the poison event to a dead-letter topic with its LSN and reason, alert, and continue - accepting that this one key is now behind until reconciled, rather than stalling the whole partition. Reconcile the dead-lettered key by re-snapshotting it.

10. Sink rebuild re-reads the whole stream. Rebuilding a sink from scratch re-reads days of change events, saturating bus read bandwidth. Fix: keep a compacted “latest state per key” topic alongside the full change log, so a rebuild reads one current image per key (small) rather than full history; for history-dependent sinks, throttle the rebuild and serve it from in-sync follower fetches to spread read load off the leaders.

Shard keys, stated plainly: capture shards by table or primary-key range, and the bus, the sink consumers, and the sink’s idempotency all key on the primary key, via hash(primary_key) % numPartitions. The primary key is simultaneously the unit of ordering (a row’s changes are serial), the unit of parallelism (one partition, one sink task per key group), and the unit of idempotency (the per-key LSN high-water mark). That single alignment is what lets delivery be parallel, ordered, and exactly-once at the same time.

Wrap-Up

The trade-offs that define this design:

  • Tail the WAL, never poll the tables. Reading the write-ahead log captures every insert, update, and delete in commit order with near-zero source query load - at the cost of a replication slot that will fill the source’s disk if the reader stalls, which makes bounded capture lag the top operational SLO.
  • Primary key is the partition key, everywhere. It is the only way to get per-key ordering and cross-key parallelism at once. We trade the ability to load-balance a single hot key (its history is irreducibly serial) for correct, deterministic row state at every sink.
  • Exactly-once is at-least-once plus an idempotent sink. We refuse a per-event distributed transaction (too slow, couples availability) and instead guarantee durable, ordered, at-least-once transport with the LSN as a stable dedup key; the sink turns that into exactly-once by treating the per-key LSN as a version that never goes backwards. End-to-end exactly-once requires the sink to cooperate, and we say so plainly.
  • The bus decouples heterogeneous sinks. Putting a partitioned, replayable log between capture and delivery lets ten sinks consume at ten different speeds, rebuild independently, and fail independently, without any one of them touching capture or the source.
  • Snapshot and stream meet at an exact LSN. A consistent (or incremental watermark-based) snapshot bootstraps a sink without a long source lock, and hands off to streaming at a precise LSN so no row is missed or doubled at the boundary.

One-line summary: a CDC pipeline tails the source’s write-ahead log over a replication slot, decodes each committed insert/update/delete into a change event keyed and partitioned by primary key so per-key commit order survives, transports them over a durable partitioned bus that decouples many heterogeneous sinks, and achieves exactly-once by delivering at-least-once with the LSN as an idempotency version that each sink applies monotonically - with bounded capture lag protecting the source and an exact-LSN snapshot handoff bootstrapping each sink.