🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Data Quality on Azure: Expectations, Quarantine, DQ Metrics

Azure Data EngineeringData Quality⭐ Premium

Most data quality incidents do not announce themselves. A vendor changes a CSV header, a partner switches a timestamp to local time, and the pipeline still reports "Succeeded" while every dashboard quietly drifts. The job of a data quality layer is to turn that silent drift into an explicit, alertable failure before a business user finds it first.

In this lesson you will learn how to:

  • Encode business rules as executable expectations rather than tribal knowledge.
  • Split a batch into clean rows and quarantined rows without losing anything.
  • Decide which checks belong in ADF, which belong in Spark, and which belong downstream.
  • Publish data quality metrics that a team can actually alert and report on.

Prerequisites

  • !Comfortable reading Python and Spark DataFrames
  • !Familiarity with ADLS Gen2 bronze and silver layers
  • !Basic ADF pipeline authoring

Why pipelines fail without anyone noticing

A Copy Activity that moves 40,000 rows from a source system will succeed even if 6,000 of those rows now have an empty customer identifier. Success in Azure Data Factory means the transport worked, not that the content is usable. The same is true for a Databricks notebook: writing a DataFrame to a Delta table completes happily whether the data is correct or garbage.

The second failure mode is creeping change. A source team adds a new region code, an upstream system starts emitting two-digit years, or a once-daily feed begins arriving twice a day. Nothing crashes. Row counts stay plausible, and the only signal is a slow erosion of trust that ends with analysts re-deriving numbers in spreadsheets.

The fix is to make correctness a first-class, testable property of every hop. Instead of asking whether the pipeline ran, ask whether the data satisfies a contract. That contract needs three parts: a machine-checkable rule, a defined action when the rule breaks, and a metric that shows the rule's history over time. Without all three you have a script with an optimistic name.

Six dimensions, six measurable checks

Interviewers almost always ask which dimensions of data quality you track. The classic answer is six, and each one maps to a concrete check you can implement on Azure storage.

DimensionTypical failureAzure-friendly checkWhat to alert on
CompletenessMissing keys or null amountsExpectColumnValuesToNotBeNull on primary keysNull rate above threshold
AccuracyCurrency value of 0.01 where 1000 was meantRange and sanity bounds per columnViolation count per day
ConsistencyTotal stored but quantity times price disagreesRecompute and compare within toleranceMismatch percentage
TimelinessYesterday's feed still not landedPartition arrival SLA checkMissing partition
UniquenessDuplicate transaction identifiersDistinct count equals row countDuplicate ratio
ValidityEmail without an at sign, bad country codeRegex or reference-list validationFormat failure count

The useful part of this table is the last column. A dimension without a threshold is a description, not a monitor. Agree on the number with the data owner, then encode it.

Encoding expectations as executable contracts

Great Expectations is the most common open-source way to express these contracts in Python. The suite lives in your repository, versioned alongside the pipeline that produces the data, so a rule change goes through the same pull request process as code.

python
import great_expectations as gx
from great_expectations.core.expectation_suite import ExpectationSuite
from great_expectations.expectations import (
    ExpectColumnValuesToNotBeNull,
    ExpectColumnValuesToBeBetween,
    ExpectColumnValuesToMatchRegex,
    ExpectColumnValuesToBeUnique,
)

context = gx.get_context()
suite = context.suites.add(ExpectationSuite(name="sales_bronze_v1"))

suite.add_expectation(ExpectColumnValuesToNotBeNull(column="sale_id"))
suite.add_expectation(ExpectColumnValuesToBeUnique(column="sale_id"))
suite.add_expectation(
    ExpectColumnValuesToBeBetween(column="quantity", min_value=1, max_value=5000)
)
suite.add_expectation(
    ExpectColumnValuesToMatchRegex(
        column="email", regex=r"^[\w.+-]+@[\w-]+\.[A-Za-z]{2,}$"
    )
)

validator = context.sources.pandas_default.read_parquet(
    "abfss://[email protected]/sales/dt=2026-01-05/"
)
result = validator.validate(expectation_suite=suite, return_exceptions=True)
failed = [e for e in result.results if e.success is False]
print(f"{len(failed)} of {len(result.results)} expectations failed")

Run this as a step in the pipeline rather than as a notebook someone remembers to open. A failed suite should fail the run, and the run failure should page someone.

Splitting clean rows from quarantined rows

Validation that only prints a warning still lets bad rows reach the silver layer. The safer pattern is a hard split: rows that pass every rule move forward, rows that fail are written to a quarantine path with the name of the rule they broke. Nothing is deleted, so nothing is lost when a rule turns out to be wrong.

python
from pyspark.sql import functions as F

checks = {
    "sale_id_not_null": df.sale_id.isNotNull(),
    "quantity_in_range": (df.quantity >= 1) & (df.quantity <= 5000),
    "unit_price_positive": df.unit_price > 0,
    "email_shape": df.email.rlike(r"^[\w.+-]+@[\w-]+\.[A-Za-z]{2,}$"),
}

failed_rule = F.lit(None).cast("string")
for name, cond in checks.items():
    failed_rule = F.when(~cond, F.lit(name)).otherwise(failed_rule)

flagged = df.withColumn("failed_rule", failed_rule)
good = flagged.where(F.col("failed_rule").isNull()).drop("failed_rule")
bad = flagged.where(F.col("failed_rule").isNotNull())

good.write.format("delta").mode("append").save(SILVER_PATH)
bad.withColumn("checked_at", F.current_timestamp()) \
    .write.format("delta").mode("append").save(QUARANTINE_PATH)

print(f"clean={good.count()} quarantined={bad.count()}")

Notice that the quarantine write carries the rule name and a timestamp. That single column turns a debugging session from "why is this wrong" into "rule quantity_in_range broke 6,140 times since 03:00".

Where ADF fits in the quality chain

Azure Data Factory is the right place for cheap, structural checks that must run even when a Spark cluster would be overkill: row count thresholds, required column presence, and file-format sanity. A Filter transformation with a strict predicate, or a pre-copy script that asserts a partition exists, catches problems at the boundary without spinning up compute.

ADF is the wrong place for deep business logic. Expressions in a pipeline JSON become unreadable once you pass four or five conditions, they cannot be unit tested, and nobody can tell from the UI which rule a given Filter represents. Keep ADF responsible for shape and arrival, and push meaning into Spark or an expectations suite where it can be named, versioned, and reviewed.

Check typeBest homeWhy
File landed, size non-zeroADF pre-activityRuns before any compute cost
Schema and column typesADF Copy mapping or expectationsCheap and boundary-level
Business rules and rangesSpark or Great ExpectationsNamed, testable, reusable
Cross-table reconciliationPost-load SQL or notebookNeeds full context
Freshness and SLAAzure Monitor alertIndependent of any one pipeline

Publishing metrics people can alert on

A quality check that nobody sees is decoration. Emit a small metrics table with one row per rule per run: rule name, dataset, evaluated count, failed count, run id, timestamp. Store it in Delta or Synapse serverless, then chart failure percentage in an Azure Monitor workbook and alert when it crosses the agreed threshold.

This also gives you a defensible answer when someone asks how reliable the warehouse is. Instead of "we check the data", you can show that unit_price_positive failed on 0.02% of rows over ninety days and spiked to 4% on the day the vendor switched formats. Trends are what turn quality from an opinion into an engineering discipline.

Common Mistakes

Treating a successful pipeline run as proof the data is correct

Fix: Fail the run explicitly when an expectation suite returns failures, and page on that failure.

Quarantining rows without recording which rule they broke

Fix: Write the failed rule name and timestamp into the quarantine table so triage starts with a cause.

Writing twenty assertions nobody has agreed to act on

Fix: Start with five rules tied to thresholds signed off by the data owner, then grow the suite.

Dropping or overwriting bad rows in place

Fix: Route them aside instead; silent deletion destroys the evidence you need to fix the source.

Best Practices

  • Version expectation suites in the same repository as the pipeline that feeds them
  • Split checks into boundary rules in ADF and business rules in Spark or SQL
  • Publish one metrics row per rule per run and chart the failure rate over time
  • Replay quarantined rows through the same code path once the source is fixed
  • Add a freshness check before every load so stale data never masquerades as current

Questions interviewers actually ask

đŸŽ¯Interview Tip

Expect a follow-up asking what you would do differently at three in the morning when a quality alert fires. Walk through the sequence: confirm the threshold was not a false positive, check whether the source changed, inspect quarantine rows for the dominant failed rule, then decide whether to fix forward or reload from the last known good partition.

Interview Questions

Q1: Where would you implement a data quality check in an Azure pipeline?

Boundary checks such as file presence, row counts and schema go in ADF before or after the copy. Business rules go in Spark or an expectations suite so they can be named and unit tested. Cross-table reconciliation runs after load, and freshness is monitored by Azure Monitor independently of the pipeline.

Q2: What do you do when a quality rule fails but the business says the data is fine?

Treat it as a rule defect, not a data defect. Record the incident, widen or correct the expectation with evidence, redeploy the suite through version control, and keep the original failure in the metrics history so the change is auditable.

Q3: How do you prevent a quarantine table from growing without limit?

Partition quarantine output by date, alert on quarantine volume rather than silently archiving it, and set a retention window such as thirty days. Investigate repeated failures of the same rule instead of letting rows accumulate untouched.

Q4: How would you measure the health of a data quality programme?

Track percentage of critical datasets covered by rules, mean time to detect a broken feed, failure rate trend per rule, and open quarantine volume. Coverage and detection time reveal whether the programme is real or ceremonial.

Key Takeaways

  • A successful pipeline run proves transport, never content
  • Each of the six quality dimensions needs a named rule and an agreed threshold
  • Quarantine with a failed_rule column beats deletion or silent passing
  • ADF handles shape and arrival; Spark and expectations handle meaning
  • Publish per-run metrics so quality becomes a chart, not an opinion
  • Version rules in code so every change is reviewable and reversible
🔒

Premium Content

Data Quality on Azure: Expectations, Quarantine, DQ Metrics

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement