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:
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
Plan & Pre-flight
Verify retention, privileges, and isolation settings before starting.
Confirm log retention covers the expected snapshot duration. Grant replication privileges. Enable consistent-read isolation (REPEATABLE READ or SNAPSHOT; the isolation level alone does not give a consistent boundary: see the boundary note). Document rollback steps in the runbook.
Mark High-Watermark
Capture the current log position (LSN/SCN) as the snapshot boundary.
Record the exact log sequence number before scanning begins. This position marks where the snapshot ends and streaming will start. Store it alongside connector configuration for recovery.
Consistent Read
Scan tables in deterministic chunks under snapshot isolation.
Read tables using primary-key ordering. Chunk large tables to cap memory and lock duration. Use a replica if possible and monitor replication lag. Each chunk can be retried independently on failure.
Stream from Boundary
Begin consuming the transaction log from the recorded high-watermark.
The connector transitions seamlessly from snapshot to streaming mode. Changes are applied idempotently with UPSERT/MERGE semantics. Per-key ordering ensures consistency even during retries.
Validate & Monitor
Compare row counts, check lag metrics, and set up ongoing monitoring.
Run row-count reconciliation between source and target. Monitor consumer lag and offset progression. Set alerts for lag spikes or stalled offsets. Document the recovery checkpoint for future restarts.
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 SNAPSHOTanchors to a binlog positionβnoFLUSH TABLES WITH READ LOCKrequired 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 listnever. -
always / when_needed:
alwaysrepeats the snapshot on every start;when_neededsnapshots 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.
- 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.
- 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.
- Write a high watermark. A second marker row. The log now brackets the exact window during which the read happened.
- Watch the window. Keep consuming the log as normal and record every primary key that produced a change event between the two watermarks.
-
Subtract, then emit. Drop from the chunk every row
whose key appeared in that window, and emit what survives as
snapshot reads (Debezium’s
roperation). 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
revent 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)
- Pick your database and run the βboundary + consistent readβ snippet.
- While snapshot runs, perform writes in a second session: insert (id=3), update (id=2).
- 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.
What is the primary challenge when performing an initial snapshot in CDC?
The key challenge is coordinating the snapshot with the transaction log position (LSN/SCN) to ensure a clean handoff. The snapshot must capture the state at a specific point, and streaming must begin from exactly that point to avoid gaps or duplicate records.
Review the correct answer and explanation.
What is a 'high-watermark' in the context of CDC snapshotting?
The high-watermark is a specific log position (LSN for PostgreSQL, SCN for Oracle, etc.) that marks the boundary. All changes up to this point are included in the snapshot, and streaming begins from this position forward. This ensures no data is lost or duplicated during the handoff.
Review the correct answer and explanation.
Why is it important to set log retention before starting a snapshot?
If the snapshot takes hours or days, the database might purge old transaction logs before the snapshot completes. Setting adequate log retention ensures that when streaming starts from the high-watermark, all necessary log entries are still available.
Review the correct answer and explanation.
What is the recommended approach for snapshotting very large tables?
For large tables, chunking (reading in batches based on primary key ranges) reduces memory pressure, allows progress to be saved incrementally, and respects production database workloads. This approach also enables parallelization and retry of failed chunks.
Review the correct answer and explanation.
What happens after the snapshot completes in a well-designed CDC pipeline?
After the snapshot completes, the CDC connector seamlessly transitions to streaming mode, reading changes from the transaction log starting at the high-watermark position. This creates a continuous flow of data without gaps, combining the snapshot with real-time changes.
Review the correct answer and explanation.