Data contracts explained: a YAML example and enforcement
What a data contract specifies, how it differs from a schema registry or a dbt test, the three places to enforce it, and the organisational part that sinks most rollouts.
A data contract is a versioned, machine-checked agreement between the team that produces a dataset and the teams that consume it: which columns exist, what type and meaning each one has, which quality rules hold, how fresh the data will be, and who to call when it breaks. The word that matters is machine-checked. A schema documented in a wiki is a description; a contract is a file in version control that fails a build when someone violates it. The idea borrows from API design, where a service would never rename a response field without a version bump, and applies it to the tables and event streams that analytics depends on. The tooling has settled down: the Open Data Contract Standard (ODCS) is the shared YAML format, governed under the Linux Foundation AI & Data, and the older Data Contract Specification is being retired in its favour. What has not settled is the hard part: getting producers to own the contract. This guide covers both.
What does a data contract specify?
A useful contract answers five questions a consumer would otherwise have to discover by breaking something. The ODCS reference has 15 sections in total, but these are the ones that carry the weight:
| Section | What it pins down | Example |
|---|---|---|
| Schema | Tables or topics, columns, logical and physical types, keys, required fields | amount_cents is a non-null bigint |
| Semantics | What a column means, in business terms | “Order total in minor units, tax included” |
| Quality | Rules the data must pass, with thresholds | No negative amounts; currency in a known list |
| Service levels | Freshness (latency), update frequency, retention | Rows land within 2 hours of creation |
| Ownership and support | The owning team, the channel for issues | checkout-platform, #checkout-data |
Two more sections matter once more than one team reads the data: classification (which columns are personal data, so the warehouse can mask them) and servers (where the dataset physically lives, so a test runner knows what to connect to).
Semantics deserves a word. Most data incidents are not type errors. A column called amount that silently switches from “before tax” to “after tax” passes every schema check ever written. Only a written definition, owned by someone who will be asked before it changes, catches that kind of change.
Data contracts vs schemas, schema registries and dbt tests
Data contracts overlap with tools teams already run, which is why the term causes so much confusion. The distinction is scope and ownership:
| Tool | Covers | Owned by | Enforced |
|---|---|---|---|
| Database DDL | Physical columns and types | The producing service | At write time, in one database |
| Schema registry (Kafka) | Message structure and evolution rules | The producing service | At produce/consume time, per topic |
| dbt tests | Quality rules on warehouse tables | The analytics team | After data lands |
| dbt model contracts | Column names and types of a dbt model | The analytics team | At model build time |
| Data contract | Schema, semantics, quality, SLAs, owner | The producer, agreed with consumers | In producer CI, at ingestion and in the warehouse |
A schema registry is the closest relative, and on Kafka it is often the enforcement point for a contract. Confluent’s Schema Registry checks each new schema version against a compatibility mode before it is accepted (the default is BACKWARD, meaning consumers on the new schema can read data written with the previous one). Confluent now uses the term itself: its data contracts add metadata, tags and rules to a schema, including CEL data-quality conditions that can send failing messages to a dead letter queue (the DLQ action is currently supported in the Java client). Those rules need Confluent Platform 7.4 or later, on the Enterprise edition, or Confluent Cloud with the Advanced Stream Governance package. A registry still only sees the topic. It does not know about the freshness SLA, the business definition or the warehouse table built from the topic.
dbt tests sit at the other end. They run after the data has landed, which is exactly when the analytics team learns about a break, and they are owned by the consumer, not the producer. They are necessary (see the data-quality tests every warehouse needs), but a test suite on its own is the consumer guessing at an agreement the producer never made.
A data contract example in YAML
Here is a complete contract for an orders table owned by a checkout team, written to ODCS v3.2.0, the current release. It validates against the official ODCS JSON Schema and passes datacontract lint.
apiVersion: v3.2.0
kind: DataContract
id: checkout-orders
name: Checkout orders
version: 1.2.0
status: active
domain: checkout
description:
purpose: One row per order placed through checkout, for revenue reporting.
limitations: Excludes orders created by the support back office.
usage: Finance revenue dashboards, weekly cohort analysis.
servers:
- server: production
type: postgres
host: orders-db.internal
port: 5432
database: checkout
schema: public
schema:
- name: orders
physicalName: orders
physicalType: table
description: One row per order. Updated in place when status changes.
properties:
- name: order_id
logicalType: string
physicalType: uuid
primaryKey: true
required: true
unique: true
- name: customer_id
logicalType: string
physicalType: uuid
required: true
- name: amount_cents
logicalType: integer
physicalType: bigint
required: true
description: Order total in minor units, tax included.
quality:
- id: amount_not_negative
type: sql
query: SELECT count(*) FROM orders WHERE amount_cents < 0
mustBe: 0
- name: currency
logicalType: string
physicalType: char(3)
required: true
quality:
- id: currency_known
metric: invalidValues
arguments:
validValues: ['EUR', 'USD', 'GBP']
mustBe: 0
- name: status
logicalType: string
physicalType: text
required: true
quality:
- id: status_known
metric: invalidValues
arguments:
validValues: ['pending', 'paid', 'refunded', 'cancelled']
mustBe: 0
- name: created_at
logicalType: timestamp
physicalType: timestamptz
required: true
- name: customer_email
logicalType: string
physicalType: text
classification: restricted
quality:
- id: orders_not_empty
metric: rowCount
mustBeGreaterThan: 0
slaProperties:
- property: latency
value: 2
unit: h
element: orders.created_at
- property: retention
value: 7
unit: y
team:
name: checkout-platform
members:
- username: checkout-oncall
role: owner
support:
- channel: '#checkout-data'
tool: slack
A few choices worth copying:
versionis the contract’s own version, separate fromapiVersion(the version of the standard). Use semantic versioning: a breaking change bumps the major version and gets a migration window.logicalTypeandphysicalTypeare both set. The logical type is what consumers code against; the physical type is what the producer’s database actually stores. A warehouse can mapintegerto its own type without the contract pretending every engine has abigint.- Quality rules use the built-in metrics where possible (
invalidValues,rowCount, alsonullValues,missingValuesandduplicateValues) and fall back totype: sqlfor business rules. The built-in metrics can be translated to any engine; SQL is tied to one dialect. customer_emailis markedrestricted. That is the hook for masking it downstream.
Where is a data contract enforced?
A contract that nothing checks is documentation. There are three enforcement points, and they catch different failures, so mature setups use all three.
1. In the producer’s CI, before the change ships
This is the point that makes a contract a contract. The file lives in the producer’s repository, next to the code that writes the table, and every merge request that touches it is checked for breaking changes against the version on main. The open source Data Contract CLI (MIT licence) does both the lint and the comparison. A GitLab CI job:
contract-check:
image: python:3.12
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
changes: [contracts/orders.odcs.yaml]
script:
- pip install --quiet datacontract-cli
- datacontract lint contracts/orders.odcs.yaml
- git fetch --depth=1 origin "$CI_DEFAULT_BRANCH"
- git show "origin/$CI_DEFAULT_BRANCH:contracts/orders.odcs.yaml" > /tmp/orders.main.yaml
- datacontract breaking /tmp/orders.main.yaml contracts/orders.odcs.yaml
Run against the example above, removing the currency column and changing amount_cents to numeric(12,2) makes datacontract breaking report two errors and exit non-zero, so the merge request goes red. Adding a new optional coupon_code column reports only informational changes and exits zero. That is the behaviour you want: additive changes flow, breaking ones need a conversation.
Two gaps remain. CI checks the contract file, not the database, so someone can still change the table without touching the contract; add datacontract test against a staging database to close that. And a producer can always bump the major version. The tool cannot stop that; your process has to.
2. At ingestion, when data crosses into the warehouse
Ingestion is where a contract meets reality. The loader should compare what arrived with what was promised, and pick a policy per dataset: fail the load, quarantine the new data, or load it and alert. Many ELT tools detect schema drift; the question is whether anybody decided what happens next.
Even without tooling support, the check is one query. In ClickHouse, compare the landed table to the contract’s columns using system.columns:
WITH contract AS (
SELECT * FROM values('name String, type String',
('order_id', 'UUID'),
('customer_id', 'UUID'),
('amount_cents', 'Int64'),
('currency', 'LowCardinality(String)'),
('status', 'LowCardinality(String)'),
('created_at', 'DateTime64(3, \'UTC\')'))
),
actual AS (
SELECT name, type FROM system.columns
WHERE database = 'raw' AND table = 'orders'
)
SELECT
c.name AS contract_column,
c.type AS contract_type,
a.type AS actual_type,
multiIf(a.name = '', 'missing', a.type != c.type, 'type changed', 'ok') AS verdict
FROM contract AS c
LEFT JOIN actual AS a ON a.name = c.name
WHERE verdict != 'ok'
ORDER BY contract_column;
Against a landing table where currency was dropped and amount_cents arrived as Decimal(12, 2), it returns exactly those two rows. Zero rows means the landing matches the contract. Extra columns in the landing table are deliberately ignored: additions are not breaking.
3. In the warehouse, as tests and build-time checks
The warehouse layer turns the contract’s quality rules into tests that run on a schedule, and makes sure your own models honour the contracts you publish to the next team down. dbt has had model contracts since v1.5. With contract: {enforced: true}, dbt runs a preflight check that the model’s query returns exactly the declared column names and data types, and refuses to build otherwise:
models:
- name: fct_orders
config:
contract:
enforced: true
columns:
- name: order_id
data_type: UUID
constraints:
- type: not_null
- name: amount_cents
data_type: Int64
- name: currency
data_type: LowCardinality(String)
Read the fine print. Contracts work on table, view (no constraints) and incremental models (only with on_schema_change: append_new_columns or fail), not on ephemeral models, Python models or sources. Constraint enforcement depends on the platform: the dbt docs note that most platforms only enforce not_null, and where not_null and check are only enforced after the build, dbt does not count them as part of the contract. dbt also ignores type size and precision differences by design.
On ClickHouse, two engine behaviours matter. First, CHECK constraints are real: each one is evaluated for every inserted row, and a violating insert fails with VIOLATED_CONSTRAINT. Rows already in the table are not rechecked when you add one.
ALTER TABLE raw.orders ADD CONSTRAINT amount_not_negative CHECK amount_cents >= 0;
Second, and less obvious: by default ClickHouse does not reject a NULL sent to a non-Nullable column. With input_format_null_as_default and insert_null_as_default both at their default of 1, the NULL becomes the column’s default value, so a missing amount lands as 0 and a missing currency as an empty string. A “required” column can therefore look perfectly populated. Either set those settings to 0 for contracted loads, so the insert fails, or test for the default value (amount_cents = 0, currency = '') instead of only IS NULL.
What changes count as breaking?
Most contract disputes come down to this table. Agree on it before the first incident, and put it in the contract’s README:
| Change | Breaking? | Why |
|---|---|---|
| Add an optional column | No | Existing queries keep working |
| Add a required column | Usually no for readers | Breaks anyone who writes to the dataset |
| Remove or rename a column | Yes | Every query naming it fails |
Change a type (bigint to numeric) | Yes | Casts, joins and aggregates change behaviour |
Widen an enum (status gains disputed) | Often | CASE statements and filters silently drop the new value |
| Change meaning (tax included to excluded) | Yes, and invisible | No schema check can see it |
| Loosen an SLA (2h latency to 24h) | Yes | Dashboards promise freshness they no longer have |
The enum row is the one teams forget. Adding a value is “additive” in schema terms, yet every status IN ('paid', 'refunded') filter in the warehouse just stopped counting the new state. Treat closed lists as part of the interface.
Why data contract rollouts fail
The tooling is the easy part. Contracts fail on organisation, in roughly this order:
The producer never agreed. The most common failure is an analytics team writing contracts for data it does not own and calling them contracts. Without the producing team signing up, it is a test suite with a new name. The producer has to gain something: fewer late-night questions, a clear list of who reads its data, or freedom to change everything the contract does not cover.
Nobody knows who the consumers are. A producer cannot assess a breaking change without knowing who reads a column. This is where lineage earns its keep: column-level lineage turns “who uses amount_cents?” from a Slack poll into a query.
Everything gets a contract. Contracting 400 tables at once produces 400 stale YAML files. Start with the five to ten datasets that feed revenue reporting or a customer-facing product, where a break has a cost someone can name.
Breaking changes have no path. If the only options are “never change” or “break it”, producers will route around the contract. Define the escape hatch up front: a new major version published alongside the old one, a deprecation window of a fixed length (for example 60 days), and a named date when the old version stops.
Violations have no owner. A failing contract check that posts into a channel nobody watches teaches everyone to ignore it. Every contract names an owning team, and every violation pages that team, not the consumer who noticed.
A rollout that survives usually looks like this: pick one high-value dataset, get the producing team to co-author the contract, wire the CI check into their repository, add the ingestion check and warehouse tests on your side, then run one real breaking change through the versioning process before adding the second dataset.
Where Goni fits
Goni covers the warehouse half of this list. Full disclosure: this is our product. Its YAML semantic layer declares tests on sources and models (not_null, unique, accepted_values, row_count_min, row_count_max, freshness and custom_sql) plus source freshness contracts, runs them on a schedule, and sends a webhook when a test flips from pass to fail. Pipelines can notify on schema changes and show which dashboards, charts and models depend on a table, and column-level lineage traces each model column back to its sources. The drawbacks: Goni does not read ODCS files or run checks in the producer’s CI, so you restate the contract’s rules as Goni tests; ClickHouse is the only warehouse it queries; and it is not open source. If that trade fits, the 14-day free trial is the quickest way to see it on your own data.
FAQ
What is a data contract in simple terms?
A data contract is a written, versioned promise from the team that produces a dataset to the teams that use it. It lists the columns and their meaning, the quality rules the data passes, how fresh it will be and who owns it. It lives in version control and is checked automatically, so a breaking change fails a build.
What is the difference between a data contract and a schema registry?
A schema registry stores message schemas for a stream such as a Kafka topic and blocks incompatible versions. A data contract is broader: it also covers business meaning, quality rules, freshness SLAs and ownership, and can span databases and warehouse tables. On Kafka, the registry is often how the contract’s schema part gets enforced.
What format should a data contract use?
Use the Open Data Contract Standard (ODCS), a YAML format maintained by the Bitol project under the Linux Foundation AI & Data. The current release is v3.2.0. The older Data Contract Specification is deprecated in favour of ODCS, and tools such as the Data Contract CLI lint and test ODCS files natively.
Are dbt model contracts the same as data contracts?
Not quite. A dbt model contract guarantees that a model’s columns and data types match its YAML before it builds, which is the schema part of a data contract for a model you publish. It does not cover freshness SLAs, ownership or producer-side checks, and it applies only to dbt models, not to sources.
Who should own a data contract?
The producing team should own it, because only the producer can prevent a breaking change before it ships. Consumers help write it and say which columns and rules they depend on. A contract written only by consumers for data they do not control is really a test suite, and it catches breaks after they happen.