Write a Data Contract Before Scheduling an AWS Pipeline
Define an AWS pipeline data contract for fields, units, time windows and failure handling. Includes a tested Python JSON Lines validator and DQDL guidance.
A pipeline data contract defines accepted structure, business meaning, dataset expectations and failure behavior. Validate before publication, distinguish per-record rules from batch completeness, and define replay handling before scheduling. Schema compatibility is only one part of that promise.
Define the consumer promise before the schedule
A scheduled pipeline can complete successfully while publishing data that a consumer cannot use. A field may still be present but have a new unit, a valid event may belong to yesterday’s window, or a retry may double a total. Scheduling determines when work runs; a data contract determines what the resulting data promises.
Start with one consumer and one decision the data supports. Ask what would make that decision wrong: a missing identifier, a changed currency, a late partition, a duplicate event or an incomplete batch. Translate each answer into an explicit rule, its evaluation scope and the action taken on failure. Avoid a contract that says only “the data must be good.”
The example here is a small daily event feed, unrelated to real customer records. It uses a local validator to make the contract concrete before an AWS implementation is chosen. The local code is not an AWS SDK, JSON Schema engine or replacement for Glue Data Quality. It is an executable specification of this particular feed.
Make the scope and units visible
The teaching contract accepts a UTF-8 JSON Lines batch containing one object per physical line. It permits 1–100 records and at most 65,536 bytes. Every record has exactly five fields. A trailing line terminator is accepted, but blank records are not. These small limits make the demonstration reproducible; a production feed needs limits based on its own operational requirements.
Amounts are integer cents in USD, not floating-point dollars. The event timestamp is UTC with whole-second precision and belongs to the half-open interval start <= occurred_at < end. Version 1 accepts no extra fields. That is an intentionally strict policy: even adding a field requires a reviewed contract change for this consumer.
Distinguish uniqueness inside this batch from uniqueness across all accepted batches. This validator enforces only the former. A durable target key or ingestion ledger must handle a replay of a previously accepted batch. Likewise, having at least one record does not prove the producer delivered every expected record.
| Rule | Scope | Failure policy |
|---|---|---|
| Exact field names, version and types | Each record | Reject the batch |
| Amount is 0..100000000 integer cents; USD only | Each record | Reject the batch |
| UTC instant falls inside declared window | Each record | Reject the batch |
| event_id appears once | Current batch | Reject the batch |
| Expected partition/count and prior-run identity | Publication workflow | Separate reconciliation gate |
Validate without silently repairing values
Save the following as contract.py. It accepts bytes, validates the full batch and returns rows only when every check passes. It performs no destination writes. The caller must supply an ordered timezone-aware interval; this separates deterministic event-window tests from the wall clock of a test machine.
The type checks deliberately reject Boolean values where integers are required. In Python, bool is a subclass of int, so isinstance(value, int) alone would accept true as an amount or version. The JSON decoder hooks reject duplicate member names and nonstandard constants rather than keeping an ambiguous last value or accepting NaN.
The timestamp grammar and calendar parsing are separate checks: matching the shape does not make February 30 valid. The returned record retains its original string and integer representations. Nothing strips identifiers, substitutes a missing amount with zero or changes an unsupported currency into USD.
import json
import re
from datetime import datetime, timezone
FIELDS = {"version", "event_id", "occurred_at", "amount_cents", "currency"}
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("duplicate JSON member")
result[key] = value
return result
def reject_constant(value):
raise ValueError("nonstandard JSON constant")
def validate_batch(raw, *, start, end):
"""Small UTF-8 JSON Lines batch; no writes and no value coercion."""
if start.utcoffset() is None or end.utcoffset() is None or start >= end:
raise ValueError("supply an ordered timezone-aware batch window")
if not isinstance(raw, bytes) or not raw or len(raw) > 65536:
raise ValueError("batch must contain 1..65536 bytes")
lines = raw.decode("utf-8").splitlines()
if not 1 <= len(lines) <= 100:
raise ValueError("batch must contain 1..100 records")
accepted, seen = [], set()
for number, line in enumerate(lines, start=1):
try:
row = json.loads(line, object_pairs_hook=unique_object,
parse_constant=reject_constant)
except (ValueError, RecursionError):
raise ValueError(f"line {number}: invalid JSON") from None
if type(row) is not dict or set(row) != FIELDS:
raise ValueError(f"line {number}: unexpected fields")
if type(row["version"]) is not int or row["version"] != 1:
raise ValueError(f"line {number}: unsupported version")
identity = row["event_id"]
if not isinstance(identity, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,40}", identity):
raise ValueError(f"line {number}: invalid event_id")
if identity in seen:
raise ValueError(f"line {number}: duplicate event_id")
amount = row["amount_cents"]
if type(amount) is not int or not 0 <= amount <= 100000000:
raise ValueError(f"line {number}: invalid amount_cents")
if row["currency"] != "USD":
raise ValueError(f"line {number}: unsupported currency")
timestamp = row["occurred_at"]
if not isinstance(timestamp, str) or not re.fullmatch(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", timestamp):
raise ValueError(f"line {number}: invalid timestamp format")
try:
instant = datetime.fromisoformat(timestamp[:-1] + "+00:00")
except ValueError:
raise ValueError(f"line {number}: invalid calendar time") from None
if not start <= instant < end:
raise ValueError(f"line {number}: outside batch window")
seen.add(identity)
accepted.append(row)
return accepted
Keep one accepted case and several deliberate failures
Save this second block as fixture.py alongside contract.py and run python3 fixture.py without optimization flags. The expected output is “Contract fixture passed.” The first check proves an event at the start boundary is accepted. The second proves repeating its identifier within the same batch is rejected.
The batch window is fixed in the example; its October date is fixture data, not a claim about current source freshness. A production scheduler derives the intended window from its run identity and business calendar, then passes it explicitly. Replaying a historical window should not require pretending that its events happened today.
We ran this exact fixture and additional local boundary and rejection cases. The checks cover the local contract only. They do not demonstrate an AWS deployment, a distributed uniqueness guarantee, source completeness or production performance.
import json
from datetime import datetime, timezone
from contract import validate_batch
start = datetime(2026, 10, 1, tzinfo=timezone.utc)
end = datetime(2026, 10, 2, tzinfo=timezone.utc)
row = {"version": 1, "event_id": "evt_001",
"occurred_at": "2026-10-01T00:00:00Z",
"amount_cents": 1250, "currency": "USD"}
raw = (json.dumps(row) + "\n").encode("utf-8")
assert validate_batch(raw, start=start, end=end) == [row]
try:
validate_batch(raw + raw, start=start, end=end)
except ValueError as error:
assert "duplicate event_id" in str(error)
else:
raise AssertionError("duplicate batch accepted")
print("Contract fixture passed")
Use AWS mechanisms for the checks they actually provide
AWS Glue Schema Registry manages versioned schemas for supported streaming integrations. It helps producers and consumers exchange data using an agreed structure and compatibility policy. That is useful governance, but schema compatibility alone cannot establish that an amount has the intended business unit or that a daily export is complete.
AWS Glue Data Quality evaluates data-quality rules using DQDL. Its documented entry points include the Data Catalog and ETL jobs, with different capabilities. Decide whether a rule runs before publication, against a cataloged dataset or in both places. Do not assume a result available in one entry point is automatically available in the other.
The small DQDL illustration below checks completeness and uniqueness of event_id and a nonempty dataset. It is a starting subset, not a translation of every Python rule. It does not enforce the declared time interval, amount type, exact JSON members or cross-run uniqueness. Review each rule’s documented semantics and test it in the actual Glue execution path before deployment.
Rules = [
IsComplete "event_id",
IsUnique "event_id",
RowCount > 0
]Source: AWS Glue Data Quality ↗
Separate row validity from dataset completeness
Imagine every received record passes, but the producer delivers only one of ten expected objects. A row validator reports no errors because the missing objects are not present to inspect. Add a dataset-level gate using independently known expectations, such as a producer manifest, agreed partition list or reconciled source count. Define who creates that evidence and when it becomes final.
Freshness also needs a precise clock. Event time measures when the business event occurred; ingestion time measures when you received it; publication time measures when the consumer could use it. A “within 24 hours” rule is incomplete until it names the clock, timezone, evaluation point and late-arrival policy.
The local validator uses event time and a supplied interval. It does not check when the file arrived. A production workflow may accept a valid historical backfill while separately flagging a missed publication deadline. Keeping those outcomes separate avoids either rejecting legitimate recovery or hiding an operational delay.
Choose a failure path that preserves the evidence
This example rejects the whole batch when any record fails. That choice fits a consumer that requires a complete daily unit. A different workflow may quarantine invalid records and publish the rest, but then the consumer must understand the missing-data policy. Never silently switch between those modes to make a scheduled job green.
Retain the original source identity, contract version, intended window and sanitized failure reason. Use access-controlled quarantine storage when retaining payloads. A line number and reason code are often enough for ordinary monitoring; full source records can contain sensitive data and should not be copied into general logs.
Write into a staging target and expose accepted data through a deliberate publication step. Passing validation should authorize that step, not imply that it already happened. If a failure occurs after staging, the next run needs to distinguish a new batch, a retry and a repaired replacement before writing again.
Design reruns before enabling a recurring trigger
Assign a stable identity to the source batch and intended window. An execution ID identifies a run attempt, so it should not be the only deduplication key. Record the accepted source identity and contract version in durable state, and make target writes idempotent according to the storage system’s actual guarantees.
If a producer corrects a previous batch, decide whether the correction replaces a partition, appends compensating events or creates a new version for consumers. An unchanged filename is not sufficient evidence that its content is unchanged. Conversely, a new filename does not prove its events are new.
Test a failure immediately before publication and another immediately afterward. A recovery procedure should explain whether the previous output remains visible, how an operator identifies committed work and how the retry avoids double counting. A scheduler retry option cannot supply those business rules.
Review changes from the consumer’s perspective
A producer may consider a new optional field harmless while a strict consumer rejects extra properties. A type-compatible change can still alter meaning, such as switching cents to dollars or changing the uniqueness scope from global to per customer. Document semantics alongside the machine-readable schema.
Give the contract an owner, change process and effective version. Keep accepted and rejected fixtures with it. Before rollout, exercise both old and new producer examples against the relevant consumers, and agree on an overlap or migration plan. Compatibility settings are evidence to consider, not approval to skip consumer testing.
Keep validation failures and source delays visible after scheduling begins. An alert should identify the failed rule, affected batch/window, downstream publication status and responsible owner. Otherwise the same problem will reappear as a vague “pipeline failed” incident with no clear recovery path.
A concrete release gate for the pipeline
Before enabling the schedule, demonstrate a valid batch, a malformed record, a boundary timestamp, a duplicate event, an incomplete source delivery and a replay after a partial failure. The local fixture supplies the first pieces; the manifest, destination and recovery tests belong to the actual pipeline implementation.
The useful outcome is a shared, testable promise: what data is accepted, what becomes visible to consumers, and what happens when either step fails. Use the related CSV guide for byte-to-record problems and the webhook guide for authenticated event delivery. Neither transport parsing nor message authentication replaces the data contract.
Your next steps
- State units, time-window semantics and uniqueness scope before selecting rules.
- Reject or quarantine deliberately; preserve source identity and publish only through a defined gate.
- Test completeness and reruns in the real pipeline, beyond the local row validator.
Sources & official resources
Linked resources checked on 2026-10-25. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →