Data Contracts and Quality: The Contract Your Pipeline Never Signed
A practical guide to data contracts: schema, ownership, SLA, tests, Great Expectations, Soda, CI, alerts, and lineage for trustworthy data.
Table of Contents
On Monday morning the sales dashboard shows zero. There is no error, no alert, no red pipeline. The tables exist, the types are valid, and the job finished successfully. What changed was the meaning of a column: someone renamed total to order_total, and the revenue model kept reading total, which now arrived empty.
Nobody broke the schema. A promise that was never written simply broke. A data contract turns that promise into something executable: schema, owner, SLA, semantics, and tests that fail before the data reaches the dashboard.
What a data contract is, and what it is not
A data contract is a versioned agreement between the producer of a dataset and its consumers. It defines the shape of the data, its meaning, who is accountable for it, and what guarantees it offers. It is not another catalog entry or a Confluence page nobody updates. It is an artifact that lives in Git and that a pipeline can verify.
It is not a database schema either. The schema says total is decimal(12,2). The contract says total is the amount charged to the customer, in MXN, taxes included, never negative, and available before 8:00. A type change can be compatible; a meaning change cannot.
Most data incidents are not technical. They are semantic. The pipeline runs, the schema validates, and the number is wrong.
Anatomy of a contract that works
A useful contract has four parts: identity, schema, SLA, and quality. Identity says which dataset it is, who owns it, which domain it belongs to, and which contract version applies. The schema describes columns, types, nullability, and keys. The SLA defines freshness, availability, and volume. Quality lists the tests that must pass.
A custom format that humans and CI can read might look like this:
apiVersion: data.sazardev.com/v1
kind: DataContract
metadata:
name: orders
domain: commerce
owner: orders-team
steward: ana@example.com
version: 2.3.0
spec:
dataset: warehouse.orders
sla:
freshness: 60m
availability: 99.9%
schema:
- name: order_id
type: string
required: true
unique: true
- name: customer_id
type: string
required: true
- name: status
type: string
enum: [pending, paid, shipped, cancelled]
- name: total
type: decimal(12,2)
minimum: 0
- name: created_at
type: timestamp
required: true
quality:
- freshness: {column: created_at, max_age: 60m}
- row_count: {min: 1}
GX or Soda implement these checks; the contract remains the source of truth.
You do not need to invent a standard if your organization already has one. The Open Data Contract Standard (ODCS) is an open option when you need interoperability. What matters is that the contract is explicit, versioned, and verifiable.
The version is part of the contract. A jump from 2.3.0 to 3.0.0 implies a breaking change and a conversation with consumers; 2.3.0 to 2.3.1 should be compatible. Without versioning, every change is a gamble.
Ownership and SLA: the part nobody writes
I have seen teams write beautiful contracts and forget the owner. A contract without an owner is an orphan document: when it fails, everyone looks at everyone. You need an accountable team, a contact person, and an escalation channel.
owner and steward are different roles. The owner is accountable for availability and evolution; the steward protects semantics, documentation, and business rules. In small teams they can be the same person, but the role must be written down.
The SLA needs an operational definition. “Freshness of 60 minutes” means nothing without a measurement window, a timezone, and a failure procedure. A reasonable SLA covers freshness, volume, and availability, each with a threshold, a window, and a severity.
Tests: from a loose assert to an executable contract
A data test is not a SELECT count(*) WHERE id IS NULL sitting in a notebook. It is an assertion with a name, a severity, and context. The categories that cover most cases are schema, integrity (nulls, duplicates, foreign keys), freshness, volume, distribution, and semantics (allowed values, formats, business rules).
Not every failure should stop the pipeline. A customer without an email can be a warning; a duplicate order_id is critical. Severity decides whether data is published, quarantined, or merely reported.
Thresholds also need intent. mostly=0.999 on customer_id may be reasonable when 0.1% of orders are guest checkouts. mostly=0.9 on order_id is an elegant way to ignore 10% of your orders. Every exception needs a business reason.
Great Expectations: suites, validations, and checkpoints
Great Expectations (GX) is a Python library for declaring expectations about data and running them inside a pipeline. The current GX Core line is 1.x, and its API changed from the 0.18 version found in many tutorials. If you see great_expectations init or context.sources, you are reading old documentation.
A current example with a Pandas DataFrame:
import pandas as pd
import great_expectations as gx
df = pd.read_parquet("data/orders/dt=2026-12-05/part-000.parquet")
context = gx.get_context()
source = context.data_sources.add_pandas("orders_source")
asset = source.add_dataframe_asset("orders")
batch_definition = asset.add_batch_definition_whole_dataframe("daily_orders")
suite = context.suites.add(
gx.core.expectation_suite.ExpectationSuite(name="orders_contract")
)
suite.add_expectation(gx.expectations.ExpectTableRowCountToBeBetween(min_value=1))
suite.add_expectation(gx.expectations.ExpectColumnValuesToNotBeNull(column="order_id"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeUnique(column="order_id"))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeInSet(
column="status", value_set=["pending", "paid", "shipped", "cancelled"]
))
suite.add_expectation(gx.expectations.ExpectColumnValuesToBeBetween(
column="total", min_value=0, max_value=100000
))
suite.add_expectation(gx.expectations.ExpectColumnValuesToNotBeNull(
column="customer_id", mostly=0.999, severity="warning"
))
validation = context.validation_definitions.add(
gx.core.validation_definition.ValidationDefinition(
name="orders_daily", data=batch_definition, suite=suite
)
)
checkpoint = context.checkpoints.add(
gx.checkpoint.checkpoint.Checkpoint(
name="orders_checkpoint", validation_definitions=[validation]
)
)
result = checkpoint.run(batch_parameters={"dataframe": df})
if not result.success:
raise SystemExit("orders contract failed")
The suite groups expectations, the validation definition binds a suite to a batch, and the checkpoint runs one or more validations and can trigger actions. The SystemExit turns a report into a control: the scheduler marks the task as failed and does not publish the data.
GX shines when you need Python expressiveness, Pandas or Spark DataFrames, or rules that combine columns. The cost is a real learning curve and an API that rewards reading the documentation for the right version.
Soda Core: YAML contracts and a CLI
Soda Core takes the opposite bet: a concise YAML contract and a CLI that fits easily into CI. Version 4.x changed the model from 3.x: data contracts are the default, and the checks for orders: syntax from older tutorials is no longer current.
A contract for a Postgres table:
dataset: postgres/analytics/public/orders
columns:
- name: order_id
data_type: character varying
checks:
- missing:
- duplicate:
- name: customer_id
data_type: character varying
checks:
- missing:
- name: status
data_type: character varying
checks:
- invalid:
valid_values: ['pending', 'paid', 'shipped', 'cancelled']
- name: total
data_type: numeric
checks:
- invalid:
valid_min: 0
- name: created_at
data_type: timestamp without time zone
checks:
- missing:
checks:
- schema:
- row_count:
- freshness:
column: created_at
threshold:
unit: hour
must_be_less_than: 24
The data source configuration is separate:
type: postgres
name: postgres
connection:
host: localhost
port: 5432
user: analyst
password: ${env.SODA_PASSWORD}
database: analytics
Verification comes down to two commands:
soda contract test --contract contract.yml
soda contract verify --data-source ds_config.yml --contract contract.yml
contract test validates the YAML structure without reading data. contract verify runs the checks and returns a non-zero exit code when the contract fails. That detail is what makes it usable in a pipeline or pull request without a custom wrapper.
Soda is easier to adopt when the team lives in SQL and wants contracts that analysts can read. GX is more flexible when rules need Python or logic that does not fit in YAML.
Great Expectations vs Soda: the honest decision
| Criterion | Great Expectations | Soda Core |
|---|---|---|
| Approach | Python API and expectation suites | YAML contracts and CLI |
| Learning curve | Medium-high | Low-medium |
| Sources | Pandas, Spark, SQL | SQL, DuckDB, Spark, Pandas |
| Expressiveness | High | High for declarative checks |
| CI integration | Python script | CLI command |
| License | Apache 2.0 for GX Core | Check the 4.x license |
The table does not decide for you. If your team writes Python all day and needs complex validations, GX fits. If analysts will read the contract and you want CI to be a command, Soda fits. Running both for the same job has a cost; use them together only when each covers a different layer.
The decision that matters is not the tool. It is who owns the contract and how they find out when it fails.
Validate at ingestion and in CI
The worst place to validate is after publishing. If the data is already in the table behind the dashboard, the incident has happened. The right pattern is to validate before promotion:
extract -> validate -> quarantine if failed -> publish -> catalog
Quarantine can be a table, an S3 prefix, or a topic. The important part is that invalid data does not reach consumers and the producer gets details: which check failed, how many rows, a sample, and the owner.
In CI, contracts are tested at two levels. On every pull request you validate the contract structure and run tests against a sample dataset or an ephemeral database. In the scheduled pipeline you verify against staging or production and block publication on failure.
name: data-contracts
on: [pull_request]
jobs:
contracts:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install soda-core soda-postgres great_expectations pandas pyarrow pytest
- run: soda contract test --contract contracts/orders.yml
- run: pytest -q tests/contracts
The first level needs no production credentials. The second does, so run it in a controlled environment with secrets and read-only permissions.
Alerts, lineage, and incident response
A useful alert answers five questions: which dataset, which check, which severity, who owns it, and what to do. Without a runbook, the alert becomes a message someone mutes at 2 a.m.
Severity decides the channel. A critical freshness failure wakes the on-call engineer. A null warning on a secondary column goes to Slack and waits for business hours. If your team gets 40 alerts a day, none of them is important.
Lineage closes the loop. When orders fails, you need to know which dashboards, models, and teams depend on that table. OpenLineage, Marquez, DataHub, and OpenMetadata capture table- or column-level lineage. Without it, impact analysis means asking in chat and waiting for luck.
Scenarios and common mistakes
The silent rename
The orders team renames total to order_total because the old name was ambiguous. The table schema is still valid and the pipeline does not fail. The revenue dashboard shows zero. A schema check with required columns and a contract test in the producer would have caught it before deployment.
The duplicate from a retry
A job retries after a timeout and inserts the same orders again. The count doubles, revenue inflates, and nobody sees an error. A duplicate check on order_id catches it at ingestion. The real fix is an idempotency key, not a DISTINCT in the dashboard.
Freshness nobody measures
The pipeline falls six hours behind because of a network issue. The dashboard still shows yesterday’s data, looking exactly like today’s. A freshness check on created_at alerts before someone decides with stale data.
Mistakes that repeat
- A contract without an owner. When it fails, nobody knows whom to call.
- Validating after publishing. Consumers already saw the bad data.
- Tests coupled to implementation. They check internal columns instead of the real contract.
- Magic thresholds.
mostly=0.9without justification silences failures. - Everything is critical. If everything wakes the on-call, nothing does.
- No contract versioning. An incompatible change is discovered in production.
- No backfill test. The contract passes on new data and fails on history.
- Confusing a green pipeline with correct data. A successful job only proves the job ran.
Checklist
- Every critical dataset has an owner, a steward, and a contact channel.
- The contract is versioned in Git and has a change process.
- The schema defines types, nullability, keys, and required fields.
- The SLA measures freshness, volume, and availability with clear windows.
- Critical checks block publication; warnings do not.
- Validation happens before publishing, with quarantine for invalid data.
- CI tests the contract on every pull request.
- Alerts include dataset, check, severity, owner, and runbook.
- Lineage shows which dashboards and models depend on the data.
- There is a plan for backfills and breaking changes.
A data contract is not a document you sign and archive. It is an executable promise: when the data changes shape or meaning, the pipeline stops before the dashboard lies.
Related articles
By relevance
Data forensics on Windows: 3 network drives, SQL Server, and a lakehouse on your PC
Hands-on Windows case: share 3 disks over SMB, configure SQL Server, sync with robocopy, and unify everything with DuckDB, Polars, and Parquet.
Data forensics in a factory: 18 months of files, one missing piece, and a lakehouse on your laptop
Hands-on case: date folders, nested blocks, movements, and logs. Unify, normalize, and trace a piece with DuckDB, Polars, and Parquet.
Go Notes API: BDD, TDD, DDD, Hexagonal Architecture with Gin, gRPC, Redis & PostgreSQL
Build a production-ready Notes API in Go 1.24+ using BDD, TDD, DDD, Hexagonal Architecture, Gin, gRPC, Redis, PostgreSQL, JWT auth, Docker, FX, and Zap. Step by step.
Go 1.26 Full-Stack Notes App: SolidJS, Auth, Hexagonal Architecture & DDD from Zero
Build a full-stack notes app in Go 1.26 with SolidJS, JWT auth, and Hexagonal Architecture. Step-by-step from zero to production with DDD, TDD, and BDD.