CDC Patterns
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Understanding Change Data Capture (CDC) Patterns
Introduction: Why CDC Matters in Data Engineering
In modern data architecture, the ability to move data from operational databases to analytical systems—such as data warehouses, data lakes, or lakehouses—is a fundamental requirement. Historically, many organizations relied on "batch loading," where they would perform a full dump of a database table at regular intervals. As datasets grow into the multi-terabyte scale, this approach becomes prohibitively expensive, slow, and resource-intensive. This is where Change Data Capture (CDC) enters the picture.
Change Data Capture is a set of software design patterns used to determine and track the data that has changed so that action can be taken using the changed data. Instead of re-reading an entire table, CDC allows you to identify only the rows that were inserted, updated, or deleted since the last synchronization. This provides a way to maintain a near-real-time replica of your production database in your analytical environment, enabling faster decision-making and reducing the load on your primary transactional systems.
Understanding CDC is critical for any data engineer because it represents the transition from static, periodic reporting to dynamic, event-driven data streaming. By mastering these patterns, you can build systems that are more efficient, less prone to downtime, and capable of handling complex data integration requirements without overwhelming your production infrastructure.
Not read yet
Core Concepts: How CDC Works
At its heart, CDC is about identifying transitions in data state. When a user updates a record in a SQL database, that event is recorded in the transaction log. CDC mechanisms tap into these logs to extract the "delta"—the difference between the old state and the new state.
The Transaction Log Approach
Most relational database management systems (RDBMS) like PostgreSQL, MySQL, or SQL Server write every transaction to a log file before committing it to the database files. This log ensures data integrity in the event of a crash. CDC tools read these logs directly, which means they don't need to run expensive SELECT queries against your production tables. This is the most efficient form of CDC because it is non-invasive and provides a complete history of all changes, including deletions.
The Query-Based Approach
If you cannot access the database logs (for example, due to security restrictions or cloud platform limitations), you may have to rely on query-based CDC. This usually involves tracking a "watermark" column, such as an updated_at timestamp or an auto-incrementing version ID. While this is easier to implement, it has significant drawbacks: it cannot easily detect deleted records, and it adds additional load to your primary database.
Callout: Transaction Log vs. Query-Based CDC
The transaction log approach is generally superior because it is asynchronous, does not require schema modifications (like adding a timestamp column), and captures deletes. Query-based CDC is a fallback mechanism that is easier to set up but is limited by the schema design and can degrade production performance if queries are not optimized.
Not read yet
Implementing CDC: Practical Patterns and Techniques
Implementing CDC requires a combination of source extraction, message queuing, and target loading. Let’s break down the most common patterns used in the industry today.
1. Log-Based CDC (The Industry Standard)
The most common way to implement log-based CDC is by using a tool like Debezium. Debezium acts as a connector that reads the transaction logs of your source database and streams those changes as events into a message broker like Apache Kafka.
Step-by-Step Implementation:
- Enable Binary Logging: Configure your database (e.g., PostgreSQL or MySQL) to output logical replication logs.
- Deploy a Connector: Set up a connector (e.g., Debezium) to monitor these logs.
- Configure Kafka: Ensure you have a Kafka cluster to receive the change event stream.
- Consume and Load: Use a consumer (like a Spark job or a Snowflake Snowpipe) to read from Kafka and update your target destination.
Example: Debezium Configuration Snippet
{
"name": "inventory-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"database.hostname": "prod-db-server",
"database.port": "5432",
"database.user": "cdc_user",
"database.dbname": "orders_db",
"table.include.list": "public.orders",
"plugin.name": "pgoutput"
}
}
Explanation: This JSON configuration tells the Debezium connector how to connect to a PostgreSQL instance and which table to watch. The pgoutput plugin is the standard logical decoding plugin for Postgres, allowing the connector to read the transaction stream.
2. The Outbox Pattern
If you are working in a microservices environment where you cannot access the database logs directly, the "Transactional Outbox" pattern is a robust alternative. In this pattern, the application writes the business data and an "event" record to an outbox table within the same transaction. A separate process then polls this outbox table to publish events to a message queue.
Why use the Outbox Pattern?
- Atomicity: You ensure that the database state change and the event notification happen together.
- Decoupling: Your services don't need to know about the messaging infrastructure.
- Reliability: If the message broker is down, the event remains in the database until it can be successfully published.
Note: The Outbox Pattern requires your application code to be aware of the "CDC" requirement. Unlike pure log-based CDC, this approach requires developers to modify the application logic to include the outbox table writes.
Not read yet
Comparison of CDC Strategies
| Feature | Query-Based (Watermark) | Log-Based (Debezium/CDC) | Outbox Pattern |
|---|---|---|---|
| Setup Complexity | Low | High | Medium |
| Performance Impact | High | Very Low | Low |
| Deletes Captured | No | Yes | Yes (if handled) |
| Schema Changes | Requires columns | Transparent | Requires tables |
| Latency | High (Batch) | Near Real-Time | Near Real-Time |
Handling Deletions: The "Soft Delete" Problem
One of the biggest challenges in data engineering is handling deleted data. If you use a query-based approach (e.g., SELECT * FROM table WHERE updated_at > last_sync), a row that is deleted from the source will simply vanish from your target system without any notification. This creates a drift between your source and your analytical destination.
To avoid this, you have two primary options:
- Soft Deletes: Instead of running a
DELETEcommand, your application marks a record asis_deleted = true. This is easily picked up by query-based CDC. - Log-Based Capture: As mentioned, log-based CDC captures the actual
DELETEevent from the database transaction logs, allowing your downstream system to issue a correspondingDELETEor "tombstone" update in the data warehouse.
Warning: Never ignore deletions. If you are building a reporting dashboard, failing to capture deletions will lead to inaccurate totals, such as revenue reports that include orders that were actually cancelled or refunded.
Not read yet
Best Practices for CDC Pipelines
Building a CDC pipeline is not just about moving data; it is about ensuring that the data arrives accurately and in the correct order.
1. Schema Evolution Management
Database schemas change over time. If a developer adds a column to a source table, your CDC pipeline must be able to handle this change without crashing. Use a Schema Registry (common with Kafka) to track the evolution of your data structures. This allows your downstream consumers to adapt to new fields automatically.
2. Idempotency
Network failures are inevitable. Your target system must be able to handle duplicate events without corrupting the data. Ensure that every update/insert operation uses the primary key to perform an "upsert" (update if exists, insert if new) rather than just an "insert."
3. Monitoring and Alerting
CDC pipelines are often "silent" until they break. Monitor the "lag" between the source database and the target system. If the lag increases, it usually indicates that the consumer is struggling to process the volume of events or that the network connection is saturated.
Recommended Metrics to Track:
- Consumer Lag: How many messages are waiting in the queue?
- Error Rate: Are there malformed records that the pipeline cannot parse?
- Connection Health: Is the database connector still active?
Not read yet
Common Pitfalls and How to Avoid Them
Even with the best tools, engineers often fall into common traps when setting up CDC.
Pitfall 1: Overloading the Source Database
If you choose a query-based approach and your table is massive, a poorly optimized SELECT query can lock the table or consume all available I/O, slowing down the production application.
- Solution: Always use indexed columns for watermarking (e.g., a
created_atorupdated_atcolumn with a B-tree index). If the table is too large, consider partition-based incremental loading.
Pitfall 2: Ordering Issues
In distributed systems, events might arrive out of order. If an UPDATE event arrives before an INSERT event for the same record, your target system will fail.
- Solution: Use a partition key in your message broker (e.g., the primary key of the table). This ensures that all events for a specific row are sent to the same partition and processed in the correct order by the consumer.
Pitfall 3: Ignoring Large Transactions
A single massive transaction (e.g., deleting 1 million rows in one go) can overwhelm your CDC pipeline and cause a spike in latency.
- Solution: Break large operations into smaller batches at the application layer, or ensure your CDC connector is configured to handle large transaction bursts by increasing memory buffers.
Not read yet
Step-by-Step Guide: Building a Simple CDC Workflow
Let's walk through how you would set up a basic log-based CDC process using a hypothetical setup of Postgres, Kafka, and a Python consumer.
Step 1: Prepare the Source
Ensure your Postgres database is configured for logical replication.
-- Set the WAL level to logical
ALTER SYSTEM SET wal_level = 'logical';
-- Create a publication for the table
CREATE PUBLICATION db_changes FOR TABLE orders;
Step 2: Extract with Debezium
Deploy the Debezium connector. It will start streaming all INSERT, UPDATE, and DELETE operations from the orders table into a Kafka topic named db.public.orders.
Step 3: Consume with Python
Write a simple consumer that performs an upsert in your target data warehouse (e.g., BigQuery or Snowflake).
from kafka import KafkaConsumer
import json
consumer = KafkaConsumer('db.public.orders', bootstrap_servers='localhost:9092')
for message in consumer:
event = json.loads(message.value)
payload = event['payload']
# Extract operation type
op = payload['op']
data = payload['after'] if op != 'd' else payload['before']
if op in ['c', 'u']:
# Perform UPSERT in destination
upsert_to_warehouse(data)
elif op == 'd':
# Perform DELETE in destination
delete_from_warehouse(data['id'])
Explanation: This script listens to the Kafka topic. It inspects the op field (c=create, u=update, d=delete) to determine which action to take. It then uses the after state for inserts/updates and the before state for deletes to ensure the target matches the source.
Not read yet
Advanced CDC Considerations
Handling Multi-Table Joins
Sometimes you need to denormalize data from multiple tables before it hits the analytical store. You can achieve this by having multiple CDC connectors streaming to different Kafka topics, then using a stream processing engine like Apache Flink or Kafka Streams to join these streams in real-time. This allows you to create a "flat" view of your data before it is persisted in the data lake.
Data Privacy and PII
CDC streams often contain sensitive information. Since you are capturing the raw transaction logs, you might be capturing PII (Personally Identifiable Information). Ensure that your CDC pipeline has a masking layer that scrubs sensitive fields (like email addresses or phone numbers) before they reach the Kafka topic or the final storage destination.
The Cost of Real-Time
Do you actually need "real-time" data? Some business requirements are satisfied by 15-minute intervals. Implementing true real-time CDC adds significant complexity to your infrastructure. If your business stakeholders don't require sub-second latency, consider a micro-batch approach, which is often easier to debug and maintain.
Not read yet
Comparison Table: CDC vs. Traditional ETL
| Feature | Traditional ETL (Batch) | CDC (Streaming) |
|---|---|---|
| Source Load | High (during query) | Low (reading logs) |
| Latency | Hours/Days | Seconds/Milliseconds |
| Complexity | Low | High |
| Data Integrity | High (snapshot) | High (transactional) |
| Resource Usage | Periodic Spikes | Constant Stream |
Key Takeaways
- CDC is an Evolution: Moving from periodic batch dumps to CDC is a necessary step for organizations that require up-to-date data for analytics, machine learning, or operational dashboards.
- Prioritize Log-Based Methods: Whenever possible, use log-based CDC (e.g., Debezium) to avoid putting unnecessary load on your production database and to ensure that deletions are captured accurately.
- Handle Deletes Explicitly: Never assume that data will stay in your system forever. Always account for deletions, either through soft-delete flags or by capturing log-based delete events.
- Idempotency is Non-Negotiable: Because distributed systems fail, your target loaders must be built to handle the same event multiple times without duplicating data. Always use upsert logic.
- Monitor the Lag: A CDC pipeline is only as good as its freshness. Implement robust monitoring to track how far behind your analytical environment is from the production source.
- Schema Evolution: Treat your schema as a living entity. Use a schema registry to ensure that your downstream consumers are not broken by upstream database modifications.
- Right-Size the Solution: Don't build a complex real-time streaming architecture if a simple, scheduled micro-batch process meets your business requirements. Complexity carries a maintenance cost that should be justified by the value of the data freshness.
Not read yet
Common Questions (FAQ)
Q: Does CDC require changing my database schema?
A: Log-based CDC does not require schema changes. However, query-based CDC often requires adding a last_updated timestamp, and the Outbox pattern requires adding an outbox table.
Q: What happens if the CDC tool goes down for an hour? A: If you are using a tool like Debezium with Kafka, the tool will store the current "offset" (the position in the transaction log). Once the tool restarts, it will resume reading from exactly where it left off, ensuring no data is lost.
Q: Can I use CDC to sync data between two different database types (e.g., MySQL to PostgreSQL)? A: Yes. CDC captures the data change and turns it into a generic event format (like JSON). You can then consume that JSON and write it into any destination database, regardless of the source technology.
Q: Is CDC free? A: The patterns themselves are free, and many tools like Debezium are open-source. However, there is a cost associated with running the infrastructure (Kafka clusters, connector instances, and the target storage).
Q: How do I handle large initial loads? A: Most CDC tools support an "initial snapshot." When you first start the connector, it will perform a full read of the table to catch up, then automatically switch to streaming mode to capture only the changes that occurred during the snapshot.
By mastering these CDC patterns, you are moving beyond simple data movement into the realm of event-driven data engineering, providing your organization with the high-quality, timely information required for success. Always prioritize reliability, idempotency, and observability, and you will find that your data pipelines become the backbone of your analytical infrastructure.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Workspace Level Access Controls
- Workspace Level Access Controls Quiz5q
- Item Level Access Controls
- Item Level Access Controls Quiz5q
- Row and Column Level Security
- Row and Column Level Security Quiz5q
- Object and File Level Security
- Object and File Level Security Quiz5q
- Dynamic Data Masking
- Dynamic Data Masking Quiz5q
- Sensitivity Labels
- Sensitivity Labels Quiz5q
- Fabric Audit Logs
- Fabric Audit Logs Quiz5q
- OneLake Security Configuration
- OneLake Security Configuration Quiz5q
- Endorsing Items
- Endorsing Items Quiz5q
- Choosing Orchestration Tools
- Choosing Orchestration Tools Quiz5q
- Schedules and Event Triggers
- Schedules and Event Triggers Quiz5q
- Orchestration with Notebooks
- Orchestration with Notebooks Quiz5q
- Parameters and Dynamic Expressions
- Parameters and Dynamic Expressions Quiz5q
- Pipeline Patterns
- Pipeline Patterns Quiz5q
- Choosing Data Stores
- Choosing Data Stores Quiz5q
- Transformation Tool Selection
- Transformation Tool Selection Quiz5q
- OneLake Shortcuts
- OneLake Shortcuts Quiz5q
- Implementing Mirroring
- Implementing Mirroring Quiz5q
- Pipeline Data Ingestion
- Pipeline Data Ingestion Quiz5q
- PySpark Transformations
- PySpark Transformations Quiz5q
- SQL Transformations
- SQL Transformations Quiz5q
- KQL Transformations
- KQL Transformations Quiz5q
- Data Denormalization
- Data Denormalization Quiz5q
- Grouping and Aggregating Data
- Grouping and Aggregating Data Quiz5q
- Handling Duplicate Data
- Handling Duplicate Data Quiz5q
- Handling Missing and Late Data
- Handling Missing and Late Data Quiz5q
- Dataflows Gen2 Ingestion
- Dataflows Gen2 Ingestion Quiz5q
- Delta Lake Table Management
- Delta Lake Table Management Quiz5q
- Choosing Streaming Engine
- Choosing Streaming Engine Quiz5q
- Native Tables vs OneLake Shortcuts
- Native Tables vs OneLake Shortcuts Quiz5q
- Query Acceleration for Shortcuts
- Query Acceleration for Shortcuts Quiz5q
- Eventstreams Processing
- Eventstreams Processing Quiz5q
- Spark Structured Streaming
- Spark Structured Streaming Quiz5q
- KQL for Streaming
- KQL for Streaming Quiz5q
- Windowing Functions
- Windowing Functions Quiz5q
- Tumbling and Hopping Windows
- Tumbling and Hopping Windows Quiz5q
- Pipeline Error Resolution
- Pipeline Error Resolution Quiz5q
- Dataflow Gen2 Error Resolution
- Dataflow Gen2 Error Resolution Quiz5q
- Notebook Error Resolution
- Notebook Error Resolution Quiz5q
- Eventhouse Error Resolution
- Eventhouse Error Resolution Quiz5q
- Eventstream Error Resolution
- Eventstream Error Resolution Quiz5q
- T-SQL Error Resolution
- T-SQL Error Resolution Quiz5q
- OneLake Shortcut Error Resolution
- OneLake Shortcut Error Resolution Quiz5q
- Lakehouse Table Optimization
- Lakehouse Table Optimization Quiz5q
- Pipeline Optimization
- Pipeline Optimization Quiz5q
- Data Warehouse Optimization
- Data Warehouse Optimization Quiz5q
- Eventstreams and Eventhouses Optimization
- Eventstreams and Eventhouses Optimization Quiz5q
- Spark Performance Optimization
- Spark Performance Optimization Quiz5q
- Query Performance Optimization
- Query Performance Optimization Quiz5q
- V-Order Optimization
- V-Order Optimization Quiz5q
- Compaction and Vacuum
- Compaction and Vacuum Quiz5q
- Partitioning and Z-Order
- Partitioning and Z-Order Quiz5q
- Caching Strategies
- Caching Strategies Quiz5q
- Query Optimization Techniques
- Query Optimization Techniques Quiz5q
- Parallel Processing Configuration
- Parallel Processing Configuration Quiz5q
- Data Skew Resolution
- Data Skew Resolution Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-700 exam-style practice questions.
Practice for DP-700