Prerequisites
- !How a transaction log works in a database
- !The difference between batch extract and continuous replication
- !Basic SQL merge operations
What You'll Learn
- 1Explain why reading a transaction log beats polling a modified timestamp
- 2Compare ADF CDC, Debezium and Cosmos DB change feed on real criteria
- 3Run a snapshot handover into log-based capture without a gap
- 4Make a CDC consumer idempotent under at-least-once delivery
- 5Handle schema changes and slowly changing history downstream
Why polling timestamps loses data
The naive approach to keeping a warehouse in sync is to query rows where a modified timestamp is greater than the last watermark. It fails in three ways that are worth naming precisely. Rows updated with a timestamp that goes backwards, through clock skew or an application setting the value itself, are skipped. Rows updated twice within the same polling interval collapse into one change, losing intermediate history. And a row deleted between polls simply never appears.
Reading the database's own transaction log removes all three. The log is the database's authoritative record of what happened, in order, including deletes and the before-image of updates. Capture reads it rather than inferring change from the current state, so nothing depends on a timestamp being correct or a row still existing at query time.
The cost of that correctness is coupling. Log-based capture needs access to the log, which means privileges on the source, a connector that understands its format, and tolerance for the source's log retention window. If the consumer falls behind longer than the log is retained, the missing changes cannot be replayed, which becomes the most important operational number in the whole design.
| Approach | Mechanism | Sees deletes | Source impact | Operational burden |
|---|---|---|---|---|
| Timestamp polling | Query on a modified column | No | Repeated full or indexed scans | Low to build, silently wrong |
| Snapshot plus log CDC | Initial copy, then transaction log | Yes | Log read, brief initial lock risk | Moderate |
| Trigger-based capture | Rows written to a shadow table | Yes | Extra writes on every change | High, invasive to the schema |
| Cosmos DB change feed | Ordered log of inserts and updates | No, by default | Native, no source instrumentation | Low for Cosmos sources |
Snapshot handover: the moment CDC usually breaks
Log-based capture is not standalone. You need an initial snapshot of existing data, and then capture of changes that occur from some point onward. The handover between those two phases is where gaps and duplicates are introduced.
The safe sequence is: record the current log position, take the snapshot, start capture from that recorded position, then reconcile. Changes that happened during the snapshot exist both in the snapshot and in the log, so the consumer must tolerate overlap by applying changes idempotently. The alternative, snapshotting without recording a position first, leaves a window during which changes are captured by neither phase.
{
"name": "cdc_orders_to_lake",
"type": "Copy",
"typeProperties": {
"source": {
"type": "SqlServerSource",
"enableCDC": true,
"captureInstance": "dbo_Orders"
},
"sink": {
"type": "AzureBlobFSWriteSettings",
"formatSettings": { "type": "ParquetSettings" }
},
"enableStaging": true
},
"policy": { "retry": 3, "retryIntervalInSeconds": 60 }
}
ADF's CDC source reads from the change table that SQL Server maintains, and it tracks its own watermark between runs so a failed run resumes rather than restarting. The prerequisite is that capture is enabled on the database and on the specific table, and that the capture instance name matches, which is the most common reason a first run returns nothing.
Debezium and the log connector model
Debezium runs connectors, typically on Kafka, that read a database's log and emit change events with a consistent envelope: a before image, an after image, an operation code and the source transaction metadata. Because it is built on Kafka, throughput, replay and fan-out come from the log rather than from the connector.
The ordering guarantee is per partition, and the connector decides how records are assigned to partitions. By default a table's changes may be spread across partitions, which is fine for throughput and wrong if downstream processing must see a single entity's changes in order. Keying by the primary key keeps an entity together and costs some parallelism.
Delivery semantics are at-least-once, so duplicates happen, particularly after a connector restart. The consumer must therefore be idempotent: upsert on the primary key with a source log position attached, so a replayed event with an older position does not overwrite newer state.
from confluent_kafka import Consumer, KafkaError
import json
def make_consumer(group_id):
return Consumer({
"bootstrap.servers": "kafka:9092",
"group.id": group_id,
"enable.auto.commit": False,
"auto.offset.reset": "earliest",
})
def apply_change(doc, event):
op = event["op"]
payload = event["after"] or event["before"]
position = event["source"]["lsn"]
existing = read_current(payload["id"])
if existing and existing["lsn"] >= position:
return "skipped_stale"
if op in ("c", "u", "r"):
upsert(payload, lsn=position)
return "written"
if op == "d":
soft_delete(payload["id"], lsn=position)
return "deleted"
return "ignored"
The stale-position check is the whole idempotency story in three lines. It makes replay harmless regardless of how many times Kafka redelivers the same record, and it turns ordering errors from corruption into no-ops.
Cosmos DB change feed: native and bounded
The change feed is a ordered, per-partition log of inserts and updates in a container. It does not require any source instrumentation because the store itself maintains it, which makes it the least invasive option in the list and the reason Cosmos-to-lake pipelines are so straightforward.
Two properties matter. The feed is ordered within a partition and not across partitions, so any global ordering requirement must be reconstructed from the event metadata. And the change feed gives you a position to read from, which consumers use either through a processor library that manages checkpoints or through an API that lets you start from an explicit continuation token.
var iterator = container.GetItemChangeFeedStreamIterator(
changeFeedOptions: new ChangeFeedIteratorOptions
{
StartFrom = ChangeFeedStartFrom.Now,
MaximumItemCount = 500,
InstanceName = $"processor-{Environment.MachineName}"
});
while (iterator.HasMoreResults)
{
using var response = await iterator.ReadNextAsync();
foreach (var document in response.Resource)
{
await UpsertToLake(document);
await checkpointStore.Save(iterator.ReadContinuation);
}
}
Checkpointing after the write, never before, is the rule. Checkpoint first and a crash between the two loses the document; write first and a crash repeats it, which an idempotent upsert absorbs. Note also that the change feed does not emit deletes unless the container is configured with a delete policy, which is a gap teams discover only when reconciling counts.
Ordering, history and the serving layer
Deciding what to do with the change stream is a modelling question. The simplest outcome is a current-state table: apply changes by primary key and only the latest version survives. That is right for an operational mirror and wrong for anything that asks how a value looked last quarter.
Type two history requires the consumer to interpret operation codes and effective timestamps rather than blindly upserting. Inserts become new versions, updates close the current version and open another, and deletes either close the version or mark the record inactive depending on the retention rule.
Where duplicates are possible, a deterministic ordering key removes ambiguity. The source log position, the transaction ID and the operation sequence together give a total order per entity, so any two consumers applying the same stream reach the same final state. Without it, two workers racing on the same entity can converge on different values and neither will report an error.
Schema change and operational monitoring
Producers evolve schemas. A connector emitting a new column downstream will either fail the deserialisation or silently default the field, depending on the configuration, and both outcomes deserve a deliberate choice. The safe pattern is additive-only changes with a schema registry and a compatibility mode that rejects breaking changes at the producer, giving consumers time to adapt.
Monitoring a CDC pipeline means watching four numbers: consumer lag against the source log position, the age of the oldest unprocessed change, the count of malformed or rejected events, and the gap between source and target row counts. The third and fourth catch correctness problems that the first two will never show.
# Where is the consumer relative to the source log?
az data-factory pipeline-run query \
--factory-name adf-prod \
--last-updated-after 2026-10-11T00:00:00Z \
--filters '[{"columnName":"Status","operator":"NotEquals","value":"Succeeded"}]' \
-o table
# Reconcile row counts between source and target
sqlcmd -S erp-prod -Q "SELECT COUNT(*) AS src FROM dbo.Orders"
az storage fs file list -f bronze --path orders/dt=2026-10/ \
--account-name stdatalake --query "length(@)" -o tsv
A persistent count gap with healthy lag means correctness is wrong somewhere, usually in the handover or in filtering. Healthy counts with growing lag means capacity is wrong. Those two diagnoses lead to completely different fixes, which is why both metrics should be on the same dashboard.
Common Mistakes
Starting the snapshot without recording the log position first
Fix: Record the position before snapshotting and replay the log from that point, tolerating overlap through idempotent applies
Assuming at-least-once delivery will not produce duplicates
Fix: Upsert keyed on the natural key with a source log position, so a stale replay becomes a no-op
Relying on a modified timestamp column for change detection
Fix: Read the transaction log, since timestamps miss deletes, collapse rapid updates and break under clock skew
Watching only consumer lag
Fix: Also track source-to-target row counts and malformed event counts, which expose correctness failures lag cannot see
Best Practices
- Partition or key change events so one entity's changes stay ordered together
- Checkpoint only after the downstream write succeeds
- Reject breaking schema changes at the producer through a registry compatibility mode
- Keep source log retention longer than the worst plausible consumer outage
Interview Questions
Q1: Why is log-based CDC more correct than polling a modified timestamp?
The log is the database's authoritative ordered record including deletes and before-images. Timestamp polling misses deletions, collapses rapid updates and skips rows affected by clock skew.
Q2: How do you avoid a gap between snapshot and capture?
Record the log position before taking the snapshot, then start capture from that position and let the consumer tolerate the resulting overlap idempotently.
Q3: What delivery semantics does Debezium provide and how do you handle them?
At-least-once, so duplicates occur especially around restarts. Consumers upsert on the primary key and compare the source log position so stale replays are ignored.
Q4: What does the Cosmos DB change feed not tell you?
By default it emits inserts and updates, not deletes, and ordering is per partition rather than global, so delete handling and global ordering must be added by the consumer.
Q5: How do you detect a correctness problem in a CDC pipeline?
Reconcile source and target row counts and track malformed event counts. Lag can be perfectly healthy while the target is missing rows entirely.
Key Takeaways
- Change capture reads the transaction log instead of inferring change from current state
- The snapshot-to-log handover is the classic source of gaps and duplicates
- At-least-once delivery makes consumer idempotency mandatory, not optional
- Ordering exists per key or per partition, so the key choice defines correctness
- Lag measures capacity; row-count reconciliation measures correctness