Intermediate

The First Hurdle: Snapshotting

Initial loads are where most CDC rollouts stumble. Follow this guided playbook to capture a consistent snapshot, hold the boundary, and merge the stream without gaps.

Start with a clean handoff

A large share of CDC escalations originate during the initial load. Teams rush the boundary, purge logs, and spend weeks replaying tables.

Use these three moves to align engineering, operations, and analytics before the stream goes live.

Prove it in 15 minutes β†’

High-watermark boundary handoff

  1. Mark high-watermark Record LSN/SCN boundary
  2. Consistent read Snapshot without gaps
  3. Stream after boundary Apply idempotently

Snapshot β†’ high-watermark β†’ stream. Preserve per-key order and use idempotent upserts/deletes at the sink.

  • Boundary & retention.

    Set the log high-watermark, confirm retention covers the run, and name an owner for recovery points.

  • Execution made safe.

    Pick the right snapshot mode, chunk large tables, and cap parallelism to respect OLTP workloads. The quickstarts show the snapshot settings for each database.

  • Proof & recovery.

    Run the quick lab, monitor offsets and lag, and document restart checkpoints.

Pre-flight checklist

Confirm these guardrails before the snapshot starts rolling.

View checklist
  • Retention window covers full snapshot duration (WAL/binlog/T-log/UNDO).
  • Privileges for log reading/replication are granted.
  • Consistent-read isolation is enabled where applicable (REPEATABLE READ/SNAPSHOT).
  • Sink MERGE/UPSERT implemented; delete/tombstone semantics defined.
  • Offsets are durable and backed up/versioned (see Offsets & Replays).
  • DDL freeze or schema-compatibility policy in place.

Why the boundary wins

Run style What happens mid-snapshot Recovery story
Naive initial load Changes land twice or not at all; log position is unknown. Full re-run of large tables; risky ad-hoc dedupe scripts.
Snapshot with boundary Log handoff preserves ordering; replays apply idempotently. Saved offset + idempotent replays; no target surgery. Only an incremental snapshot resumes mid-table (see below).
Incremental snapshot Primary-key ranges throttle load while respecting OLTP. Retries pick up the next range; log anchor stays valid.

A CDC pipeline is designed to stream ongoing changes, but it must first be initialized with the data that already exists in the source tables. This process of performing an initial, full copy of the data is known as snapshotting or the initial load.

Why snapshots break

The central problem is consistency. Without a boundary, writes that land mid-run show up twice (snapshot + stream) or disappear entirely. Retention clocks keep ticking and, if the log purges, the only fix is to start over.

Picture a payments table: you start scanning, finance posts refunds, and analytics reconciles against a different truth hours later. The fallout is expensive clean-up, tense incident calls, and a loss of trust in the pipeline.

A staged handoff

Modern log-based CDC tools coordinate a point-in-time snapshot with the transaction log so the handoff to streaming has no gaps or double-counts. Treat the run in three phases:

Snapshot flow diagram showing three phases: marking high watermark, performing consistent read snapshot, and streaming changes from the boundary
The three-phase handoff: mark boundary β†’ snapshot data β†’ stream from boundary

Before snapshot: mark the high-watermark

Read and persist the current log position (LSN/SCN). Share it in the runbook and verify retention outlives the planned duration.

  • Capture boundary metadata alongside connector configuration.
  • Alert on log growth so retention doesn’t expire mid-run.

During snapshot: hold a consistent read

Use snapshot/consistent-read isolation and scan tables in deterministic chunks. The goal is predictable load that won’t pin OLTP locks or exhaust undo segments.

  • Chunk big tables in primary-key order and cap parallelism.
  • Read from a replica when possible; monitor lag to stay honest.

After snapshot: stream from the boundary

Start consuming the log from the recorded position. Any rows that change post-snapshot must apply idempotently so retries are safe.

  • Implement UPSERT/MERGE semantics and explicit delete handling.
  • Version and store offsets so restart is a click, not a rebuild.

Snapshot Lifecycle

Run it on your database

Grab the snippet for your engine to capture the boundary and hold a consistent read while Debezium (or another connector) walks the tables.

PostgreSQL
-- Requirements (once/admin). Both settings need a server restart;
-- pg_reload_conf() does not apply either of them.
ALTER SYSTEM SET wal_level = logical;
ALTER SYSTEM SET max_replication_slots = 10;  -- adjust
-- Now restart PostgreSQL, then check:
SHOW wal_level;  -- must say: logical

-- Illustration of the idea only, NOT a procedure (race: see the note below).
-- Boundary + consistent read (within one tx while snapshotting):
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT pg_current_wal_lsn();  -- record this
-- Keep transaction open during table scans; Debezium coordinates via logical slot.

The boundary lines above show the idea only and have a race: the transaction snapshot is taken before the LSN is read, so a commit in between is invisible to the scan yet sits below the recorded LSN, and a stream that starts at that LSN misses it. Reading the LSN and taking the snapshot in two separate steps can miss a commit between them, so a procedure must obtain the consistent point and the snapshot together. The PostgreSQL documentation for creating a logical replication slot describes how to do this; check the documentation for your version.

MySQL (InnoDB)
-- Requirements:
-- binlog_format=ROW; binlog_row_image=FULL; GTID (preferred)

-- Boundary + consistent snapshot:
SHOW MASTER STATUS;                  -- or SELECT @@global.gtid_executed;
START TRANSACTION WITH CONSISTENT SNAPSHOT;
-- Read tables in PK order; Debezium avoids FTWRL in OLTP paths.
SQL Server
-- Requirements (once/admin):
ALTER DATABASE YourDb SET ALLOW_SNAPSHOT_ISOLATION ON;
ALTER DATABASE YourDb SET READ_COMMITTED_SNAPSHOT ON;
EXEC sys.sp_cdc_enable_db;  -- if using native CDC

-- Boundary + snapshot:
SELECT sys.fn_cdc_get_max_lsn();     -- record
SET TRANSACTION ISOLATION LEVEL SNAPSHOT;
BEGIN TRAN;
-- Read tables; keep tx open during snapshot.
Oracle
-- Requirements (once/admin):
ALTER DATABASE ADD SUPPLEMENTAL LOG DATA;  -- minimal or ALL columns for PK-less

-- Boundary:
SELECT CURRENT_SCN FROM V$DATABASE;        -- record
-- Consistent reads use UNDO/flashback; ensure UNDO retention covers snapshot.
How consistent reads behave
  • PostgreSQL: REPEATABLE READ keeps scans stable within one transaction (pg_export_snapshot() lets other sessions import that transaction's snapshot, but neither gives you a log position); long scans can delay VACUUM, so watch table bloat alerts.
  • MySQL/InnoDB: START TRANSACTION WITH CONSISTENT SNAPSHOT anchors to a binlog positionβ€”no FLUSH TABLES WITH READ LOCK required for OLTP safety.
  • SQL Server: CDC tables + max LSN establish the boundary; snapshot isolation or read committed snapshot keeps readers from blocking writers.
  • Oracle: A saved SCN plus UNDO retention gives you flashback reads; make sure UNDO window covers the run.

Snapshot modes (choose intentionally)

  • initial: Do a snapshot then continue streaming (default for first run).
  • initial_only: One-time bulk load, no streaming (bootstraps batch targets).
  • no_data: Capture structure but no table data (for pre-seeded targets or special cases). On MySQL this replaces schema_only, which is deprecated; the Debezium 3.7 pages do not list never.
  • always / when_needed: always repeats the snapshot on every start; when_needed snapshots when no offsets exist or the recorded log position is gone. See Backfill and Re-Snapshot Safely for the full list. Check the names for your version.
  • incremental snapshot: Chunk tables online (no global pause) using low/high watermarks and primary-key ranges; supports resuming mid-table.

How incremental snapshots actually work (watermarks)

“Chunk the table online, no global pause” is the headline. The interesting part is how a chunk read that races the log still converges on the right answer. The method comes from Netflix’s DBLog paper and is what Debezium’s incremental snapshots implement.

The move is to stop trying to make the read atomic, and let the log arbitrate instead.

  1. Write a low watermark. Insert a marker row into a dedicated signal table. Because it is an ordinary write, it appears in the transaction log at a known position.
  2. Select the chunk. Read the next N rows in primary-key order. No table lock, no global pause, and the read is explicitly allowed to go stale.
  3. Write a high watermark. A second marker row. The log now brackets the exact window during which the read happened.
  4. Watch the window. Keep consuming the log as normal and record every primary key that produced a change event between the two watermarks.
  5. Subtract, then emit. Drop from the chunk every row whose key appeared in that window, and emit what survives as snapshot reads (Debezium’s r operation). Those keys are not lost β€” the log already carries a newer value for them.

The chunk boundary doubles as the resume point: record the last completed chunk’s key range and a crash resumes mid-table instead of restarting the snapshot. Chunk size is the tuning knob in both directions β€” smaller chunks shorten each watermark window (less to subtract, less memory) at the cost of more round trips.

What this costs you in practice

  • Write access to the source. The signal table is a real table the connector writes to. Where that is unacceptable, newer Debezium versions accept signals over a Kafka topic instead.
  • A usable primary key. Chunking is PK-ordered. Keyless tables have no stable chunk boundary and no resume point β€” the same constraint that breaks idempotent sinks downstream.
  • Read load on the primary. Nothing here is free; the chunk selects still compete with OLTP traffic. This buys you the absence of a lock, not the absence of work.
  • Duplicate deliveries, as always. A retry can emit a chunk twice. That is fine, and it is the same property the rest of this site depends on: the sink upserts on the primary key and orders by log position, so a replayed r event is harmless.

Note that the subtraction happens in the connector, before anything reaches the broker β€” it is not something your sink has to reimplement. Your sink’s job is unchanged: treat r like an upsert and let log position break ties.

Performance: chunking & throughput

  • Chunking: Read large tables in PK-ordered chunks (5k–200k rows) to bound memory and reduce long transactions. Prefer monotonic PKs; otherwise use synthetic chunking keys.
  • Parallelism: Limit concurrent table snapshots to protect OLTP (1–3 in parallel).
  • Throttling: Use fetch size / max rows per poll to keep steady pressure, not bursts.
  • Replica reads: For MySQL/PG, consider reading from a replica to offload the primary (ensure replication lag is acceptable and log positions still align).

Operational guardrails (day-one checks)

  • Log retention: Ensure WAL/binlog/T-log won’t be purged before snapshot finishes. Alert on backlog age and size.
  • Privileges: Replication/log-read permissions; publication/slot creation where applicable.
  • DDL during snapshot: Prefer compatibility rules (schema registry) and deploy windows; avoid table rebuilds that invalidate consistent reads.
  • Sink idempotency: Upsert/delete semantics in the warehouse/search index must be idempotent so replays (post-snapshot) don’t duplicate data.
  • Restart safely: Snapshots should be restartable. Because the sink is idempotent, re-reading rows is harmless. Only an incremental snapshot resumes mid-table, from the last completed chunk and the recorded watermark.

Idempotent sink patterns

Use UPSERT/MERGE semantics keyed on the primary key, ordered by the source log position, with explicit delete markers. Ready-made templates are in the MERGE cookbook.

How snapshot rows interleave with streamed changes. A snapshot row (op = 'r') is a read of the table as it stood at one point in the source log, and it carries that log position: for an initial snapshot, the position the snapshot read from; for an incremental chunk, a position in the log at the time the chunk was read. Check the source block of an r event for your connector. Later streamed changes to the same key usually carry higher positions (row locks serialise writers per key), so when a streamed change and a snapshot row for the same key meet in the sink, the higher position wins. One caveat: on PostgreSQL a streamed event’s source.lsn is the position of the change’s WAL record, not of the commit, so a transaction that was already open at the snapshot’s position and commits afterwards can arrive with positions below it, and a snapshot row stamped at that position would then beat it. Check what position your connector gives snapshot rows, and see the stamp rule for a SQL reload. That is why the guard compares log position: a snapshot row that arrives late, is re-sent after a retry, or comes from an overlapping chunk or a re-run snapshot holds an older position than the streamed change already applied, and is skipped instead of overwriting it. A timestamp cannot do this job: snapshot rows carry the time of the snapshot, and the envelope ts_ms is later on every replay, so a stale row can look newer than the streamed change it should lose to.

Warehouse MERGE example
-- Untested: not run against a live warehouse. Written for Snowflake, BigQuery
-- and PostgreSQL 15+. Assumes dw.customers has a primary key customer_id, a
-- deleted flag, a source_lsn column that is never NULL, and nullable name and
-- email (a delete carries no row values). Readers filter deleted = FALSE.
-- If you add source_lsn to an existing table, backfill it first: NULL < x is
-- NULL, so a row with a NULL source_lsn would never be updated. Or compare
-- COALESCE(t.source_lsn, -1) < s.lsn.
-- lsn is the log position copied from the event as-is, never a clock time.
-- If you keep a source updated_at as a data column, copy it but never
-- compare it.
MERGE INTO dw.customers AS t
USING (
  -- overlapping chunks and replays put several rows per key in staging;
  -- MERGE needs one source row per target row, so keep the latest by position
  SELECT customer_id, name, email, op, lsn
  FROM (
    SELECT customer_id, name, email, op, lsn,
           ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY lsn DESC) AS rn
    FROM staging.customers
  ) ranked
  WHERE rn = 1
) AS s
ON t.customer_id = s.customer_id
WHEN MATCHED AND t.source_lsn < s.lsn THEN UPDATE SET
  name = s.name,
  email = s.email,
  deleted = (s.op = 'd'),
  source_lsn = s.lsn
WHEN NOT MATCHED THEN INSERT (customer_id, name, email, deleted, source_lsn)
VALUES (s.customer_id, s.name, s.email, (s.op = 'd'), s.lsn);

The strict < makes a replay of the same change (same position) a no-op. If two different changes to one key can share a position, order by and compare the (position, seq) pair; see Making Sinks Bulletproof and Materialization.

Re-running a snapshot later for a new sink, a schema change or a lost slot is a task of its own: Backfill and Re-Snapshot Safely.

Observability: what to track

  • Source log lag (bytes/time behind) and slot/binlog growth.
  • Snapshot throughput (rows/s), chunk duration, ETA by table.
  • Sink merge latency and deadlocks.
  • Error budget: % chunks retried; time to resume after failure.

Failure modes β†’ actions

  • Long snapshots block VACUUM/UNDO: shrink chunk size; run on a replica; pause between chunks.
  • Log purged mid-snapshot: for a plain boundary snapshot the boundary is no longer valid: start the snapshot again; increase retention; consider replica. An incremental snapshot can resume from its last completed chunk. On Postgres, a slot that lost its WAL cannot be resumed at all; see the replication slot runbook. For MySQL binlogs and SQL Server CDC change tables, see SQL Server & MySQL CDC specifics.
  • No primary key: declare a stable key (a unique column set, for example with Debezium’s message.key.columns, or a surrogate column) and key the sink on it, ordered by log position. A hash of all columns changes with every update, so it identifies a version, not a row, and a timestamp cannot say which version is newer.
  • DDL during snapshot: retry chunk with stable schema; versioned views; schema-compat rules.
  • Replica lag: validate boundary alignment; if laggy, snapshot from primary or temporarily gate OLTP.

Hands-on: prove no gaps/dupes (β‰ˆ15 min)

  1. Pick your database and run the β€œboundary + consistent read” snippet.
  2. While snapshot runs, perform writes in a second session: insert (id=3), update (id=2).
  3. After handoff, insert (id=4). Verify sink via MERGE and run a dup check.
Dup check query
SELECT id, COUNT(*) AS c
FROM dw.orders
GROUP BY id
HAVING COUNT(*) > 1;

Common gotchas

Snapshotting Knowledge Check

Test your understanding of CDC snapshotting concepts and best practices.

Q1

What is the primary challenge when performing an initial snapshot in CDC?

Q2

What is a 'high-watermark' in the context of CDC snapshotting?

Q3

Why is it important to set log retention before starting a snapshot?

Q4

What is the recommended approach for snapshotting very large tables?

Q5

What happens after the snapshot completes in a well-designed CDC pipeline?

0/5 correct
Progress 0% No progress yet
Progress is stored locally in this browser.