Building a Data Contract Between Services
Define the fields, types and guarantees a producer owes its consumers, enforce the contract in tests, and evolve it without breaking downstream jobs.
On this page
Introduction
A service that emits events or tables is de facto publishing an interface, whether or not anyone wrote it down. When the schema changes silently, every consumer that parsed the old shape breaks at once, usually at 3am on a weekend. A data contract makes that interface explicit: the fields, their types, their semantics, their nullability and the compatibility rules that govern change. It converts an implicit assumption into a tested guarantee, so evolution is a deliberate act rather than an accident that surfaces as a downstream outage. A contract is only real when a test enforces it, so the specification and the check must ship together.
Why Implicit Schemas Break
When the only definition of an event is the code that writes it, consumers reverse engineer field meanings from samples and guess which are optional. A producer renames a field for clarity and a consumer stops seeing data without any error, because an extra or missing key in JSON is silent. Nobody is wrong and everybody is broken, which is the signature of an interface that was never specified. The contract is the artefact that makes both sides explicit and testable.
from jsonschema import Draft202012Validator
CONTRACT = {
"$id": "orders.v2",
"type": "object",
"properties": {
"order_id": {"type": "string", "minLength": 1},
"amount_cents": {"type": "integer", "minimum": 0},
"currency": {"enum": ["USD", "EUR", "GBP"]},
"created_at": {"type": "string", "format": "date-time"}, # event time, UTC
"coupon": {"type": ["string", "null"]}, # added in v2, optional
},
"required": ["order_id", "amount_cents", "currency", "created_at"],
"additionalProperties": True, # consumers ignore unknown fields
}
_validator = Draft202012Validator(CONTRACT)
def validate_event(event: dict) -> tuple[bool, str | None]:
errors = sorted(_validator.iter_errors(event), key=lambda e: list(e.path))
if errors:
e = errors[0]
return False, f"{list(e.path)}: {e.message}"
return True, None
What a Contract Specifies
A useful contract states each field name, type, whether it is required or nullable, its allowed values or range, its units, and an example. It also states semantics, not only syntax: whether a timestamp is event time or processing time, whether an amount includes tax, whether a deleted entity is absent or tombstoned. Finally it states delivery guarantees such as at least once, and the ordering guarantees consumers may rely on. Syntax alone leaves the hardest questions unanswered.
from jsonschema import Draft202012Validator
def is_backward_compatible(old: dict, new: dict) -> tuple[bool, list[str]]:
# Adding optional fields is safe; removing fields or tightening types is not.
problems: list[str] = []
old_props, new_props = old.get("properties", {}), new.get("properties", {})
for name, spec in old_props.items():
if name not in new_props:
problems.append(f"removed field: {name}")
for name in old.get("required", []):
if name not in new.get("required", []):
problems.append(f"field became optional: {name}")
for name in new.get("required", []):
if name not in old.get("required", []):
problems.append(f"field became required (breaking): {name}")
return (not problems), problems
Compatibility Rules
Define up front what counts as a breaking change. Adding an optional field is usually safe; removing a field, renaming one, changing its type, tightening a range or making an optional field required is breaking. Decide whether consumers ignore unknown fields, which allows additive change without coordination, and enforce that in the consumer library. State the rule so a producer knows before shipping whether they must version or can extend in place.
Enforcing the Contract in CI
Validate that the producer output conforms to the contract on every build and that the contract has not changed incompatibly against the previous version. Run the same schema against real or generated samples so a drift between code and contract fails fast. Publish the schema to a registry so consumers can pin a version and subscribe to change notifications. A contract enforced only by documentation drifts within weeks; one enforced by tests survives.
Versioning and Evolution
Version the contract and keep it backward compatible within a major version, mirroring API versioning practice. Additive changes go in the same major; breaking changes require a new major with a deprecation window and a migration path for consumers. Emit the version in each record so a consumer can handle both shapes during transition. Never reuse a version number after changing semantics, because consumers cache schemas and will apply the wrong rules.
Consumer-Side Validation
Consumers should validate incoming data against the pinned contract and quarantine records that fail rather than silently accepting them into a pipeline. Quarantining with the failure reason turns a data quality incident into a bounded, inspectable set of records. Validate at the boundary, once, rather than trusting every internal field thereafter, and fail closed for records that would corrupt aggregates. This is the same defence as validating user input, applied to inter-service data.
Detecting Contract Drift
Even with validation, producers drift. Monitor the observed schema in the stream against the declared one: new fields, missing fields, type changes and null rate changes all signal that reality and contract have diverged. Alert on unexpected fields because they usually indicate a producer changed something without updating the contract, which means the contract is no longer the source of truth.
Organisational Mechanics
A contract needs an owner, a review path and a change log. Producers propose changes, consumers review them for impact, and the registry records who approved and when. Without ownership the contract rots; without review the breaking change ships. Keep the contract in the same repository as the producer so it is updated in the same pull request, and make a missing or stale schema fail the pipeline.
Testing the Contract
Test that valid records pass, that each documented violation is rejected with the right error, that the last compatible schema still validates against new output, and that a simulated breaking change fails the compatibility check. Include a consumer test that pins the version and proves it tolerates an added optional field. These tests are cheap and they catch the exact class of change that otherwise reaches production during a holiday.
Sources
Sources: JSON Schema, Avro schema evolution, Confluent schema registry.
FAQ
- Is adding a field a breaking change?
- Not if consumers ignore unknown fields and the field is optional. Make that tolerance explicit in the contract and consumer library, then additive change is safe without coordination.
- Where should the contract live?
- In the producer repository so it is updated in the same pull request as the code, and published to a registry so consumers can pin a version and be notified of changes.
Report a problem with this articleOpens a pre-filled issue on GitHub.