StackPractices
advanced By Mathias Paulenko

Data Quality Guide: Validation, Profiling, Monitoring

Master data quality: validation frameworks, profiling, schema enforcement, anomaly detection, and pipeline checks with Great Expectations, Pandera, and Soda.

Topics: data

Introduction

Data quality issues silently corrupt analytics, ML models, and business decisions. A null primary key breaks a join downstream. A status value nobody documented shows up in a report three months later. A source that silently halves its row count propagates “insights” that are simply wrong.

Data quality work has three layers: profiling (understand what the data looks like), validation (enforce what it should look like), and monitoring (detect when it drifts). This guide walks through the six quality dimensions, then the three mainstream validation stacks — Great Expectations, Pandera, and Soda — and finally how to wire checks into Airflow, dbt, and monitoring loops so bad data stops before it spreads.

When to Use Each Tool

The three tools overlap but optimize for different layers of the stack:

ToolBest atWhere it livesWhen to skip it
Great ExpectationsWarehouse-scale validation with reports and historyData platform / orchestratorYou just need ad-hoc checks — it is heavyweight
PanderaPython-native DataFrame schemas in codeInside notebooks, scripts, ETL functionsYour data lives only in SQL — use dbt tests/Soda
SodaSQL-first checks against warehousesDeclarative YAML + CLI scansYou need row-level logic in Python
dbt testsValidation inside the transformation layerNext to modelsYou do not use dbt
flowchart diagram: Extract

The pattern underneath: validate at every stage boundary, quarantine what fails, and monitor what passes. Fail-fast checks (schema, keys, row count) stop the pipeline; soft checks (distribution drift, unusual null rates) warn without blocking.

A rollout order that works: start with Pandera checks at the raw ingestion boundary — they are the cheapest to write and catch the highest-impact failures early. Add dbt tests once the transformation layer exists. Introduce Soda or GX when you need shared reports, history, and checks owned by people who don’t write pipeline code. Each layer replaces nothing; they stack.

For the orchestration layer around these checks, see the Airflow guide; for the transformation layer, the dbt guide.

Data Quality Dimensions

Every quality check maps to one of six dimensions. Knowing which dimension a check covers tells you what you are not testing yet:

DimensionQuestion it answersExample check
AccuracyDoes the data match reality?Order total matches payment processor record
CompletenessAre required fields populated?No nulls in order_id; row count within expected range
ConsistencyIs data consistent across systems?Customer ID exists in both orders and customers
ValidityDoes it conform to expected formats?Email matches regex; date not in the future; country in ISO list
UniquenessAre there duplicates?Primary keys unique; no duplicated orders per batch
TimelinessIs data fresh?Pipeline completed within SLA; data < 24h old

In practice, teams usually implement Validity and Uniqueness first (easiest to automate), and under-invest in Accuracy and Consistency (harder: they require comparing against an external truth or a second system). The tools map unevenly onto the dimensions too — a not_null check covers Completeness, a regex covers Validity, but nothing in a schema check verifies that a total actually equals what the payment processor charged. Reconciliation checks like the dbt revenue test later in the guide are how Consistency gets covered in practice.

Data Profiling

Profile before you validate — you cannot write expectations for data you have not measured. Profiling tells you the real null rates, ranges, and value sets; validation rules written blind either miss real problems or fire on acceptable data.

# profiling/profile_dataset.py — Understand your data before validating
import pandas as pd
from ydata_profiling import ProfileReport  # formerly pandas-profiling

df = pd.read_csv("data/orders.csv")

# Full profile report (HTML): distributions, correlations, warnings
profile = ProfileReport(df, title="Orders Dataset Profile", minimal=True)
profile.to_file("reports/orders_profile.html")

# Manual profiling with pandas when you need the numbers in code
def profile_dataframe(df: pd.DataFrame) -> dict:
    profile = {
        "row_count": len(df),
        "column_count": len(df.columns),
        "null_counts": df.isnull().sum().to_dict(),
        "null_percentages": (df.isnull().sum() / len(df) * 100).round(2).to_dict(),
        "duplicate_rows": int(df.duplicated().sum()),
        "dtypes": df.dtypes.astype(str).to_dict(),
        "unique_counts": {col: int(df[col].nunique()) for col in df.columns},
    }
    for col in df.select_dtypes(include="number").columns:
        profile[col] = {
            "min": float(df[col].min()),
            "max": float(df[col].max()),
            "mean": float(df[col].mean()),
            "median": float(df[col].median()),
            "std": float(df[col].std()),
            "quartiles": df[col].quantile([0.25, 0.5, 0.75]).to_dict(),
        }
    return profile

profile = profile_dataframe(df)
print(f"Rows: {profile['row_count']}, Columns: {profile['column_count']}")
print(f"Nulls: {profile['null_counts']}")
print(f"Duplicates: {profile['duplicate_rows']}")

Two profiling habits pay off: keep the report per batch (compare today’s profile with yesterday’s to spot silent schema changes), and write expectations from measured distributions — e.g., set expect_column_values_to_be_between bounds from observed quantiles plus margin, not from guesses.

Great Expectations

Great Expectations (GX) is the heavyweight option: suites of expectations, checkpoints, and generated Data Docs reports. Its sweet spot is warehouse-scale validation where you need history and shared reports across a team. GX 1.x reorganized the API around data_sources → assets → batch_definitions → validation_definitions — the snippets below use that flow.

Suite creation (GX 1.x)

# gx/suite.py — Expectation suite, GX 1.x API
import great_expectations as gx

context = gx.get_context()

# Create the suite and add expectations
suite = context.suites.add(gx.ExpectationSuite(name="orders_suite"))
suite.add_expectation(
    gx.expectations.ExpectColumnValuesToNotBeNull(column="order_id")
)
suite.add_expectation(
    gx.expectations.ExpectColumnValuesToBeUnique(column="order_id")
)
suite.add_expectation(
    gx.expectations.ExpectColumnValuesToBeBetween(
        column="total_amount", min_value=0, max_value=100000
    )
)
suite.add_expectation(
    gx.expectations.ExpectColumnValuesToBeInSet(
        column="status",
        value_set=["pending", "processing", "shipped", "completed", "cancelled"],
    )
)
suite.add_expectation(
    gx.expectations.ExpectColumnValuesToMatchRegex(
        column="email", regex=r"^[^@]+@[^@]+\.[^@]+$"
    )
)
suite.add_expectation(
    gx.expectations.ExpectTableRowCountToBeBetween(
        min_value=100, max_value=1000000
    )
)

Validation (GX 1.x)

# gx/validate.py — Run a suite against a DataFrame, GX 1.x
import great_expectations as gx
import pandas as pd

context = gx.get_context()

# Data source → asset → batch definition → validation definition
ds = context.data_sources.add_pandas("orders_source")
asset = ds.add_dataframe_asset("orders_df")
batch_def = asset.add_batch_definition_whole_dataframe("orders_batch")

suite = context.suites.get(name="orders_suite")
validation = context.validation_definitions.add(
    gx.ValidationDefinition(data=batch_def, suite=suite, name="orders_validation")
)

df = pd.read_csv("data/orders.csv")
results = validation.run(batch_parameters={"dataframe": df})

if not results.success:
    for r in results.results:
        if not r.success:
            cfg = r.expectation_config
            print(f"FAILED: {cfg.type} on column {cfg.kwargs.get('column', 'N/A')}")
    raise ValueError("Data quality checks failed")

Instead of the removed auto-profiler, generate expectations from a measured profile: run profile_dataframe (previous section), then emit ExpectColumnValuesToBeBetween bounds from quantiles and ExpectColumnValuesToBeInSet from observed unique_counts on low-cardinality columns. Review the generated suite once before shipping — auto-expectations are a draft, not gospel.

Pandera

Pandera validates DataFrames in-process — ideal when your pipeline is Python (pandas, Polars) and the checks belong next to the code that owns them, not in an external platform. Schemas are declarative and composable.

DataFrame schema validation

# validation/pandera_schemas.py — Schema enforcement for pandas DataFrames
import pandera as pa
import pandas as pd

orders_schema = pa.DataFrameSchema({
    "order_id": pa.Column(int, checks=pa.Check.unique(), nullable=False),
    "customer_id": pa.Column(int, nullable=False),
    "created_at": pa.Column(pa.DateTime, nullable=False),
    "status": pa.Column(
        str,
        checks=pa.Check.isin(["pending", "processing", "shipped", "completed", "cancelled"]),
        nullable=False,
    ),
    "subtotal": pa.Column(float, checks=pa.Check.ge(0), nullable=False),
    "tax": pa.Column(float, checks=pa.Check.ge(0), nullable=True),
    "shipping": pa.Column(float, checks=pa.Check.ge(0), nullable=True),
    "email": pa.Column(
        str,
        checks=pa.Check.str_matches(r"^[^@]+@[^@]+\.[^@]+$"),
        nullable=True,
    ),
}, strict=True, coerce=True)  # strict: no extra columns; coerce: cast types

df = pd.read_csv("data/orders.csv")
try:
    validated = orders_schema.validate(df, lazy=True)  # lazy: collect ALL errors
    print(f"Validation passed: {len(validated)} rows")
except pa.errors.SchemaErrors as e:
    print(f"Validation failed: {len(e.failure_cases)} issue(s)")
    # e.failure_cases lists failing rows, columns, and checks

# Custom business-rule check
def no_weekend_orders(series: pd.Series) -> pd.Series:
    return series.dt.dayofweek < 5  # Monday=0, Sunday=6

orders_schema = pa.DataFrameSchema({
    "created_at": pa.Column(
        pa.DateTime,
        checks=pa.Check(no_weekend_orders, element_wise=False,
                        error="No weekend orders allowed"),
    ),
})

Two details matter in production: lazy=True returns every failing row in one pass instead of stopping at the first — essential for quarantine reports; and coerce=True fixes types before checks run, so a "42" read as string becomes 42 instead of failing the int check.

Schema inheritance and composition

# Base schema for shared columns; extend per table
base_schema = pa.DataFrameSchema({
    "id": pa.Column(int, checks=pa.Check.unique(), nullable=False),
    "created_at": pa.Column(pa.DateTime, nullable=False),
    "updated_at": pa.Column(pa.DateTime, nullable=True),
}, strict=False)

customers_schema = base_schema.add_columns({
    "email": pa.Column(str, checks=pa.Check.str_matches(r"^[^@]+@[^@]+$")),
    "country": pa.Column(str, checks=pa.Check.isin(["US", "CA", "UK", "DE", "FR", "JP"])),
})

products_schema = base_schema.add_columns({
    "name": pa.Column(str, nullable=False),
    "price": pa.Column(float, checks=pa.Check.ge(0)),
    "sku": pa.Column(str, checks=pa.Check.str_length(min_value=8, max_value=20)),
})

Inheritance keeps the audit trail sane: change created_at rules once and every derived schema picks them up automatically.

Soda

Soda puts checks in YAML and runs them against the warehouse directly — no Python pipeline required. It suits SQL-first teams and slots into orchestrators as a scan step.

# checks/orders_checks.yml — Soda Core checks
checks for orders:
  - row_count > 0
  - row_count < 1000000
  - missing_count(order_id) = 0
  - duplicate_count(order_id) = 0
  - missing_count(customer_id) = 0
  - invalid_count(email) = 0:
      valid regex: ^[^@]+@[^@]+\.[^@]+$
  - invalid_count(status) = 0:
      valid values: [pending, processing, shipped, completed, cancelled]
  - min(total_amount) >= 0
  - max(total_amount) <= 100000
  - schema:
      warn: when forbidden column present [ssn, credit_card_number]
      fail: when required column missing [order_id, customer_id, status]
  - freshness(created_at) < 1d
  - anomaly_score for row_count:
      default threshold: 3
      # fires when row count deviates >3 std devs from history
# Run checks against a data source
soda scan -d warehouse -c soda_config.yml checks/orders_checks.yml

# Inside a pipeline (Airflow) with templated variables
soda scan -d warehouse -c soda_config.yml checks/orders_checks.yml --variable start_date={{ ds }}

The warn:/fail: split is Soda’s built-in version of soft vs hard gates: schema changes to required columns stop the scan with failure; unexpected sensitive columns warn so someone reviews them.

Integrating Quality Checks into Pipelines

Validation that only runs ad-hoc is a lab exercise. The value comes from placing checks at every stage boundary so corruption stops where it starts.

Airflow integration

# dags/pipeline_with_quality.py — Quality gates between stages
from airflow import DAG
from airflow.operators.python import PythonOperator
from airflow.providers.postgres.hooks.postgres import PostgresHook
from datetime import datetime

dag = DAG(
    "pipeline_with_quality_checks",
    schedule="0 2 * * *",
    start_date=datetime(2026, 1, 1),
    catchup=False,
    max_active_runs=1,
)

def extract(**context):
    import pandas as pd
    hook = PostgresHook(postgres_conn_id="source_db")
    df = hook.get_pandas_df(
        "SELECT * FROM source WHERE date = %(ds)s", parameters={"ds": context["ds"]}
    )
    df.to_csv(f"/data/raw/{context['ds']}/orders.csv", index=False)
    return len(df)

def validate_raw(**context):
    import pandera as pa
    import pandas as pd
    df = pd.read_csv(f"/data/raw/{context['ds']}/orders.csv")
    schema = pa.DataFrameSchema({
        "order_id": pa.Column(int, checks=pa.Check.unique(), nullable=False),
        "status": pa.Column(str, checks=pa.Check.isin(
            ["pending", "processing", "shipped", "completed", "cancelled"]
        )),
    })
    schema.validate(df, lazy=True)

def transform(**context):
    import pandas as pd
    df = pd.read_csv(f"/data/raw/{context['ds']}/orders.csv")
    df["total"] = df["subtotal"] + df["tax"] + df["shipping"]
    df.to_csv(f"/data/processed/{context['ds']}/orders.csv", index=False)

def validate_processed(**context):
    import pandera as pa
    import pandas as pd
    df = pd.read_csv(f"/data/processed/{context['ds']}/orders.csv")
    schema = pa.DataFrameSchema({
        "order_id": pa.Column(int, checks=pa.Check.unique(), nullable=False),
        "total": pa.Column(float, checks=pa.Check.ge(0), nullable=False),
    })
    schema.validate(df, lazy=True)

extract_task = PythonOperator(task_id="extract", python_callable=extract, dag=dag)
validate_raw_task = PythonOperator(task_id="validate_raw", python_callable=validate_raw, dag=dag)
transform_task = PythonOperator(task_id="transform", python_callable=transform, dag=dag)
validate_processed_task = PythonOperator(task_id="validate_processed", python_callable=validate_processed, dag=dag)

extract_task >> validate_raw_task >> transform_task >> validate_processed_task

Three design choices worth copying: the check runs between stages (raw errors never reach transform), lazy=True surfaces the full failure list for the quarantine report, and the query uses a parameterized %(ds)s instead of string interpolation — parameterized queries, always.

When a gate fails, the question is what happens to the bad rows. The two sane options: quarantine them to a side table with the failure reason and keep processing the rest, or fail the task and stop everything. Fail for schema/key violations; quarantine for row-level business-rule outliers.

dbt tests as quality checks

dbt tests run inside the transformation layer — the last gate before data reaches dashboards. Singular tests (SQL files in tests/) return rows that violate the rule; zero rows returned means pass.

-- tests/assert_order_count_within_range.sql
SELECT 1
WHERE (
    SELECT COUNT(*) FROM {{ ref('stg_orders') }}
    WHERE created_at = CURRENT_DATE()
) < 10 OR (
    SELECT COUNT(*) FROM {{ ref('stg_orders') }}
    WHERE created_at = CURRENT_DATE()
) > 100000

-- tests/assert_revenue_matches_source.sql
SELECT
    warehouse.revenue AS warehouse_revenue,
    source.revenue AS source_revenue,
    ABS(warehouse.revenue - source.revenue) AS discrepancy
FROM (
    SELECT SUM(total_amount) AS revenue FROM {{ ref('fct_orders') }}
    WHERE created_at >= CURRENT_DATE() - INTERVAL '7 days'
) warehouse
CROSS JOIN (
    SELECT SUM(total_amount) AS revenue FROM {{ source('raw', 'orders') }}
    WHERE created_at >= CURRENT_DATE() - INTERVAL '7 days'
) source
WHERE ABS(warehouse.revenue - source.revenue) > 0.01

The revenue reconciliation test is the most valuable pattern in the file: it catches Consistency-dimension failures — the warehouse drifted from the source — that row-level checks cannot see. The dbt guide covers generic tests (unique, not_null, accepted_values, relationships) that handle most column-level rules without custom SQL.

Anomaly Detection

Schema checks catch the errors you anticipated. Anomaly detection catches the ones you did not: a source silently halves its rows, a null rate triples, a distribution shifts. The workhorse is z-score against a rolling baseline:

# monitoring/anomaly_detection.py — Statistical anomaly detection
import numpy as np

def detect_row_count_anomalies(
    current_count: int,
    historical_counts: list[int],
    threshold: float = 3.0,
) -> dict:
    mean = np.mean(historical_counts)
    std = np.std(historical_counts)
    z_score = (current_count - mean) / std if std > 0 else 0
    return {
        "current": current_count,
        "mean": round(mean, 2),
        "std": round(std, 2),
        "z_score": round(z_score, 2),
        "is_anomaly": abs(z_score) > threshold,
        "direction": "high" if z_score > 0 else "low",
    }

# Column-level: null-rate spike (only flag increases)
def detect_null_rate_anomaly(
    current_null_rate: float,
    historical_rates: list[float],
    threshold: float = 3.0,
) -> dict:
    mean = np.mean(historical_rates)
    std = np.std(historical_rates)
    z_score = (current_null_rate - mean) / std if std > 0 else 0
    return {
        "current_rate": current_null_rate,
        "mean_rate": round(mean, 4),
        "z_score": round(z_score, 2),
        "is_anomaly": z_score > threshold,  # decreases are fine
    }

Two rules keep anomaly detection useful instead of noisy: collect at least 30 days of baseline before enabling alerts (z-scores with 5 samples alert on everything), and monitor the metrics that actually matter — row counts, null rates of key columns, distinct counts of IDs — not every column in the table. Seasonality is the third rule: a weekend dip is not an anomaly if weekends always dip, so compare against same-weekday baselines when your data has a weekly rhythm.

The output of detection is only as useful as what happens next. Route anomalies to the same alerting channel as infrastructure incidents — a data incident is a production incident — and record the resolution. Over a few months that history becomes your most valuable documentation: which checks caught real problems, which only generated noise, and which metrics nobody ever looked at. For the alerting side of this loop, see the monitoring guide.

Best Practices

  • Profile before validating — expectations written from measured distributions, not guesses
  • Validate at every stage boundary — raw, staging, and marts each have different failure modes
  • Fail fast on structural checks — schema, keys, row count zero → stop the pipeline
  • Warn, don’t block, on drift — distribution shifts and null-rate increases get quarantine + alert
  • Quarantine bad rows — route them to a side table with the failure reason; don’t silently drop
  • Collect 30 days of baseline before enabling anomaly alerts
  • lazy=True everywhere — report all failures per run, not just the first
  • Version schemas with the models — a schema change without a validation change is a silent break
  • Store validation results — GX Data Docs or a results table; history powers anomaly baselines
  • Involve domain experts — valid status values and price ranges are business rules, not guesses

Common Mistakes

  • Validating only the final output — errors introduced in extraction propagate through transforms; gate every boundary
  • No historical baseline — anomaly detection with a week of history alerts on noise
  • Overly strict validation — rejecting rows for a missing optional field blocks the whole pipeline; warn on non-critical checks
  • String-interpolated pipeline parameters — f"WHERE date = '{ds}'" is an injection vector and breaks on odd values; parameterize
  • Hardcoded thresholds — a row_count < 1000000 that made sense last year fires on growth; prefer statistical bounds
  • Dropping bad rows silently — quarantine them with the reason; silent drops create unaccountable gaps
  • Schema drift blindness — upstream renames a column, downstream breaks mysteriously; strict=True + schema checks on required columns catch it at the gate
  • Treat validation as one-time — sources evolve; checks need monitoring and maintenance like production code

See Also

Frequently Asked Questions

What is data profiling?

Analyzing a dataset to understand its structure, content, and quality: row counts, null rates, distributions, ranges, unique counts, dtypes. Profiling is the first step — you cannot write meaningful validation rules for data you have not measured.

Great Expectations vs. Pandera vs. Soda — which should I use?

GX for warehouse-scale validation with reports and history (heaviest, most features). Pandera for Python-native validation inside notebooks, scripts, and ETL code. Soda for SQL-first declarative checks against the warehouse. Many stacks use two: Pandera in the ingestion code plus Soda/dbt tests at the warehouse layer.

What is anomaly detection in data quality?

Statistical detection of unexpected changes in data metrics — z-scores against a rolling baseline, IQR, or time-series decomposition. It catches failures schema checks cannot see: a source halving its row count, a null rate tripling, a distribution drifting. Needs ~30 days of baseline to avoid alert noise.

When should a data quality check fail the pipeline vs. warn?

Fail when the data is structurally unusable: null or duplicate primary keys, missing required columns, broken referential integrity, zero rows. Warn when data is suspicious but processable: elevated null rates, shifted distributions, unexpected optional values. The fail/warn split prevents pipelines stopping for cosmetic issues.

How do I test data quality in CI/CD?

Run dbt tests on changed models (--select state:modified+) in the PR pipeline. For Python ETL, run Pandera schemas against sample fixtures as a unit test step. In production, wire Soda scans or validation tasks into the orchestrator — CI catches rule regressions, orchestration catches data regressions.