Snowflake Change Data Capture
Delta processing without a log table
Snowflake's change data capture is built on streams: a lightweight object that sits on a table and records the net effect of changes since the stream was last read. A stream is not a log of every statement â it is a pointer plus a change set, and when you consume it, the rows arrive with METADATA$ACTION and METADATA$ISUPDATE columns that tell you whether each row was an insert, an update, or a delete. Reading the stream advances its offset atomically with the consuming transaction, which is the property that makes at-least-once delivery achievable without a message broker.
The design has two consequences worth internalising before building anything. First, concurrent writers do not produce duplicates or gaps in the stream, because the change set is derived from the table's transaction history rather than from triggers. Second, if the consuming transaction rolls back, the offset rolls back with it â so a failed pipeline run can simply be re-run and will see exactly the same changes again.
- A stream on a table records inserts, updates, and deletes since the last consume.
METADATA$ACTIONdistinguishes inserts from deletes;METADATA$ISUPDATEmarks update halves.- Consuming and applying happen in one transaction, which is what gives you exactly-once effects.
Prerequisites
- !Snowflake tasks and scheduling
- !MERGE statements and transaction basics
What You'll Learn
- 1Create and consume streams for insert, update, and delete detection
- 2Orchestrate consume-and-apply as a self-scheduling task chain
- 3Track offsets and prove pipeline completeness
- 4Replay safely using Time Travel and clones
The mechanics of consumption
The two-column metadata is the entire contract. An INSERT action arrives as a single row with METADATA$ISUPDATE false; a delete arrives as ACTION = 'DELETE'; an update appears as two rows for the same key â one DELETE with the update flag and one INSERT with the update flag â which is why naive SELECT * consumers often double-count.
-- A stream on a source table
CREATE OR REPLACE STREAM raw.orders_cdc
ON TABLE raw.orders
APPEND_ONLY = FALSE
COMMENT = 'Net change feed for the orders table';
-- What a consumer sees
SELECT
METADATA$ACTION,
METADATA$ISUPDATE,
METADATA$ROW_ID,
order_id,
status,
amount
FROM raw.orders_cdc;
-- Apply the change set in the same transaction that consumes it
BEGIN
MERGE INTO curated.orders t
USING (
SELECT
order_id,
status,
amount,
updated_at
FROM raw.orders_cdc
WHERE NOT (METADATA$ACTION = 'DELETE' AND METADATA$ISUPDATE = TRUE)
) s
ON t.order_id = s.order_id
WHEN MATCHED AND s.status = 'CANCELLED' THEN DELETE
WHEN MATCHED THEN UPDATE SET
status = s.status,
amount = s.amount,
updated_at = s.updated_at
WHEN NOT MATCHED THEN INSERT (order_id, status, amount, updated_at)
VALUES (s.order_id, s.status, s.amount, s.updated_at);
COMMIT;
-- After a successful consume, the stream is empty until new changes arrive
SELECT COUNT(*) AS remaining FROM raw.orders_cdc;
The filter that removes the update's delete half is the detail most implementations get wrong. Because an update emits a delete-plus-insert pair, a MERGE that treats every DELETE action as a real deletion will remove a row and immediately reinsert it, which is survivable but destroys history and any downstream triggers. Filtering on NOT (METADATA$ACTION = 'DELETE' AND METADATA$ISUPDATE) keeps genuine deletes while discarding the synthetic half of updates.
Append-only streams are a useful variation for pure insert tables such as event logs. Setting APPEND_ONLY = TRUE means the stream never records deletes and updates, which lets you skip the update-half filter entirely and reduces the stream's bookkeeping cost.
The reliable micro-batch pipeline
A production CDC pipeline is usually three hops: a stream on the source, a task that consumes it into a staging table, and a task that applies the staging rows with MERGE. Splitting consume from apply makes each hop retryable and lets you inspect the change set before it touches curated data.
| Hop | Object | Purpose | Failure behaviour |
|---|---|---|---|
| Capture | stream on source | records net changes | offset survives; no data copied |
| Stage | task plus temp or staging table | drains the stream into durable rows | task fails without advancing offset |
| Apply | task plus MERGE | writes curated tables idempotently | rerun applies the same change set |
-- Hop 1: drain the stream into a staging table
CREATE OR REPLACE TABLE staging.orders_changes AS
SELECT
METADATA$ACTION AS change_action,
METADATA$ISUPDATE AS is_update,
order_id,
status,
amount,
updated_at,
CURRENT_TIMESTAMP() AS captured_at
FROM raw.orders_cdc
WHERE NOT (METADATA$ACTION = 'DELETE' AND METADATA$ISUPDATE = TRUE);
-- Hop 2: apply the staged changes
MERGE INTO curated.orders t
USING staging.orders_changes s
ON t.order_id = s.order_id
WHEN MATCHED AND s.change_action = 'DELETE' THEN DELETE
WHEN MATCHED THEN UPDATE SET
status = s.status,
amount = s.amount,
updated_at = s.updated_at
WHEN NOT MATCHED AND s.change_action = 'INSERT' THEN INSERT
(order_id, status, amount, updated_at)
VALUES (s.order_id, s.status, s.amount, s.updated_at);
TRUNCATE TABLE staging.orders_changes;
Idempotency is what makes this safe to rerun. If the apply task succeeds but the subsequent bookkeeping fails, running the task again must not corrupt the target. Two properties give you that: the MERGE is keyed on a natural key rather than on row identity, and the staging table is truncated only after a successful apply, so a rerun re-applies the same change set to a table that already contains it â which MERGE handles because the update is a no-op write of identical values.
Task orchestration and dependencies
Snowflake tasks can schedule themselves on an interval and chain to a child task, which is enough to drive a CDC pipeline without an external orchestrator for many workloads. The parent task owns the schedule; children run only when the parent succeeds.
-- The root of the chain: schedules every five minutes
CREATE OR REPLACE TASK raw.orders_cdc_drain
WAREHOUSE = cdc_wh
SCHEDULE = '5 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('RAW.ORDERS_CDC')
AS
CALL staging.drain_orders_stream();
-- Child applies only after a successful drain
CREATE OR REPLACE TASK curated.orders_cdc_apply
WAREHOUSE = cdc_wh
AFTER raw.orders_cdc_drain
AS
CALL curated.apply_orders_changes();
-- A second chain for a related table, running off the same schedule
CREATE OR REPLACE TASK raw.customers_cdc_drain
WAREHOUSE = cdc_wh
SCHEDULE = '5 MINUTE'
WHEN SYSTEM$STREAM_HAS_DATA('RAW.CUSTOMERS_CDC')
AS
CALL staging.drain_customers_stream();
-- Resume after creation: tasks are created suspended
ALTER TASK curated.orders_cdc_apply RESUME;
ALTER TASK raw.orders_cdc_drain RESUME;
-- Inspect the current state
SHOW TASKS LIKE '%cdc%';
SELECT
name,
state,
scheduled_time,
completed_time
FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY())
WHERE name ILIKE '%cdc%'
ORDER BY scheduled_time DESC
LIMIT 20;
SYSTEM$STREAM_HAS_DATA is the guard that keeps idle tables from costing warehouse time. Without it, the task runs on schedule and performs an empty consume, which is cheap individually and expensive at fleet scale. The WHEN clause evaluates before the warehouse resumes, so an idle pipeline genuinely costs nothing.
One operational trap: creating a task that depends on a parent requires the parent to exist first, and altering a parent task's schedule does not automatically propagate to children. When changing the cadence, resume states and dependency chains both need re-checking with SHOW TASKS before assuming the new schedule is live.
Tracking offsets and proving completeness
Because a stream offset advances only inside a consuming transaction, the honest progress metric is not "when did the task last run" but "how far behind is the stream". Snowflake exposes both the pending change volume and the history of every consume.
-- How much change is waiting right now
SELECT
s.name AS stream_name,
s.table_name,
s.offset,
s.stream_source_table,
COUNT(c.*) AS pending_rows
FROM information_schema.streams s
LEFT JOIN TABLE(INFORMATION_SCHEMA.STREAM_HISTORY()) c
ON c.stream_name = s.name
WHERE s.name ILIKE '%CDC%'
GROUP BY s.name, s.table_name, s.offset, s.stream_source_table;
-- Task execution outcomes
SELECT
name,
scheduled_time,
query_start_time,
state,
error_code,
error_message
FROM TABLE(INFORMATION_SCHEMA.TASK_HISTORY(
SCHEDULED_TIME_RANGE_START => DATEADD(day, -1, CURRENT_TIMESTAMP())
))
WHERE name ILIKE '%orders_cdc%'
ORDER BY scheduled_time DESC
LIMIT 50;
-- End-to-end reconciliation: source vs curated
SELECT
(SELECT COUNT(*) FROM raw.orders) AS source_rows,
(SELECT COUNT(*) FROM curated.orders) AS curated_rows,
(SELECT COUNT(*) FROM raw.orders_cdc) AS pending_changes,
(SELECT COUNT(*) FROM raw.orders
WHERE updated_at > COALESCE(
(SELECT MAX(updated_at) FROM curated.orders),
'1900-01-01'::TIMESTAMP_NTZ)) AS rows_newer_than_curated;
The reconciliation query is the one to put on a dashboard. Pending rows tell you latency; the count of source rows newer than the curated maximum tells you whether the pipeline is genuinely caught up or merely idle because the task failed silently. Together they turn "the pipeline looks fine" into a number with an alert threshold.
Time Travel, clones, and replay
When a change set is applied incorrectly â a bad filter, a broken business rule â the recovery path does not require re-extracting from the origin system. Streams and curated tables both benefit from Time Travel, and a zero-copy clone lets you inspect the bad state without touching production.
-- Snapshot the curated table before a risky migration
CREATE TABLE curated.orders_backup
CLONE curated.orders;
-- See the change set that existed before it was consumed
SELECT
METADATA$ACTION,
order_id,
status,
amount
FROM raw.orders_cdc AT(OFFSET => -60 * 60)
WHERE order_id = 'ORD-10023';
-- Rebuild curated from an earlier state
CREATE OR REPLACE TABLE curated.orders
CLONE curated.orders AT(TIMESTAMP => DATEADD(hour, -4, CURRENT_TIMESTAMP()));
-- Replay a window of raw into curated by resetting the stream offset:
-- create a fresh stream, apply the window, then swap
CREATE OR REPLACE STREAM raw.orders_replay
ON TABLE raw.orders AT(TIMESTAMP => DATEADD(day, -2, CURRENT_TIMESTAMP()));
INSERT INTO curated.orders
SELECT order_id, status, amount, updated_at
FROM raw.orders_replay
WHERE NOT (METADATA$ACTION = 'DELETE' AND METADATA$ISUPDATE = TRUE);
Cloning a table does not clone the stream that sits on it, which matters when planning a replay: the new clone starts with a fresh offset pointing at the current table state, not at the historical one. For a true historical replay, create the stream on the source at the desired timestamp as shown above, or rebuild curated from the source table itself rather than trying to rewind an existing stream.
Ordering, duplicates, and idempotency
Streams guarantee that changes are delivered at least once, and the consuming MERGE is what converts that into exactly-once effects. The design rules that make the conversion work are worth stating explicitly.
- Key every apply on a natural key so a rerun is a no-op rather than a duplicate.
- Drop the update's delete half before applying, or updates become delete-plus-insert churn.
- Treat out-of-order arrivals as normal: a late update simply overwrites, so the apply must be last-write-wins by the source's own timestamp.
- Never assume the stream delivers changes for one row contiguously; batch consumers must handle interleaving.
- Keep the consume and the apply in one transaction so a partial failure cannot leave curated half-written.
Out-of-order arrivals deserve their own note. If two updates to the same order land in the same batch, the stream preserves both, and a MERGE that updates on every matched row will apply them in the order they appear in the change set â not in the order they happened. When the source carries an updated_at or version column, add a guard such as WHEN MATCHED AND s.updated_at > t.updated_at so a stale row in a later batch cannot overwrite a newer one.
Mistakes that silently drop or duplicate rows
Common Mistakes
Consuming the stream in a SELECT and applying in a separate transaction
Fix: The offset advances with the first transaction; do the drain and the MERGE inside one, or stage into a durable table first.
Treating the update's DELETE half as a real deletion
Fix: Filter with NOT (METADATA<MathBlock tex={`ACTION = 'DELETE' AND METADATA`} />ISUPDATE) before applying.
Assuming tasks resume automatically after creation
Fix: Tasks are created suspended; resume the children before the parents or the chain never starts.
Scheduling a task on a stream with no WHEN guard
Fix: Use SYSTEM$STREAM_HAS_DATA so idle streams do not burn warehouse credits every interval.
Applying changes without a natural key
Fix: MERGE on business keys so a replayed batch is idempotent rather than duplicative.
Ignoring out-of-order updates
Fix: Guard the MERGE with the source's version or updated_at so a stale row cannot overwrite a newer one.
Truncating staging before the apply transaction commits
Fix: Truncate after a successful apply; a rerun should re-read the same staged rows.
Believing a clone carries the source's stream offset
Fix: A clone starts with a fresh offset; create a timestamped stream explicitly for historical replays.
Practices that keep CDC trustworthy
Best Practices
- Separate capture, stage, and apply so each hop is independently retryable and inspectable.
- Put a WHEN STREAM_HAS_DATA guard on every scheduled drain task.
- Reconcile source and curated counts daily and alert on sustained drift.
- Keep curated apply operations keyed on natural keys with last-write-wins semantics.
- Snapshot with zero-copy clones before risky migrations or rule changes.
- Record the pipeline offset and task history alongside curated timestamps for auditability.
- Version-control the drain and apply logic as stored procedures so reruns are deterministic.
- Review task history after schedule changes; dependency chains do not auto-propagate.
Key takeaways
Key Takeaways
- Streams record the net effect of changes since the last consume, and consuming is transactional with the apply.
- Updates arrive as a delete half plus an insert half; filter the synthetic half before applying.
- A three-hop design â capture, stage, apply â makes every failure recoverable without re-extracting from the source.
- Tasks can drive the pipeline natively, but they start suspended and need a stream-data guard to avoid idle costs.
- Progress is measured by pending change volume, not by the last task run time.
- Time Travel and zero-copy clones provide replay without touching upstream systems.
- Exactly-once effects come from idempotent MERGEs, not from the stream's delivery guarantees alone.
Where to go next
- Streams and Tasks â the fundamentals these pipelines are built on.
- Tasks Advanced â dependency chains, forests, and operational patterns.
- SCD Types â how to model history in the curated layer.
- Time Travel Advanced â recovery windows and retention planning.