Web Analytics
HeyFreaks.com

How to Implement Change Data Capture Using Snowflake Streams?

8 min de lectură
0
Comentarii
21
Vizualizări

In modern data engineering, business information changes continuously. New customer records are added, existing orders are updated, and outdated information may be deleted. Processing an entire dataset every time a small change occurs can consume unnecessary computing resources and increase data processing time.

This is where Change Data Capture (CDC) plays an important role. CDC helps identify changes made to source data and process only the affected records instead of loading the complete dataset repeatedly.

Snowflake provides a built-in feature called Streams to capture changes in tables. It helps developers track inserted, updated, and deleted records and build efficient data processing workflows.

For professionals interested in learning modern data engineering concepts, Snowflake Training in Chennai provides an opportunity to understand Streams, Tasks, SQL transformations, and real-time data pipeline development.

Let's explore how to implement Change Data Capture using Snowflake Streams with a practical example.

1. What Is Change Data Capture (CDC)?

Change Data Capture is a technique used to identify and process changes made to data in a database.

Instead of extracting the complete table whenever new information arrives, CDC captures only the records that have been inserted, updated, or deleted.

For example, consider an e-commerce application that stores customer order information.

  • A new customer places an order.

  • An existing customer updates an order.

  • A customer cancels an order.

Rather than processing every order record again, a CDC pipeline identifies these changes and processes the affected records.

This approach helps reduce unnecessary data processing and keeps target tables synchronized with source data.

2. What Are Snowflake Streams?

Snowflake Streams are database objects that capture changes made to a table.

They maintain change tracking information using the source table's change data, allowing developers to identify which records have been inserted, updated, or deleted.

A Snowflake Stream does not store a complete copy of the source table. Instead, it provides change information between transactional points.

Streams support different types of change tracking:

  • Standard Streams: Track inserted, updated, and deleted records, including metadata about the changes.

  • Append-Only Streams: Track inserted rows only.

  • Insert-Only Streams: Capture inserted records, including certain changes associated with external tables and supported data sources.

For most standard CDC use cases involving regular Snowflake tables, a standard stream is a suitable starting point.

3. Create a Source Table

Let's build a simple CDC pipeline using customer order information.

First, create a database and schema:

CREATE DATABASE CDC_DB;

 

CREATE SCHEMA CDC_DB.SALES;

Now, create a source table:

CREATE OR REPLACE TABLE CUSTOMER_ORDERS (

    ORDER_ID NUMBER,

    CUSTOMER_NAME STRING,

    ORDER_AMOUNT NUMBER(10,2),

    ORDER_STATUS STRING

);

Insert some sample records:

INSERT INTO CUSTOMER_ORDERS VALUES

(101, 'Arun', 2500, 'PENDING'),

(102, 'Priya', 3500, 'COMPLETED'),

(103, 'Kumar', 1800, 'PENDING');

This table represents the original order information. We will use it to capture changes through a Snowflake Stream.

4. Create a Snowflake Stream

After creating the source table, the next step is to create a Stream.

Execute the following SQL command:

CREATE OR REPLACE STREAM CUSTOMER_ORDERS_STREAM

ON TABLE CUSTOMER_ORDERS;

The Stream is now configured to track changes made to the CUSTOMER_ORDERS table.

You can check the Stream information using:

SHOW STREAMS;

When a new record is inserted or an existing record is updated or deleted, the Stream makes the corresponding change information available for consumption.

5. Insert, Update, and Delete Records

Now let's perform some operations on the source table to understand how Streams capture changes.

Insert a new record:

INSERT INTO CUSTOMER_ORDERS VALUES

(104, 'Divya', 4200, 'PENDING');

Update an existing record:

UPDATE CUSTOMER_ORDERS

SET ORDER_STATUS = 'COMPLETED'

WHERE ORDER_ID = 101;

Delete an existing record:

DELETE FROM CUSTOMER_ORDERS

WHERE ORDER_ID = 103;

These operations create change records that can be read from the Stream.

6. Read Changes Using Stream Metadata

Snowflake provides metadata columns that help identify the type of change captured by a Stream.

Three important metadata columns are:

  • METADATA$ACTION: Identifies whether the change is an INSERT or DELETE.

  • METADATA$ISUPDATE: Indicates whether a record is associated with an UPDATE operation.

  • METADATA$ROW_ID: Provides a unique identifier for the tracked row.

You can retrieve the captured changes using:

SELECT

    ORDER_ID,

    CUSTOMER_NAME,

    ORDER_AMOUNT,

    ORDER_STATUS,

    METADATA$ACTION,

    METADATA$ISUPDATE

FROM CUSTOMER_ORDERS_STREAM;

For an UPDATE operation, a standard Stream generally exposes a DELETE record representing the old version and an INSERT record representing the new version. The METADATA$ISUPDATE column helps distinguish these update-related records from standalone insertions and deletions.

This information is useful when building CDC pipelines that need to maintain accurate target data.

7. Create a Target Table

The next step is to create a target table that stores the processed customer order information.

CREATE OR REPLACE TABLE CUSTOMER_ORDERS_TARGET (

    ORDER_ID NUMBER,

    CUSTOMER_NAME STRING,

    ORDER_AMOUNT NUMBER(10,2),

    ORDER_STATUS STRING

);

We will use this table to apply the changes captured by the Stream.

8. Process CDC Changes Using MERGE

The MERGE command helps insert new records, update existing records, and remove deleted records from the target table.

For this example, we can process the Stream using:

MERGE INTO CUSTOMER_ORDERS_TARGET T

USING (

    SELECT *

    FROM CUSTOMER_ORDERS_STREAM

    QUALIFY ROW_NUMBER() OVER (

        PARTITION BY ORDER_ID

        ORDER BY METADATA$ACTION

    ) = 1

) S

ON T.ORDER_ID = S.ORDER_ID

 

WHEN MATCHED AND S.METADATA$ACTION = 'DELETE'

THEN DELETE

 

WHEN MATCHED AND S.METADATA$ACTION = 'INSERT'

THEN UPDATE SET

    T.CUSTOMER_NAME = S.CUSTOMER_NAME,

    T.ORDER_AMOUNT = S.ORDER_AMOUNT,

    T.ORDER_STATUS = S.ORDER_STATUS

 

WHEN NOT MATCHED AND S.METADATA$ACTION = 'INSERT'

THEN INSERT (

    ORDER_ID,

    CUSTOMER_NAME,

    ORDER_AMOUNT,

    ORDER_STATUS

)

VALUES (

    S.ORDER_ID,

    S.CUSTOMER_NAME,

    S.ORDER_AMOUNT,

    S.ORDER_STATUS

);

This example demonstrates the basic MERGE approach. In production pipelines, the source changes should be deduplicated carefully, especially when a row has multiple changes within the same Stream offset. For updates, the new INSERT version should be selected rather than the old DELETE version.

After successfully consuming the Stream within the transaction, its offset advances, allowing the next processing cycle to capture subsequent changes.

9. Automate CDC Using Snowflake Tasks

Manually executing CDC queries every time new records arrive is not practical for large applications.

Snowflake Tasks help automate SQL operations based on a schedule or event-driven workflow.

For example, you can create a Task to process captured changes every five minutes:

CREATE OR REPLACE TASK CDC_PROCESS_TASK

WAREHOUSE = COMPUTE_WH

SCHEDULE = '5 MINUTE'

WHEN SYSTEM$STREAM_HAS_DATA(

    'CUSTOMER_ORDERS_STREAM'

)

AS

MERGE INTO CUSTOMER_ORDERS_TARGET T

USING CUSTOMER_ORDERS_STREAM S

ON T.ORDER_ID = S.ORDER_ID

 

WHEN MATCHED AND S.METADATA$ACTION = 'DELETE'

THEN DELETE

 

WHEN MATCHED AND S.METADATA$ACTION = 'INSERT'

THEN UPDATE SET

    T.CUSTOMER_NAME = S.CUSTOMER_NAME,

    T.ORDER_AMOUNT = S.ORDER_AMOUNT,

    T.ORDER_STATUS = S.ORDER_STATUS

 

WHEN NOT MATCHED AND S.METADATA$ACTION = 'INSERT'

THEN INSERT (

    ORDER_ID,

    CUSTOMER_NAME,

    ORDER_AMOUNT,

    ORDER_STATUS

)

VALUES (

    S.ORDER_ID,

    S.CUSTOMER_NAME,

    S.ORDER_AMOUNT,

    S.ORDER_STATUS

);

Enable the Task using:

ALTER TASK CDC_PROCESS_TASK RESUME;

This creates a scheduled CDC workflow that processes available changes automatically. For production use, configure appropriate permissions, error handling, and update handling for multiple changes to the same record.

10. Best Practices for Implementing CDC

When building CDC pipelines with Snowflake Streams, keep these points in mind:

  • Monitor Stream staleness and consume changes within the configured retention period.

  • Use MERGE for applying changes to target tables.

  • Handle duplicate records carefully.

  • Validate source and target data regularly.

  • Use Tasks to automate repetitive processing.

  • Monitor failed executions through task history.

  • Test INSERT, UPDATE, and DELETE operations before deploying pipelines.

Understanding these practices helps developers build reliable and maintainable data processing workflows.

Learners interested in practical CDC implementation, SQL development, and automated data engineering workflows can explore Best Snowflake Training in Coimbatore to gain hands-on experience with real-world Snowflake concepts.

Conclusion

Change Data Capture is an important technique for building efficient and scalable data pipelines. Snowflake Streams make it easier to identify changes in source tables without repeatedly processing complete datasets.

By combining Streams with SQL MERGE operations and Snowflake Tasks, developers can create automated workflows that handle inserted, updated, and deleted records.

At Qmatrix Technologies, learners can explore Snowflake architecture, Streams, Tasks, ETL pipelines, and real-time data engineering projects through practical training. Developing these skills can help aspiring Snowflake developers and data engineers understand how modern organizations manage continuously changing data.

 

Sponsorizat