Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 41

Incremental Data Loading with Spark and Delta Lake

This lesson is built with resources from youtube.com, medium.com and 1 more site.

Hello! Welcome back to our journey into practical data architecture.

In our last lesson, we tackled Slowly Changing Dimensions, focusing on how to preserve historical truth in our dimension tables using Delta Lake's MERGE command. Today, we'll continue to build on the theme of creating efficient and robust pipelines. Instead of focusing on what data we're changing, we'll focus on how much data we process in each pipeline run.

Your learning outcome for this lesson is to implement a high-watermark incremental load for a batch pipeline using Spark and Delta Lake. This is a fundamental technique that separates scalable, cost-effective data systems from brittle and expensive ones. Moving from full data reloads to incremental processing is a critical step for any data architect.

1. The Core Concept: Full vs. Incremental Loading

In many data scenarios, especially as you move from bronze to silver layers, you don't need to reprocess the entire history of your data every time the pipeline runs. Doing so is wasteful, consuming unnecessary time and cloud compute resources.

  • Full Load: Erases the target table and reloads everything from the source. Simple, but inefficient and not scalable.
  • Incremental Load: Processes only the new or updated records since the last successful run. This is the goal for most production batch pipelines.

To do this, the pipeline needs a "bookmark" to remember where it left off. This bookmark is called a high-watermark. It's typically the maximum value of a column that reliably increases over time, like a last_updated_timestamp or a sequential ID.

The workflow is straightforward, as illustrated in the diagram below.

High-Watermark Incremental Load Workflow
This flowchart shows the high-watermark process: 1. Get the old watermark from the last run. 2. Get the new, current watermark from the source. 3. Load only the data between these two watermarks. 4. Update the stored watermark to the new one for the next run.

Let's ground these concepts in a more detailed explanation.

Unlocking Data Pipeline Performance: Mastering Incremental ...

The article 'Unlocking Data Pipeline Performance' provides an excellent overview of why incremental loading is so critical and introduces the core concepts of using watermarks and idempotent MERGE operations.

Please read the first two main sections, starting from 'Why Incremental Loading is the Engine...' down to the end of 'The Core Challenge...'. Focus on the distinction between full and incremental loads and the conceptual PySpark example that shows how a watermark is used to filter data.


2. The Classic High-Watermark Implementation

Now, let's translate the concept into a practical implementation using PySpark and Delta Lake. We'll build a pipeline that incrementally syncs data from a source table to a target table using a timestamp column as our watermark.

The architectural pattern involves three key components:

  1. Source Table: The table containing the data to be processed (e.g., bronze_orders), which must have a reliable watermark column (e.g., updated_at).
  2. Target Table: The destination for the data (e.g., silver_orders).
  3. Control Table: A small, persistent table used to store the high-watermark value between pipeline runs.

Here are the steps you would implement in a Databricks notebook:

Step 1: Get the Last High-Watermark

First, you query your control table to get the starting point for this run.

# Assume 'control_table' stores our watermarks
# We retrieve the last successful watermark for our specific pipeline
try:
    last_watermark_df = spark.sql("SELECT watermark_value FROM control_table WHERE pipeline_name = 'silver_orders'")
    last_watermark = last_watermark_df.collect()[0]['watermark_value']
except:
    # Handle the very first run where the control table or entry might not exist
    last_watermark = '1970-01-01 00:00:00' 

Step 2: Extract Incremental Data from the Source

Using the watermark, you filter the source table to get only the new or updated records. You also determine the new high-watermark from this incremental batch.

# Read new/updated data from the source table
incremental_df = spark.table("bronze_orders").where(f"updated_at > '{last_watermark}'")

# It's good practice to cache this DataFrame if you'll use it multiple times
incremental_df.cache()

# Find the new high-watermark from the data we just read
if not incremental_df.isEmpty():
    new_high_watermark = incremental_df.agg({"updated_at": "max"}).collect()[0][0]
else:
    # If no new data, the new watermark is the same as the old one
    new_high_watermark = last_watermark

Step 3: Load Data into the Target using MERGE

You use a MERGE operation to idempotently apply these changes to the target table. This ensures that if you re-run the pipeline with the same data, you won't create duplicates. This leverages the same MERGE skills from our previous lesson on SCDs.

from delta.tables import DeltaTable

silver_orders_table = DeltaTable.forName(spark, "silver_orders")

(silver_orders_table.alias("target")
  .merge(
    incremental_df.alias("source"),
    "target.order_id = source.order_id" # The merge key
  )
  .whenMatchedUpdateAll() # Update existing orders
  .whenNotMatchedInsertAll() # Insert new orders
  .execute())

Step 4: Update the High-Watermark

Finally, after the data has been successfully loaded, you update the control table with the new high-watermark. This is the most critical step to ensure the next run starts from the correct place.

# Update the control table for the next run
spark.sql(f"""
    UPDATE control_table
    SET watermark_value = '{new_high_watermark}'
    WHERE pipeline_name = 'silver_orders'
""")

# Clear the cache
incremental_df.unpersist()
Test your understanding!

In our classic high-watermark pipeline, imagine the job successfully merges data into the silver_orders table but fails right before it can update the watermark in the control_table. What would happen on the next run? How does the use of the MERGE command help mitigate any potential issues?

Show answer

On the next run, the pipeline would read the same old watermark and process the same batch of data again. However, this is not a disaster. Because we are using an idempotent MERGE operation with a unique order_id key, it would simply find matches for all the records and update them with the same data. It would not insert duplicate records. This ensures data integrity even if parts of the pipeline are re-run.


3. A Modern Alternative: Delta Lake's Change Data Feed (CDF)

The classic high-watermark pattern is robust and widely applicable. However, it relies on you having a reliable timestamp or sequential ID column. What if a record is deleted? A timestamp-based approach won't capture that.

Delta Lake provides a more powerful, built-in mechanism for incremental processing: Change Data Feed (CDF).

When you enable CDF on a Delta table, Delta automatically records all INSERTs, UPDATEs, and DELETEs in the transaction log. You can then query these changes directly, using the table's version number as your watermark. This is often more reliable and performant than a manual timestamp-based approach.

Let's explore how to implement this.

Incremental Load using Change Data Feed in Databricks

The article 'Incremental Load using Change Data Feed in Databricks' provides a concise, step-by-step tutorial on this exact pattern. It's a perfect practical guide.

Please read the entire article. It will walk you through enabling CDF, creating a control table to store the version number (the watermark), reading the changes, and merging them into a target table. Pay close attention to how the table_changes() function is used and how the _change_type column simplifies the MERGE logic.

As the article demonstrates, the CDF pattern follows similar steps but uses Delta Lake's native capabilities:

  1. Enable CDF: A simple ALTER TABLE command is all that's needed.
  2. Use Version as Watermark: Your control table now stores the last_processed_version instead of a timestamp.
  3. Read Changes with table_changes(): You query the changes between the last processed version and the latest version of the table. This gives you a DataFrame with all the incremental changes, including a _change_type column.
  4. MERGE with _change_type: The MERGE statement becomes even more powerful, as you can specify different actions based on whether the change was an insert, update_postimage, or delete.
  5. Update Version Watermark: You update your control table with the latest table version number.

From an architectural standpoint, using CDF is preferable when your source is a Delta table because it's less prone to errors from out-of-order data or clock skew, and it natively handles deletions.


Conclusion

You have now learned one of the most important patterns in data engineering for building efficient and scalable batch systems. Moving from processing all data to only processing what's new is a game-changer for performance and cost.

Key Takeaways:

  • Incremental loading is a foundational pattern for processing only new or changed data, saving time and resources.
  • The high-watermark strategy uses a "bookmark" (like a timestamp or version number) to track progress.
  • A control table is essential for persisting the watermark between pipeline runs.
  • The idempotent MERGE operation is the perfect tool for safely applying incremental updates, inserts, and deletes to a Delta table.
  • Delta Lake's Change Data Feed (CDF) offers a powerful, built-in mechanism that uses table versions as watermarks and simplifies handling all change types, including deletes.

In our next and final lesson of this module, we will address another critical aspect of pipeline robustness: implementing programmatic data quality checks. After all, an efficient pipeline is only useful if the data it delivers is accurate and trustworthy.