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

Data Quality at Scale: Frameworks, Tests, Contracts

Data EngineeringData Quality⭐ Premium

Data Quality at Scale: Frameworks, Tests, Contracts

Difficulty: Senior Level | Companies: Netflix, Uber, Airbnb, Stripe, Spotify

A quality check that runs on one table is a script. A quality practice that runs on ten thousand tables, survives schema changes, and tells an analyst whether to trust a number before they query it is a system. The gap between the two is almost entirely about placement, ownership and consequence: where the check runs, who maintains it, and what happens when it fails.

Prerequisites

  • !SQL aggregation and window functions
  • !How CI pipelines gate a merge
  • !Warehouse table contracts and staging layouts

What You'll Learn

  • 1Map business risk onto measurable quality dimensions
  • 2Express expectations as a versioned suite rather than ad-hoc asserts
  • 3Place checks at ingestion, transform and publish with different consequences
  • 4Score and publish quality so consumers can see it before querying

Six dimensions, and which ones you can automate

Every quality framework converges on the same short list. Completeness asks whether required values are present. Accuracy asks whether values agree with reality, which usually means a domain constraint such as a non-negative amount. Consistency asks whether two tables that should agree do, such as order date preceding ship date. Timeliness asks whether the data arrived when promised. Uniqueness asks whether keys are duplicated. Validity asks whether values match an expected format or enumeration.

The automation profile differs sharply across them. Completeness, uniqueness, validity and timeliness are fully mechanical and cheap to evaluate on every run. Consistency needs a join between two tables, which makes it more expensive and better suited to a scheduled reconciliation than to a blocking gate. Accuracy is the hard one: it needs a reference source or a domain expert, so most teams start with a small set of high-value plausibility rules and expand as incidents reveal gaps.

DimensionExample assertionAutomatableBlocking?
CompletenessNull ratio under one percent on required columnsYes, cheapUsually yes
UniquenessDistinct keys equal total rowsYes, cheapYes
ValidityEnum or regex match on a controlled fieldYes, cheapYes
TimelinessNewest row within the promised cadenceYes, cheapYes
ConsistencyOrder date not after ship date across tablesYes, joins requiredScheduled reconciliation
AccuracyBalance equals ledger sum from a reference sourceNeeds reference dataEscalate, do not block

Encoding expectations with Great Expectations

Frameworks earn their keep by making expectations declarative, versioned and reusable. Instead of scattering assertions through transformation code, you declare a suite once, review it in a pull request like any other code, and run it as a checkpoint whenever new data lands. The suite becomes the executable form of the contract between the producer and every downstream consumer.

python
import great_expectations as gx

context = gx.get_context()

validator = context.sources.pandas_default.read_csv("data/orders.csv")

validator.expect_column_values_to_not_be_null("order_id")
validator.expect_column_values_to_be_unique("order_id")
validator.expect_column_values_to_be_between("amount", min_value=0, max_value=100000)
validator.expect_column_values_to_match_regex("email", r"^[\w\.-]+@[\w\.-]+\.\w+$")
validator.expect_column_values_to_be_in_set(
    "order_status", ["pending", "completed", "cancelled"]
)
validator.expect_table_row_count_to_be_between(min_value=1000, max_value=10000000)
validator.expect_column_pair_values_A_to_be_greater_than_B(
    "updated_at", "created_at", or_equal=True
)

results = validator.validate()

context.add_or_update_checkpoint(
    name="orders_checkpoint",
    validations=[{
        "batch_request": batch_request,
        "expectation_suite_name": "orders_suite",
    }],
).run()

Two habits separate teams who get value from those who do not. Store the suite in the same repository as the transformation so a schema change and its updated expectations land in one review. And keep a data asset snapshot with each run, because a failing assertion without the offending rows is a support ticket rather than a diagnosis.

A quality runner that scores a dataset

When a framework is heavier than you need, a small runner with a consistent output shape does most of the work. The critical design choice is that every check emits the same record: name, observed value, threshold and pass or fail. Once the shape is uniform you can trend it, alert on it, and aggregate it into a score without special-casing anything.

python
from datetime import datetime
from pyspark.sql import functions as F


class QualityRunner:
    def __init__(self, spark):
        self.spark = spark
        self.results = []

    def _record(self, check, passed, value, threshold):
        self.results.append({
            "check": check,
            "passed": bool(passed),
            "value": float(value),
            "threshold": float(threshold),
            "run_at": datetime.utcnow().isoformat(),
        })

    def completeness(self, df, columns, threshold=0.99):
        total = df.count() or 1
        for column in columns:
            present = df.filter(F.col(column).isNotNull()).count()
            self._record(f"completeness_{column}", present / total >= threshold, present / total, threshold)

    def uniqueness(self, df, key_columns, threshold=0.999):
        total = df.count() or 1
        distinct = df.select(*key_columns).distinct().count()
        ratio = distinct / total
        self._record(f"uniqueness_{'_'.join(key_columns)}", ratio >= threshold, ratio, threshold)

    def volume(self, current, mean, sigma, z_limit=3.0):
        z = (current - mean) / sigma if sigma else 0.0
        self._record("volume", abs(z) <= z_limit, z, z_limit)

    def summary(self) -> dict:
        passed = sum(1 for r in self.results if r["passed"])
        return {
            "total": len(self.results),
            "passed": passed,
            "failed": len(self.results) - passed,
            "score": round(100 * passed / len(self.results), 1) if self.results else 100.0,
        }

Keep the runner deterministic and side-effect free apart from appending results. A check that mutates the frame it is inspecting will eventually pass on data it just fixed, and that class of bug is remarkably hard to find after the fact.

Where checks belong in the pipeline

Placement decides what a failure costs. Checks at ingestion protect the lake from a source that changed underneath you, and a failure there should quarantine the batch rather than poison downstream models. Checks after transformation protect business logic and should block publication, because a wrong aggregate that reaches dashboards costs far more to correct than a delayed one. Checks at publish are the last gate and are the right place for cross-table consistency that cannot be evaluated earlier.

Architecture Diagram
ingest      raw lands, schema compared to contract, quarantine on mismatch
            completeness, validity, volume on the raw batch

transform   dedup, join and model, then business-rule assertions
            uniqueness on keys, consistency across conformed tables

publish     publish only if all gates green, else hold the partition
            freshness, row count and checksum against the prior run

downstream  consumers read a published-at timestamp and a quality score
            stale or low-scoring data raises a warning before the query

The quarantine path deserves as much attention as the check itself. Rejected rows should land somewhere queryable with the failing assertion attached, because the recovery question is always whether the data can be repaired and reloaded or must be re-extracted from a source that may no longer have it.

Anomaly detection when you have no explicit rule

Explicit assertions encode what you already know. Anomaly detection covers the long tail of things nobody anticipated, and it works well precisely because it needs no rule: compare today's distribution against a trailing baseline and escalate when the deviation is unusual. Row counts, null rates, distinct-key counts and numeric distributions all behave this way, and a three-sigma rule on the daily series catches a surprising share of real incidents within a day.

python
import statistics


class AnomalyMonitor:
    def __init__(self, history_days=30):
        self.history = {}
        self.history_days = history_days

    def observe(self, metric: str, value: float) -> None:
        self.history.setdefault(metric, []).append(value)
        if len(self.history[metric]) > self.history_days:
            self.history[metric].pop(0)

    def evaluate(self, metric: str, value: float, sigma_limit=3.0, min_points=14) -> dict:
        series = self.history.get(metric, [])
        if len(series) < min_points:
            return {"metric": metric, "status": "insufficient_history", "value": value}
        mean = statistics.fmean(series)
        sigma = statistics.pstdev(series)
        if sigma == 0:
            return {"metric": metric, "status": "flat", "value": value, "deviation": 0.0}
        deviation = (value - mean) / sigma
        status = "anomaly" if abs(deviation) > sigma_limit else "normal"
        return {"metric": metric, "status": status, "value": value, "deviation": round(deviation, 2)}

Baseline sensitivity matters. Compare Monday against a trailing mean that includes weekends and every Monday becomes an anomaly, so either keep separate baselines per weekday or use a seasonal-naive comparison against the same weekday in previous weeks. Getting this wrong is the fastest way to make the on-call team ignore the anomaly system entirely.

Data contracts as the shared vocabulary

Quality checks are only enforceable when the producer has agreed to them. A data contract captures that agreement in versioned, machine-readable form: the schema, the service level, the quality assertions and the ownership. When the producer changes a column without bumping the contract version, CI fails before the change reaches anyone, and the conversation happens with the person who can fix it rather than with the analyst who noticed a blank dashboard.

Contracts also make scale tractable. Rather than reviewing ten thousand tables by hand, you review the contract templates per domain, then let each domain instantiate them. The platform team owns the template and the enforcement mechanism; the domain owns the values. That split is what keeps a quality programme from collapsing into a central bottleneck.

Making quality visible to consumers

A check nobody can see has no influence on behaviour. Publish the score, the timestamp of the last successful run and the list of currently failing assertions directly beside the dataset in the catalog. Analysts make different decisions when they can see that a table is at ninety-two percent with a freshness breach versus assuming it is fine.

The feedback loop completes the system. When a quality failure reaches a consumer before the alert does, record that as an instrumentation gap and add the missing check. When a check fires repeatedly without anyone acting, tighten or retire it. Both signals tell you whether the programme is actually reducing risk or merely generating records.

✨Fail fast at ingestion

A bad record should never enter the lake. Quarantine at ingestion costs one batch to investigate; a bad record discovered after three joins and a materialized aggregate costs a backfill, a re-notification and a measure of trust you do not get back quickly.

Common Mistakes

Thousands of checks with no ownership

Fix: Bind every suite to a producing team and fail CI when a suite is orphaned

Checking only after transformation

Fix: Add an ingestion gate so bad batches are quarantined before they are joined

Comparing every day against a single trailing mean

Fix: Use weekday-aware baselines or a seasonal-naive comparison to avoid false anomalies

Failing on every assertion equally

Fix: Separate blocking gates from warnings so engineers keep trusting the red state

Best Practices

  • Keep suites in the same repository as the transformations they protect
  • Emit a uniform result record from every check so trends and scores come free
  • Quarantine rejected rows with the failing assertion attached for fast repair
  • Publish the quality score and last successful run next to the dataset
  • Retire checks that fire often and never change a decision

Interview Questions

Q1: How would you monitor quality across ten thousand tables?

Tier the estate: full suites on high-consumption tables, generic completeness and volume checks on the long tail, plus anomaly baselines everywhere, with ownership enforced so orphaned tables are escalated rather than ignored.

Q2: Where should a quality check run, and what happens on failure?

At ingestion to quarantine bad batches, after transformation to block wrong aggregates, and at publish for cross-table consistency. Failure quarantines, blocks or warns depending on which stage it sits in.

Q3: How do you handle quality checks on streaming data?

Run lightweight assertions per micro-batch on key presence, value ranges and lag, keep expensive cross-table reconciliation on a schedule, and route violations to a dead-letter topic for replay.

Q4: How do you measure the business impact of a quality issue?

Track incidents per month by dimension, time to detection and time to resolution, downstream dashboards or models affected, and the rework hours spent correcting published numbers.

Q5: What makes a quality score trustworthy?

Published weights, visible underlying values, deterministic computation, and a demonstrated correlation between a low score and issues that consumers actually cared about.

Key Takeaways

  • Automate completeness, uniqueness, validity and timeliness first
  • Declare expectations as versioned suites reviewed alongside transformation code
  • Uniform result records make trending, alerting and scoring nearly free
  • Placement determines cost: quarantine at ingest, block at transform, gate at publish
  • Anomaly baselines need weekday awareness or they generate noise
  • Publish the score beside the dataset or the programme has no influence
🔒

Premium Content

Data Quality at Scale: Frameworks, Tests, Contracts

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-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement