VAYULearn
Colour theme
Investigate a failure
VAYU Learn

Data Architecture & Reliability

Building Data Quality Checks That Actually Catch Failures

Most Data Quality Checks Catch Obvious Failures. Here Are the Checks That Catch the Failures That Cost You Three Weeks of Bad Dashboards.

Data Architecture & ReliabilitySpark & PySpark
Most data quality checks only tell you the pipeline didn’t crash. The ones that matter catch silent corruption -partial data loss, distribution drift, schema changes, and successful jobs producing incorrect data.

TL;DR

  • A table-exists check and a not-null check catch total failures — they do nothing against the failures that actually cost time: partial data loss, silent schema drift, and distributions quietly shifting
  • Row count validation against a rolling baseline catches silent data loss that a fixed threshold misses on seasonal or variable-volume pipelines
  • Null rate monitoring with a threshold — not a binary check — catches partial upstream failures before they corrupt downstream aggregations
  • Distribution drift detection (mean/stddev bounds, PSI for categorical fields) catches the failure class that produces a job marked “success” with garbage output
  • Schema validation belongs at every layer a pipeline touches, not just at ingestion — a schema that’s correct at read time can still drift by the time it reaches the warehouse

The checks that catch obvious failures are already redundant with your job’s own error handling. The checks worth writing catch the failures that don’t throw an exception.


The pipeline had a data quality suite. Six checks. All green, every day, for five weeks.
assert table.count() > 0 assert "amount" in df.columns assert df.filter(col("amount").isNull()).count() == 0
During those five weeks, a currency conversion bug was silently deflating 40% of international transactions by roughly 8%. Every check passed. The table wasn’t empty. The column existed. Nothing was null.
The checks were testing whether the pipeline ran. Nobody was testing whether the pipeline was right.
The bug was found by an analyst who happened to compare a monthly total against a finance report by hand. Five weeks of revenue reporting had to be restated.

The Checks Everyone Writes That Catch Nothing New

Most data quality suites are built around three checks: does the table exist, does the expected column exist, are there any nulls in a required field. These checks are not wrong to have. They are also almost entirely redundant with the pipeline’s own error handling — a job that fails to write a table, or writes with a wrong schema, will usually fail loudly on its own, without needing a separate check to notice.

The checks that provide genuine additional coverage are the ones that catch a job that completed successfully and produced wrong output. That is a different failure class entirely, and it requires different techniques.


Row Count Validation That Actually Works

Fixed Thresholds vs Rolling Baselines

A fixed minimum row count (assert count > 1_000_000) works for stable, non-seasonal pipelines. It produces false negatives on anything with real volume variance — weekday vs weekend traffic, monthly billing cycles, holiday spikes — and false positives when volume genuinely should be near zero, such as a maintenance window.

A rolling baseline comparison adapts to the pipeline’s actual behavior:

from pyspark.sql import functions as F
import numpy as np

def validate_row_count_against_baseline(
current_count: int,
table_name: str,
history_table: str,
lookback_days: int = 30,
tolerance_std: float = 2.5,
spark=None
):
"""
Compare today's row count against a rolling historical baseline
rather than a fixed threshold.
"""

history = spark.sql(f"""
SELECT row_count
FROM {history_table}
WHERE table_name = '{table_name}'
AND run_date >= date_sub(current_date(), {lookback_days})
"""
).toPandas()["row_count"].values

if len(history) < 7:
# Not enough history yet — fall back to a sanity floor
print(f"WARNING: only {len(history)} days of history for {table_name}. "
f"Skipping baseline check, using absolute floor instead.")
assert current_count > 0, f"{table_name}: zero rows, no history to compare against"
return

mean = np.mean(history)
std = np.std(history)
lower_bound = mean - (tolerance_std * std)
upper_bound = mean + (tolerance_std * std)

if not (lower_bound <= current_count <= upper_bound):
raise ValueError(
f"{table_name}: row count {current_count:,} is outside "
f"expected range [{lower_bound:,.0f}, {upper_bound:,.0f}] "
f"(30-day mean: {mean:,.0f}, std: {std:,.0f})"
)

print(f"{table_name}: {current_count:,} rows — within expected range")

Implementation

Log the row count on every run so the baseline table has data to compare against:

def log_row_count(table_name: str, row_count: int, spark):
spark.sql(f"""
INSERT INTO pipeline_metrics.row_count_history
VALUES ('{table_name}', current_date(), {row_count}, current_timestamp())
"""
)

# Use in a pipeline
current_count = df.count()
log_row_count("transactions", current_count, spark)
validate_row_count_against_baseline(current_count, "transactions",
"pipeline_metrics.row_count_history",
spark=spark)

A 2.5 standard deviation tolerance is a reasonable starting point — tight enough to catch meaningful anomalies, loose enough to avoid alert fatigue on normal variance. Tune per table based on how volatile its volume genuinely is.


Null Rate Monitoring With Thresholds

Why a Simple isNull Check Isn’t Enough

A binary null check (assert nulls == 0) only catches total failure — every value in the column is missing. It does nothing for a partial failure — a bug that causes 8% of records to lose a field while 92% remain correct. That 8% is exactly the kind of failure that slips through unnoticed for weeks, because most of the data still looks right.

Implementation

def validate_null_rates(
df,
column_thresholds: dict[str, float],
baseline_thresholds: dict[str, float] = None
):
"""
Check null rate per column against a maximum acceptable threshold.
Optionally compare against a historical baseline to catch
a rate that is technically within bounds but has shifted meaningfully.
"""

total = df.count()
results = {}

for col, max_rate in column_thresholds.items():
null_count = df.filter(F.col(col).isNull()).count()
rate = null_count / total if total > 0 else 0
results[col] = rate

if rate > max_rate:
raise ValueError(
f"Column '{col}': null rate {rate:.2%} exceeds "
f"threshold {max_rate:.2%} ({null_count:,} / {total:,} rows)"
)

# Flag a meaningful shift even within threshold
if baseline_thresholds and col in baseline_thresholds:
baseline = baseline_thresholds[col]
if rate > baseline * 3 and rate < max_rate:
print(f"WARNING: '{col}' null rate {rate:.2%} is 3x baseline "
f"{baseline:.2%} but still within threshold — investigate")

return results

# Example: amount usually has ~0.1% nulls (failed transactions)
# A threshold of 2% would still pass a jump to 1.5% —
# but the baseline comparison flags it as worth investigating
validate_null_rates(
df,
column_thresholds={"amount": 0.02, "merchant_id": 0.01, "customer_id": 0.05},
baseline_thresholds={"amount": 0.001, "merchant_id": 0.0005, "customer_id": 0.02}
)

The threshold catches hard failures. The baseline comparison catches the early signal of a developing problem before it crosses the hard threshold — the difference between finding a bug on day one and finding it on day twelve.


Distribution Drift Detection

What Drift Looks Like in Practice

The currency conversion bug in the opening story is the canonical example: the pipeline ran successfully, no nulls appeared, the schema was correct, and the actual values were systematically wrong. This class of failure is only visible by looking at the distribution of values, not their presence or absence.

Implementation — Statistical Comparison

For continuous numeric columns, compare mean and standard deviation against a historical baseline:

def validate_distribution(
df,
column: str,
baseline_mean: float,
baseline_std: float,
tolerance_std: float = 3.0
):
"""
Flag when a column's distribution has shifted meaningfully
from its historical baseline — catches successful-but-wrong runs.
"""

stats = df.select(
F.mean(column).alias("mean"),
F.stddev(column).alias("std")
).collect()[0]

current_mean = stats["mean"]
lower = baseline_mean - (tolerance_std * baseline_std)
upper = baseline_mean + (tolerance_std * baseline_std)
if not (lower <= current_mean <= upper):
raise ValueError(
f"Column '{column}': mean {current_mean:.2f} is outside "
f"expected range [{lower:.2f}, {upper:.2f}] "
f"(baseline mean: {baseline_mean:.2f}, std: {baseline_std:.2f}). "
f"This can indicate a silent transformation bug even though "
f"the pipeline completed without error."
)
print(f"'{column}' distribution: mean={current_mean:.2f} - within expected range")
# Baseline values should come from a rolling historical calculation,
# recalculated periodically as legitimate business patterns evolve
validate_distribution(df, "amount", baseline_mean=127.40, baseline_std=45.2)

An 8% systematic deflation, as in the opening story, shifts the mean by a fixed proportional amount — exactly the kind of shift this check is designed to catch, and exactly the kind of shift a null check or schema check cannot see at all.

Implementation — PSI for Categorical Drift

For categorical columns — status codes, country codes, event types — Population Stability Index (PSI) measures how much a distribution has shifted between two periods:

def calculate_psi(baseline_df, current_df, column: str) -> float:
"""
Population Stability Index — measures distribution shift
for categorical columns. PSI < 0.1: no significant shift.
PSI 0.1-0.25: moderate shift, investigate. PSI > 0.25: major shift.
"""
baseline_dist = (
baseline_df.groupBy(column).count()
.withColumn("pct", F.col("count") / F.sum("count").over(Window.partitionBy()))
.select(column, F.col("pct").alias("baseline_pct"))
)
current_dist = (
current_df.groupBy(column).count()
.withColumn("pct", F.col("count") / F.sum("count").over(Window.partitionBy()))
.select(column, F.col("pct").alias("current_pct"))
)

joined = baseline_dist.join(current_dist, column, "full_outer") \
.fillna(0.0001, subset=["baseline_pct", "current_pct"]) # avoid log(0)
psi_df = joined.withColumn(
"psi_component",
(F.col("current_pct") - F.col("baseline_pct")) *
F.log(F.col("current_pct") / F.col("baseline_pct"))
)
psi = psi_df.agg(F.sum("psi_component")).collect()[0][0]
return abs(psi)
psi_value = calculate_psi(baseline_transactions_df, current_transactions_df, "status")
if psi_value > 0.25:
raise ValueError(f"Major distribution shift in 'status': PSI={psi_value:.3f}")
elif psi_value > 0.1:
print(f"WARNING: moderate distribution shift in 'status': PSI={psi_value:.3f}")

PSI is the standard tool for this in fraud and credit risk modeling, and it applies just as directly to catching a producer team silently changing what values they emit for a status field.


Schema Validation at Each Layer

Why One Schema Check Isn’t Enough

A schema check at ingestion confirms the raw data matches expectations. It does not confirm the schema is still correct after three transformation steps, a join, and a write to the warehouse. A bug in a transformation — a column accidentally dropped, a type silently coerced — passes the ingestion check and corrupts the final output.

Implementation

from pyspark.sql.types import StructType

def validate_schema_at_layer(df, expected_schema: StructType, layer_name: str):
"""
Run this at every meaningful checkpoint — after ingestion,
after major transformations, before the final write.
"""

actual_fields = {f.name: f.dataType for f in df.schema.fields}
expected_fields = {f.name: f.dataType for f in expected_schema.fields}

missing = set(expected_fields) - set(actual_fields)
mistyped = {
c for c in expected_fields
if c in actual_fields and expected_fields[c] != actual_fields[c]
}

if missing:
raise ValueError(f"[{layer_name}] Missing expected columns: {missing}")
if mistyped:
raise ValueError(f"[{layer_name}] Type mismatches: {mistyped}")

print(f"[{layer_name}] Schema validated — OK")


# Wire into a pipeline at each checkpoint
df_raw = spark.read.schema(RAW_SCHEMA).parquet("s3://bucket/raw/")
validate_schema_at_layer(df_raw, RAW_SCHEMA, "ingestion")

df_transformed = apply_transformations(df_raw)
validate_schema_at_layer(df_transformed, TRANSFORMED_SCHEMA, "post-transform")

df_final = apply_aggregations(df_transformed)
validate_schema_at_layer(df_final, FINAL_SCHEMA, "pre-write")

Checking at each layer isolates exactly where a schema problem was introduced — the checkpoint that fails tells you which transformation to investigate, rather than discovering the final output is wrong and having to trace backward through the whole pipeline.


Wiring Checks Into a Pipeline

def run_pipeline_with_quality_gates(spark):
df_raw = spark.read.schema(RAW_SCHEMA).parquet("s3://bucket/raw/transactions/")
validate_schema_at_layer(df_raw, RAW_SCHEMA, "ingestion")

row_count = df_raw.count()
log_row_count("transactions", row_count, spark)
validate_row_count_against_baseline(
row_count, "transactions", "pipeline_metrics.row_count_history", spark=spark
)

validate_null_rates(
df_raw,
column_thresholds={"amount": 0.02, "merchant_id": 0.01},
baseline_thresholds={"amount": 0.001, "merchant_id": 0.0005}
)

df_transformed = apply_transformations(df_raw)
validate_schema_at_layer(df_transformed, TRANSFORMED_SCHEMA, "post-transform")

baseline = get_rolling_baseline("amount", days=30, spark=spark)
validate_distribution(
df_transformed, "amount",
baseline_mean=baseline["mean"], baseline_std=baseline["std"]
)

df_transformed.write.format("delta").mode("append") \
.save("s3://bucket/output/transactions/")

print("Pipeline completed — all quality gates passed")

Every gate raises a hard exception on failure — the pipeline stops rather than writing output that has already failed validation. A quality check that logs a warning but lets bad data through provides no real protection.


The Data Quality Checklist

Row count
□ Comparing against a rolling baseline, not a fixed threshold
□ At least 7-14 days of history before baseline checks activate
□ Tolerance calibrated per table based on actual volume variance

Null rates
□ Threshold set per critical column, not a blanket zero-tolerance rule
□ Baseline comparison catches shifts within threshold, before they cross it
□ Checked at ingestion, not just assumed from downstream behavior

Distribution
□ Numeric columns checked against historical mean/std bounds
□ Categorical columns checked with PSI or equivalent shift metric
□ Baseline recalculated periodically as legitimate patterns evolve

Schema
□ Validated at ingestion, after major transforms, and before final write
□ Type mismatches treated as hard failures, not warnings
□ Each checkpoint isolates where a problem was introduced

Wiring
□ Every check raises a hard failure — pipeline stops on violation
□ Checks run before the final write, not after
□ Metrics logged on every run to build the historical baseline

Final Takeaway

A data quality suite that only catches total failures is testing whether your pipeline ran, not whether it produced correct output. The failures that cost real time and real trust are the ones where everything appears to have worked — no crash, no missing data, no empty table — and the actual values are quietly wrong.

Row count baselines, null rate thresholds, distribution drift detection, and layered schema validation catch that category of failure. They require more setup than a null check. They are also the only checks that would have caught the bug in the opening story before an analyst found it by hand five weeks later.

📌 Core Principle

A passing data quality check should mean the data is correct - not just that the pipeline didn't crash. Those are different claims. Build checks for the one that matters.

Next in Series

️Great Expectations in Production - A Real Implementation Guide

You now know what checks to write.

Next: how to implement them at scale using Great Expectations — setup that doesn’t break your pipeline, expectation suites that make sense for real production tables, integration with Airflow specifically, and what to actually do when an expectation fails instead of just logging it and moving on.