Machine Learning pathway increased my salary by 40%
Change Data Capture and Replication
Capture every change from operational systems without querying production tables: log-based CDC architecture, initial snapshots, schema history, delete handling, exactly-once delivery and the operational controls that keep replication trustworthy at scale.
Executive Summary
Change data capture is the difference between knowing what a system contains and knowing how it changed. Query-based extraction answers the first question and fails at the second: updates during the extraction window are lost, deletes are invisible, and repeated scans load production systems. Log-based capture reads the transaction log and produces an ordered stream of inserts, updates and deletes with minimal source impact. That accuracy is what makes CDC the foundation for real-time analytics, cache invalidation, search indexing and event-driven integration. It also introduces its own risks: an initial snapshot that never completes, schema changes that break the stream, replication slots that fill a disk, and downstream consumers that cannot handle out-of-order delivery. This topic covers CDC architecture, snapshot and streaming phases, schema history, delivery guarantees, operational failure modes and the design of downstream consumers that can trust the stream.
Definition
Change data capture is a technique for identifying and delivering the changes made to a data source, typically by reading the database transaction log rather than querying tables. It produces a change stream containing the operation type, the affected row, the before and after values, the transaction position and a timestamp. Replication is the broader practice of maintaining a copy of data in another system, which CDC enables with low latency and low source impact. A complete CDC implementation has two phases: an initial consistent snapshot that establishes a baseline, and continuous streaming that applies changes from the point where the snapshot was taken. Correctness depends on the boundary between those phases being exact, on schema history being preserved so old events remain interpretable, and on consumers handling at-least-once delivery with idempotent application.
Why It Matters
Most operational questions are about change rather than state: what orders were modified, which prices changed, when a customer record was updated, what a record looked like before an edit. Query-based extraction cannot answer these reliably and burdens production databases with repeated scans. CDC answers them natively and enables real-time features that batch extraction cannot support. It also removes a class of silent failure: watermark-based polling misses updates made during the extraction window and never sees deletes, producing a platform that is confidently wrong. The cost is operational complexity, and organisations that adopt CDC without understanding snapshot boundaries, schema history and slot management create a new set of incidents in place of the old ones.
Evolution of the Technology
Triggers and Audit Tables -> Timestamp Polling -> Log-Based CDC -> Streaming Platforms with CDC -> Event-Native Operational Data. Early approaches used database triggers writing to audit tables, which added write overhead to production. Timestamp polling was simpler but missed updates and deletes. Log-based capture, popularised by tools such as Debezium reading the write-ahead log, delivered accurate change streams with negligible source impact. Streaming platforms then made those streams durable and replayable. The current direction is event-native operational data, where the change stream is the system of record for downstream consumers and batch views are derived projections.
Learning Objectives
- Explain how log-based CDC differs from query-based extraction
- Design a consistent initial snapshot with an exact streaming boundary
- Preserve and apply schema history so old events remain interpretable
- Handle inserts, updates, deletes and tombstones correctly downstream
- Choose delivery semantics and implement idempotent consumers
- Size and monitor replication slots to prevent source-side outages
- Design partitioning and ordering guarantees for a change stream
- Recover from a broken stream without full re-snapshot
- Test CDC correctness with reconciliation against source state
- Operate CDC connectors with ownership and service levels
Prerequisites
- Working knowledge of relational databases and transactions
- Familiarity with message queues or streaming platforms
- Understanding of data ingestion patterns
- Experience operating a production pipeline
Log-Based Capture and the Change Event
Databases write every modification to a log before applying it: the write-ahead log in PostgreSQL, the binary log in MySQL, the redo log in Oracle, the transaction log in SQL Server. Log-based CDC reads that log and translates each entry into a change event. A well-formed change event contains the operation type, the table, the key, the before and after images where available, the transaction identifier, the log position and a commit timestamp. That structure is what makes downstream processing possible: the key enables idempotent upsert, the before image enables audit and reversal, the position enables checkpointing and replay, and the timestamp enables time-based processing despite clock differences. Not every database provides before images or commit timestamps at equal cost, so the achievable event richness varies by source. Documenting what each source actually provides prevents designs that assume audit capability the source cannot deliver.
Change Event Structure
| Field | Purpose | If Missing |
|---|---|---|
| Operation type | Distinguishes insert, update, delete | Deletes appear as stale rows |
| Key | Enables idempotent application | Duplicates on replay |
| Before image | Audit and reversal | No history of prior values |
| After image | Current state application | Cannot apply updates directly |
| Log position | Checkpoint and replay | Recovery requires full resnapshot |
| Commit timestamp | Time-based processing | Ordering relies on arrival time |
Snapshot, Streaming and the Exact Boundary
CDC starts with a snapshot: a consistent read of every table that establishes a baseline. Streaming then begins from a log position that corresponds exactly to the snapshot point. Getting that boundary right is the core correctness problem. If streaming starts after the snapshot began, changes committed during the snapshot are lost. If it starts before, changes are applied twice, which is acceptable only if consumers are idempotent. A well-implemented connector records the log position at snapshot start, holds a read-consistent view for the duration, and then streams from that recorded position, applying changes that occurred during the snapshot on top of it. Long snapshots introduce practical problems: replication slots retain log segments for the whole duration, which can fill a disk on a busy source. Incremental or chunked snapshots reduce that window by capturing tables in segments while streaming continues, at the cost of more complex state tracking.
Snapshot Strategies
| Strategy | Mechanism | Trade-off |
|---|---|---|
| Initial consistent snapshot | Single read view, then stream from start position | Simple, but holds log segments for the duration |
| Chunked snapshot | Capture tables in segments while streaming | Shorter log retention, more state to manage |
| Incremental snapshot | Watermark-based chunks with change overlay | Low source impact, complex merge logic |
| No snapshot, stream only | Consume from a chosen position | Fast, but no historical baseline |
Schema History and Interpretability
A change stream is long-lived, and the schema it describes does not stay still. An event produced in March must remain interpretable in December, after two column additions and one rename. This is why CDC implementations maintain a schema history: a record of every schema version with the log position at which it took effect, so that a consumer reading an old event can resolve the structure that applied at that moment. Without schema history, old events become ambiguous, and reprocessing after an incident produces corrupted results. Practical implications follow. Schema history must be stored durably and backed up, because losing it makes the stream unreadable. Breaking changes such as column drops or type narrowing should be coordinated, since they cannot be represented additively. Consumers should deserialise against the schema version in the event rather than the current schema, and they should treat unknown fields as forward-compatible additions rather than errors.
Schema Change Impact on Streams
| Change | Stream Impact | Required Action |
|---|---|---|
| Add nullable column | Additive | None, consumers ignore unknown fields |
| Widen type | Compatible | Update target types before consumption |
| Rename column | Breaking | Coordinate, keep both during transition |
| Drop column | Breaking | Historical events lose a field |
| Narrow type | Breaking | Risk of truncation on apply |
| Change primary key | Severe | Requires resnapshot and consumer redesign |
Delivery Semantics and Idempotent Application
CDC connectors typically provide at-least-once delivery: every change is delivered, but a restart may deliver some twice. Exactly-once end to end is achievable only when the consumer can commit its write and its checkpoint atomically, which is possible in some streaming engines and transactional stores and not in others. The practical answer is to design consumers that are idempotent, so duplicate delivery is harmless. Idempotent application uses the change key and the log position: an upsert keyed on the primary key converges regardless of duplicates, and a deduplication table of recently applied positions rejects repeats within a window. Deletes require explicit handling, since an upsert cannot express absence; tombstones or delete markers must be applied as deletions, and soft-delete patterns in the source must be interpreted rather than assumed. Ordering also matters: changes to the same key must be applied in order, which means partitioning by key and avoiding parallelism within a key.
Consumer Idempotency Patterns
| Pattern | Mechanism | Limitation |
|---|---|---|
| Keyed upsert | Merge on primary key | Cannot express deletes |
| Position deduplication | Track applied log positions | Requires bounded state |
| Transactional apply | Write and checkpoint in one transaction | Engine-dependent |
| Partition by key | Ordered processing per key | Limits parallelism per key |
| Tombstone handling | Apply deletes explicitly | Requires source delete visibility |
Initial Snapshot to Continuous Replication
Establishing a baseline and streaming without gaps
Recovery from a Broken Stream
Restoring replication without a full resnapshot
Replication Slots and Source-Side Risk
Log-based CDC imposes a subtle dependency on the source: the database must retain log segments until the consumer has read them. In PostgreSQL this is a replication slot, in MySQL a binary log retention window, and in each case an unconsumed backlog consumes disk on the production server. The failure mode is severe and predictable: a connector stops, the slot retains logs, the disk fills, and the production database becomes read-only or unavailable. The incident is caused by the analytics platform but experienced by the business. Controls follow directly. Alert on retained log size and on slot lag, not only on connector health. Set a maximum retention that fails the slot safely rather than filling the disk, and accept that a failed slot means a resnapshot. Pause slots during planned maintenance windows rather than leaving them to accumulate. Treat connector health as a production-critical dependency with an escalation path to the platform team, because the blast radius is the operational system rather than the warehouse.
Source-Side CDC Risks
| Risk | Cause | Control |
|---|---|---|
| Disk exhaustion | Unconsumed replication slot | Alert on retained size, cap retention |
| Write amplification | Triggers used instead of log reading | Use log-based capture only |
| Long snapshot lock | Read-consistent view held too long | Chunked or incremental snapshot |
| Log purge before consume | Retention window too short | Coordinate retention with lag budget |
| Credential over-privilege | Replication user with broad rights | Minimum privileges for log reading |
Downstream Consumers That Can Trust the Stream
A change stream is only useful if consumers can rely on its properties. That requires explicit guarantees rather than optimism. Ordering should be guaranteed per key by partitioning on the key, with the trade-off that a single hot key limits throughput. Completeness should be asserted by reconciliation against source state rather than by trusting the connector, because a gap in the stream is invisible without comparison. Latency should be measured from source commit to downstream availability, not from connector read, since the difference is where lag hides. Deletes must be representable in the target, which means the target store needs either physical deletion or a tombstone column with filtering at read time. Finally, consumers should be able to rebuild from the raw change log, which requires retaining it long enough to matter and structuring it so that replay produces a deterministic result. Consumers that cannot be rebuilt are consumers that cannot be repaired.
Consumer Guarantees
| Guarantee | Mechanism | Verification |
|---|---|---|
| Per-key ordering | Partition by key | Sequence checks per key |
| Completeness | Reconciliation against source | Count and checksum comparison |
| Latency | Commit timestamp to availability | End-to-end lag metric |
| Delete visibility | Tombstones or physical delete | Absence assertions in tests |
| Rebuildability | Retained raw change log | Periodic replay drill |
Frameworks & Standards
CDC frameworks provide structure for correctness, operation and recovery so that replication is engineered rather than improvised.
CDC Frameworks
| Framework | Focus | Use |
|---|---|---|
| Snapshot-then-stream | Exact boundary correctness | Every new connector |
| Schema history | Long-term interpretability | Any stream retained beyond days |
| Idempotent consumer | Safe duplicate handling | All downstream appliers |
| Slot hygiene | Source-side safety | PostgreSQL and MySQL sources |
| Reconciliation | Proving equivalence | Financial and operational data |
Tools & Technologies
| Category | Tools | Use Case |
|---|---|---|
| CDC connectors | Debezium, Kafka Connect, Airbyte CDC, native replication | Log-based capture from operational databases |
| Streaming platform | Kafka, Kinesis, Pulsar, Redpanda | Durable, replayable change streams |
| Stream processing | Flink, Spark Structured Streaming, Kafka Streams | Applying changes to targets |
| Target stores | Iceberg, Delta Lake, warehouse tables, search indexes | Idempotent upsert and delete application |
| Schema registry | Confluent Schema Registry, Apicurio | Schema versioning and compatibility checks |
| Monitoring | Prometheus, connector metrics, custom lag dashboards | Slot lag, consumer lag and completeness |
| Reconciliation | Custom SQL checks, data diff tooling | Comparing platform state with source |
| Orchestration | Airflow, Dagster | Snapshot scheduling and recovery workflows |
Query-Based Extraction vs Log-Based CDC
| Aspect | Query-Based | Log-Based CDC |
|---|---|---|
| Captures deletes | No | Yes |
| Misses mid-window updates | Frequently | No |
| Source load | Scans and read replicas | Log read, minimal |
| Latency | Minutes to hours | Seconds |
| Operational complexity | Low | Moderate to high |
| Schema history | Not applicable | Required |
Enterprise Use Cases
Case Studies
Problem: A CDC connector stopped after a credential expired. Its replication slot retained four days of write-ahead logs, filling the primary disk and making the operational database read-only during trading hours.
Architecture: Introduced slot lag and retained-size alerting, capped retention so the slot fails before the disk fills, moved credentials to automated rotation, and added a runbook that prioritises pausing the slot over protecting the stream.
Outcome: The failure mode became a bounded connector restart rather than a production outage, and the alert fired on a test drill within ninety seconds.
Lessons: CDC creates a dependency in the opposite direction from most data work: the analytics platform can take down the operational system.
Problem: A connector was configured to begin streaming from the current position after the snapshot completed. Changes committed during the nine-hour snapshot were never captured, leaving a permanent gap in order history.
Architecture: Recorded the log position at snapshot start rather than completion, applied changes occurring during the snapshot on top of it, and added reconciliation comparing platform row counts and checksums against source per table.
Outcome: The historical gap was identified by reconciliation and repaired from retained logs, and new connectors use the corrected boundary by default.
Lessons: The snapshot boundary is the single most important correctness detail in CDC and the easiest to get subtly wrong.
Implementation Steps
Enterprise SOPs
Purpose: Recover replication without source impact
Owner: Data Platform Engineering
Steps: Check slot lag and retained size first, pause slot if disk pressure exists, inspect connector state and last committed position, verify schema history, restart from committed position, reconcile state, record incident
Evidence: Slot metrics, connector logs, reconciliation results, incident record
Purpose: Handle source schema changes without breaking streams
Owner: Data Platform Team with source owner
Steps: Receive change notice, classify additive, compatible or breaking, test against a replica, update target types, deploy consumers before source change, verify after change
Evidence: Change notice, classification, test results, deployment records
Purpose: Add a source safely
Owner: Ingestion Engineering
Steps: Confirm log access and privileges, size retention, choose snapshot strategy, record boundary position, configure schema history, build idempotent consumer, reconcile, set alerts, document runbook
Evidence: Access records, snapshot plan, boundary record, reconciliation output, alert configuration
Implement CDC for an Order and Inventory Platform
Problem: An order platform needs real-time inventory availability and search indexing. Current nightly extracts miss mid-day price changes, cannot represent cancelled orders, and place heavy read load on the production database during peak trading.
- Log-based capture from the order and inventory databases with minimal source impact
- Chunked snapshot to limit replication slot retention during initial load
- Schema history retained so events remain interpretable after column changes
- Idempotent consumers applying changes by key with explicit delete handling
- Per-key ordering for inventory to prevent oversell
- Slot lag and retained-size alerting with a defined safe-failure policy
Architecture: Debezium connectors read the database logs and publish to a streaming platform partitioned by primary key. The initial load uses chunked snapshots with the log position recorded at start. A schema registry stores versions with effective positions. Consumers apply changes idempotently, handle tombstones for cancellations, and write to search indexes and an availability service. Reconciliation compares row counts and checksums against source per table each hour, and slot metrics alert at defined thresholds before disk pressure occurs.
Outcome: Inventory reflects cancellations within seconds, search indexing follows price changes, production read load from extraction disappears, and the source database is protected by bounded slot retention.
Key Metrics & KPIs
Risks & Mitigation
Maturity Model
Future Roadmap
2026 Trends & Emerging Developments
Career Applications
Frequently Asked Questions
Research References
Continue this lesson with a subscription
Data Engineering & Intelligent Data Platforms is part of the paid catalogue. You have read the free preview. A subscription opens the rest of this lesson, the classroom slides and the assessment questions.
- The full lesson for this topic and every other catalogue topic
- Every classroom slide deck and worked example
- All assessments, with a verifiable certificate on completion
The Free-To-Learn library stays open to everyone and is not affected by this.
