How-To Guide

How to Detect Schema Drift in Data Pipelines

Catch producer changes before they corrupt downstream tables: compare observed schemas against a pinned contract and quarantine the records that diverge.

On this page

  1. Introduction
  2. What Schema Drift Is and Why It Breaks Pipelines
  3. Pinning an Expected Schema
  4. Sampling and Comparing Observed Schemas
  5. Classifying Drift: Additive, Breaking and Cosmetic
  6. Quarantining Records and Alerting
  7. Backfilling and Reconciling After Drift
  8. Conclusion

Introduction

A data pipeline is only as trustworthy as its assumptions about the shape of its input. Producers evolve: someone adds a column, renames a field, changes a type from integer to string, or starts emitting nulls where the pipeline expects values. If the consumers never notice, the damage shows up later as wrong aggregates, silently dropped rows, or a dashboard that quietly reports zeros. Schema drift detection is the practice of continuously comparing what a producer actually emits against the schema the pipeline was built for, and failing loudly the moment they diverge. This article shows how to pin an expected schema, compare it against observed data, classify the drift, and quarantine records instead of corrupting downstream tables.

What Schema Drift Is and Why It Breaks Pipelines

Schema drift is any change in the structure or types of incoming data that the consumer did not plan for. It comes in two forms: the schema declared by the producer changes, or the data no longer conforms to the declared schema. Both are dangerous because pipelines are built on assumptions that are implicit in code. A column added at the end is usually harmless; a column removed, a type changed, or a field that was always present suddenly becoming null can break joins, fill aggregates with nulls, or crash a strict parser and halt the pipeline.

The cost of undetected drift grows with pipeline length. If the change happens at ingestion and is caught there, the blast radius is one batch. If it propagates three transformations deep, you must trace which downstream tables were written from bad data, then backfill them. Detecting drift close to the source, before any transformation, is the cheapest place to stop it.

Pinning an Expected Schema

Detection needs a reference. Pin the schema the pipeline expects in version control, next to the pipeline code, so a change to the contract is a reviewable diff rather than an invisible assumption. Express it in a standard form such as JSON Schema or a typed model so both validation and documentation come from one source. Record required fields, types, permitted nullability, and value constraints together, because a field that changes from non-null to nullable is drift even when the type is unchanged.

Alongside the schema, record a version and a compatibility policy. Additive optional fields are backward compatible and can flow through automatically; removing a field, tightening a type, or making an optional field required is a breaking change that must be reviewed by consumers before the producer ships it.

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "OrderEvent",
  "type": "object",
  "required": ["order_id", "amount", "currency", "created_at"],
  "properties": {
    "order_id": { "type": "string", "minLength": 1 },
    "amount": { "type": "number", "minimum": 0 },
    "currency": { "type": "string", "enum": ["USD", "EUR", "GBP"] },
    "created_at": { "type": "string", "format": "date-time" },
    "channel": { "type": ["string", "null"] }
  },
  "additionalProperties": false
}

Sampling and Comparing Observed Schemas

At ingestion, infer the observed schema from a sample of records and compare it with the pinned schema. Inference means walking each record, recording the path of every field and the inferred type of its value, and merging those observations across the sample. Nullability is inferred too: a field is nullable if any sampled record has it absent or null. Comparing the inferred schema to the pinned one yields a set of differences you can classify.

from __future__ import annotations
from typing import Any

def infer_schema(records: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
    schema: dict[str, dict[str, Any]] = {}
    for rec in records:
        for key, value in rec.items():
            slot = schema.setdefault(key, {"types": set(), "nullable": False})
            if value is None:
                slot["nullable"] = True
            else:
                slot["types"].add(type(value).__name__)
    return schema

def diff_schema(expected: dict, observed: dict) -> list[str]:
    problems: list[str] = []
    for field, spec in expected.items():
        if field not in observed:
            problems.append(f"missing field: {field}")
            continue
        got = observed[field]["types"]
        if not got <= set(spec["types"]):
            problems.append(f"type drift on {field}: {sorted(got)}")
        if observed[field]["nullable"] and not spec.get("nullable", False):
            problems.append(f"unexpected nullability: {field}")
    for field in observed:
        if field not in expected and not expected.get("allow_extra", True):
            problems.append(f"unexpected field: {field}")
    return problems

Classifying Drift: Additive, Breaking and Cosmetic

Not all drift deserves the same response. Additive drift introduces new fields; if the pipeline ignores unknown fields it is compatible, and you can log it without failing. Cosmetic drift renames or reorders fields with identical semantics, which usually needs a mapping update. Breaking drift removes required fields, changes a type incompatibly, or introduces nulls into a field the transform treats as non-null; this must halt the batch before it writes anything downstream.

Classify with explicit rules, not judgement on the fly. Encode which fields are optional, which types are coercible, and which renames are known aliases. Then a drift report becomes a list of typed findings, each with a severity, so the on-call engineer can decide quickly instead of reading a wall of raw differences.

Quarantining Records and Alerting

When drift is breaking, do not write the batch. Route the offending records to a quarantine table, tag them with the batch identifier and the reason they failed, and let the pipeline continue with the records that passed rather than dropping the whole run. Quarantining preserves the evidence needed to diagnose the producer change, and it keeps the healthy portion of the data flowing. Dropping records silently is the worst option because nobody learns that data was lost.

Alert on the drift event, not only on the downstream failure. The alert should name the field, the expected and observed types, the sample record that triggered it, and the producing source. That information turns a vague report that the dashboard looks wrong into a specific, actionable message that points at the producer that changed.

Backfilling and Reconciling After Drift

Once you have republished or corrected the producer, you need to reconcile. Replay the quarantined records through the updated pipeline, then recompute any aggregates that were derived from the affected window. Because the downstream tables were written from a mix of conforming and non-conforming data, you cannot assume they are correct; you must recompute the affected partition and compare row counts and key sums before and after.

Add a reconciliation check that runs after every backfill: total rows loaded, distinct keys, and a checksum of a numeric column. If the recomputed numbers match the source and the drift report is empty, the incident is closed. This same reconciliation discipline is what makes any data pipeline auditable.

Conclusion

Schema drift detection is a small amount of code with an outsized payoff: pin the expected schema in the repository, infer the observed schema at ingestion, diff them, classify the differences, quarantine records on breaking drift, and alert with enough context to identify the producer. Fail closed for records that would corrupt aggregates and fail open for additive, backward-compatible changes. Do that and a producer change becomes a routine, reviewable event instead of a silent corruption that surfaces weeks later.

Sources: JSON Schema, Avro schema evolution, Confluent Schema Registry.

FAQ

Should drift detection fail the whole pipeline or just the bad records?
Prefer quarantining the records that violate the contract and continuing with the rest. Failing the entire run loses good data and delays the signal, while continuing with corrupted records is worse still. Quarantine preserves both throughput and evidence.
Where should the expected schema live?
In version control alongside the pipeline code, so a contract change is a reviewable diff. A standard format such as JSON Schema lets the same definition drive validation, documentation and compatibility checks.

Related Examples