Skip to main content

Welcome to a Grasp lesson

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

Lesson 42

Implementing Data Quality Checks in Spark

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

Hello! Welcome to the final lesson in our module on implementing ELT pipelines.

In our last session, we focused on making our pipelines efficient by implementing incremental loads. We saw how processing only new or changed data is critical for performance and scalability. Now, we'll address an equally important question: how do we ensure the data we're processing is correct and trustworthy? An efficient pipeline delivering bad data is worse than no pipeline at all.

Your learning outcome for this lesson is to implement programmatic data quality checks within a Spark pipeline. This means embedding automated validation directly into our code to catch issues before they impact downstream analytics, BI dashboards, or ML models. As a data architect, building this trust layer is one of your most important responsibilities.

1. A Framework for Data Quality

Before we dive into code, let's establish a conceptual framework. Data quality isn't a single concept but a collection of dimensions. A common model breaks it down into six key areas.

Data Quality Management With Databricks

To understand the different facets of data quality, let's start with the article 'Data Quality Management With Databricks.' It introduces a proven model for thinking about what 'good data' actually means.

Please read the first two sections, 'What Is Data Quality?' and 'Principles of Data Quality.' Focus on understanding the 'Six Dimensions' model: Consistency, Accuracy, Validity, Completeness, Timeliness, and Uniqueness. This will give us a vocabulary for the types of checks we'll implement.

These six dimensions give us a target. Our programmatic checks will be designed to enforce rules related to them—for example, checking for Completeness by ensuring a critical column is never null, or checking Validity by ensuring a date column is in the correct format.

A typical data quality process within a pipeline follows a clear pattern, as illustrated below.

Proactive Data Quality Checking in a Lakehouse Architecture
This diagram shows a proactive data quality process. Data flows through Bronze, Silver, and Gold layers. Rules are defined, checks are applied, bad data is quarantined, and the results are monitored on a dashboard. This is the workflow we will model.

Our implementation will mirror this process:

  1. Define Rules: Specify the constraints that define valid data.
  2. Apply Checks: Execute code that tests data against these rules.
  3. Handle Violations: Decide what to do with records that fail a check.
  4. Monitor Results: Observe quality metrics to understand data health over time.

We will explore two primary methods for implementing this in a Spark environment: a general-purpose approach using custom code and open-source libraries, and the highly integrated, declarative approach native to Databricks.


2. General-Purpose Data Quality in Spark

The most straightforward way to implement data quality checks in any Spark job is to use the standard DataFrame API. You can check for invalid data and then decide how to handle it. Two common patterns are flagging and quarantining.

  • Flagging: You add a new column to your DataFrame to mark records that violate a rule. This keeps all data flowing but allows downstream consumers to easily filter out bad records.

    from pyspark.sql.functions import col, when
    
    # Flag orders where the amount is not positive
    checked_df = source_df.withColumn(
        "dq_check_passed",
        when(col("order_amount") > 0, True).otherwise(False)
    )
    
  • Quarantining: You split the DataFrame into two—one with good data and one with bad data. The good data proceeds down the pipeline, while the bad data is written to a separate "quarantine" table for later analysis and remediation.

    # Define the quality condition
    good_data_condition = col("order_amount") > 0
    
    # Split the DataFrame
    good_df = source_df.filter(good_data_condition)
    quarantined_df = source_df.filter(~good_data_condition)
    
    # Process good data
    good_df.write.format("delta").mode("append").saveAsTable("silver_orders")
    
    # Save bad data for review
    quarantined_df.write.format("delta").mode("append").saveAsTable("quarantined_orders")
    

While effective for simple rules, writing custom logic for dozens of checks across many columns can become cumbersome. This is where dedicated data quality libraries come in. One such library built for Spark is Deequ, open-sourced by AWS.

The following video demonstrates PyDeequ, the Python wrapper for Deequ. It shows how a library can provide a much more scalable and maintainable framework for defining and running data quality checks.

Guaranteeing Data Quality SLAs with Deequ & Databand

Watch this demonstration from the 'Guaranteeing Data Quality SLAs with Deequ & Databand' talk to see how PyDeequ can be used within a Spark pipeline. It moves beyond simple checks to a more robust, framework-driven approach.

Watch the section from 16:29 to 23:18. Focus on how the code uses: A Profiler to get an automatic statistical summary of the data. Analyzers to compute specific metrics like completeness, distinctness, and size. Compliance rules to define and check custom business logic (e.g., asset_type must be 'common stock'). Notice how this abstracts away the manual filter and withColumn logic into a reusable set of checks.

Using a library like Deequ professionalizes your data quality efforts. It allows you to define a comprehensive suite of tests, execute them efficiently at scale, and receive a structured report of the results, which is a significant step up from ad-hoc validation code.


3. The Databricks Way: Expectations

For pipelines running within the Databricks ecosystem, there's a more integrated and declarative solution: Expectations in Delta Live Tables (now part of the broader Lakeflow framework).

Introducing Delta Live Tables
This image shows how Delta Live Tables simplify pipeline creation in Databricks. 'Expectations' are highlighted as a key feature for ensuring data quality directly within the pipeline definition.

Instead of writing imperative code to filter or flag data, you declare your quality rules directly on the table definition. The pipeline engine then enforces these rules automatically. An expectation consists of three parts:

  1. A name (e.g., valid_order_status).
  2. A constraint (e.g., order_status IN ('SHIPPED', 'PROCESSING', 'RETURNED')).
  3. An action to take when the constraint is violated.

There are three possible actions, and choosing the right one is a critical architectural decision.

Action ON VIOLATION Clause Result Use Case
Warn (Default behavior) Invalid records are loaded into the target table, and a metric is logged. You want to monitor data quality but not stop the flow of data.
Drop DROP ROW Invalid records are silently dropped and not loaded into the target. Minor data issues that can be safely ignored without breaking logic.
Fail FAIL UPDATE The entire pipeline update stops and fails upon finding an invalid record. Critical data errors that make the entire dataset untrustworthy.

The following video provides a practical walkthrough of defining and applying expectations with all three actions.

30 DLT Data Quality & Expectations | Monitor DLT pipeline using SQL | Define DQ rule |Observability

This video, '30 DLT Data Quality & Expectations', demonstrates how to implement this pattern in a Databricks notebook. It clearly shows the effect of each violation action.

Watch the segments from 01:08 to 06:10 and from 08:46 to 12:16. Observe how: Rules are defined in a Python dictionary for reusability. The @dlt.expect_all decorator applies these rules. The behavior changes when the action is set to warn (default), fail, and drop. The pipeline's UI provides immediate feedback on data quality metrics.

A key benefit of this integrated approach is the built-in observability. As the video shows, the results of your quality checks are automatically logged and are queryable, making it easy to build monitoring dashboards and alerts.

Test your understanding!

You are building a pipeline to process customer data. The email column is used for marketing campaigns, and the country_code is used for regulatory reporting.

  1. For an invalid email format, which action (warn, drop, fail) would you choose and why?
  2. For a NULL value in country_code, which action would you choose and why?
Show answer
  1. For an invalid email, warn or drop would be appropriate. A bad email address won't break downstream systems, but it's useless for marketing. warn would let you know about the issue while still loading the customer record, while drop would discard the record entirely if you decide a customer without a valid email is not useful. fail would be too aggressive.

  2. For a NULL country_code, fail is the most appropriate action. Regulatory reporting is a critical function, and missing data could lead to legal or compliance issues. Failing the pipeline forces immediate human intervention to fix the source data or the ingestion logic, preventing incorrect reports from ever being generated.


Conclusion

You have now learned how to weave a safety net into your data pipelines using programmatic data quality checks. This practice is fundamental to building reliable, enterprise-grade data systems.

Key Takeaways:

  • Programmatic DQ is essential for building trust and ensuring the reliability of your data architecture.
  • A good DQ framework involves defining rules, applying checks, handling violations, and monitoring results.
  • In general Spark, you can use custom code (flagging/quarantining) or leverage powerful open-source libraries like Deequ for scalable validation.
  • In Databricks, Delta Live Tables Expectations offer a declarative, highly integrated way to enforce data quality with warn, drop, or fail actions.
  • The choice of action is a critical design decision that balances data integrity with pipeline resiliency.

This lesson concludes our module on implementing ELT pipelines. You've learned to build robust, efficient, and trustworthy pipelines using modern tools like Spark and Delta Lake.

In our next module, Modern Cloud Data Warehousing, we will shift our focus to the final destination for much of this curated data. We'll explore the architecture of platforms like Snowflake, BigQuery, and Redshift and see how they serve the analytics and business intelligence use cases that our high-quality data pipelines enable.