How to Build a Data Validation Pipeline
Parse with schemas before logic, collect per-field errors with paths, quarantine bad rows with reasons, and replay from the dead-letter store.
On this page
Introduction
Bad data entering a system is cheap to reject and expensive to evict. A malformed record that slips through the boundary propagates into derived tables, caches, and downstream consumers, and the eventual discovery, a crash in a report, a negative price in an invoice, a null where a name should be, triggers a forensic exercise to trace which ingest let it in and a repair job to unpick everything it touched. A validation pipeline is the boundary made deliberate: every inbound record is parsed against an explicit schema before any business logic sees it, failures are collected completely rather than one at a time, rejected records are quarantined with their reasons and their raw payloads, and fixes flow back through replay rather than ad-hoc database surgery. This tutorial builds that pipeline with schema-first parsing, per-field error collection with paths, a dead-letter store with context, and the metrics that make validation quality visible, using Zod in TypeScript and Pydantic in Python as the two canonical shapes.
Parse, do not validate
The strongest pattern in data validation is borrowed from type theory: parse, don’t validate. Validation checks a value and returns a boolean, leaving the caller to trust that the check covered everything and that the value has not changed since. Parsing converts untrusted input into a typed output in one step: the parse either succeeds and hands back a value whose type carries the guarantees, or fails and hands back errors. After parsing, no downstream code needs defensive checks, because the type is the proof.
import { z } from 'zod';
const OrderLine = z.object({
sku: z.string().regex(/^[A-Z0-9-]{4,24}$/),
quantity: z.number().int().positive().max(10_000),
unitPriceCents: z.number().int().nonnegative(),
});
const InboundOrder = z.object({
externalId: z.string().min(1).max(64),
lines: z.array(OrderLine).min(1).max(500),
currency: z.enum(['USD', 'EUR', 'JPY']),
});
export type InboundOrder = z.infer<typeof InboundOrder>;
const result = InboundOrder.safeParse(raw);
if (!result.success) {
return quarantine(raw, result.error.issues.map(toRejection));
}
await processOrder(result.data);
The type dependency runs one way: business logic imports the parsed type, never the raw shape, and the compiler enforces that nothing downstream touches unvalidated fields. Pydantic offers the same shape in Python, model_validate returning a typed model or a ValidationError, and the discipline is identical: untrusted data crosses exactly one line, the parse, and everything after it is typed.
Collect every error, not the first
A record with four bad fields that reports one error at a time costs four ingest cycles and four fix-and-retry rounds with the source team. Error collection is a throughput feature: the validator gathers all issues in one pass, each with a path to the offending field, and the rejection report is complete on the first attempt. Both canonical libraries do this: Zod’s error.issues array carries path, code, and message per issue; Pydantic’s ValidationError exposes errors with loc tuples. The pipeline’s job is to preserve that structure into the quarantine, path and code as machine-readable fields, message as the human-readable rendering, so downstream tooling can aggregate by field and code, and the answer to which field is most often wrong is a query.
function toRejection(issue: z.ZodIssue) {
return {
path: issue.path.join('.'),
code: issue.code,
message: issue.message,
};
}
The aggregation pays off immediately in operations: a rejection histogram by path and code is the data-quality dashboard for the source system, and a new code appearing in volume is an upstream schema change announcing itself before anyone reads an email. Custom error codes, attached through refinements and transforms in the schema, keep the vocabulary stable across schema versions so the dashboard’s history stays comparable.
Quarantine with full context
Rejected records are data too: they are the evidence of what the source actually sent, the input to every future fix, and, when the validation rule turns out to be wrong, the proof that the pipeline rejected good data. The dead-letter store deserves a real design: the raw payload, unmodified, because re-parsing after a schema fix requires the original bytes; the rejection reasons with paths and codes; the metadata, source, batch, arrival time, and the schema version that rejected it; and a status field supporting the replay lifecycle, pending, replayed, discarded-with-reason.
CREATE TABLE quarantine (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
source text NOT NULL,
raw_payload jsonb NOT NULL,
rejections jsonb NOT NULL,
schema_version text NOT NULL,
arrived_at timestamptz NOT NULL DEFAULT now(),
status text NOT NULL DEFAULT 'pending'
);
Never drop silently, the rule that separates a validation pipeline from data loss with extra steps: a rejection without a record is indistinguishable from a bug that lost the record, and the incident review cannot tell them apart. Sizing and retention follow the same discipline as any operational store, quarantine volume is data-quality telemetry, and a sudden fill is a source incident with evidence attached. Access controls belong here too, because quarantined records are exactly the untrusted inputs, and rendering them in admin tooling must escape and sandbox as rigorously as the original boundary did.
Replay as the fix mechanism
Every validation failure is one of two defects: the data is wrong, or the rule is wrong. Both fixes end the same way, replay: the corrected records, or the unchanged records under a corrected schema, flow through the exact same validated path, never through a side door that inserts directly. Replay through the main path is what keeps the invariant true, everything in the store passed the current schema, and it is what makes rule changes safe to deploy, the schema fix plus a replay of pending quarantine is a single operation, not a migration script hand-editing accepted data. The mechanics are a job that reads pending records for a source, re-parses with the current schema, routes successes to processing and leaves failures pending with refreshed rejection reasons, and records the schema version that produced each outcome, so the quarantine’s history shows which rule set rejected what. Backpressure and idempotency apply as in any re-ingest: replayed records must upsert by their identity key, and the replay job must be resumable, because the fix that empties a large quarantine backlog is, by definition, a bulk operation.
for await (const row of pending(source)) {
const result = InboundOrder.safeParse(row.raw_payload);
if (result.success) {
await processOrder(result.data); // idempotent by externalId
await markReplayed(row.id, SCHEMA_VERSION);
} else {
await refreshRejections(row.id, result.error.issues, SCHEMA_VERSION);
}
}
Measure validation as a quality signal
The pipeline exports four numbers that together describe boundary health. Rejection rate per source per window: the headline data-quality metric, expected to be low and stable, and alerting on shifts rather than absolutes. Rejection histogram by path and code: which fields fail and how, the dashboard that makes source teams self-sufficient, they see their own top error before you email them. Quarantine age: pending records growing old are unfixed defects accumulating, and age by source is the accountability metric for the fix loop. False-rejection rate: the rate at which records rejected by an older schema are accepted by the current one on replay, which measures how often the rules, not the data, were wrong, and justifies schema-coverage improvements. These four make the boundary auditable: at any moment, the fraction rejected, the reasons, the backlog, and the rule-error rate are queries, and a data-quality incident starts with numbers instead of a forensic trace.
Test the boundary like an adversary
Validation code fails on inputs nobody imagined, so the test suite’s job is to imagine them systematically. Golden rejections: for each error code, a minimal record that triggers exactly it, asserting the path and code, which locks the vocabulary. Malformed structures, not just malformed values: a JSON string where an object belongs, an array of arrays, a number as a string, nulls everywhere, deeply nested garbage, because parsers fail differently on structure than on values. Boundary values: every min and max in the schema gets both sides tested, and unicode, empty strings, and enormous numbers probe the edges the schema author did not consider. Round-trip: valid records parse, serialize, and re-parse to equal values, catching transformations that silently corrupt. Adversarial replay: run production-shaped bad records from the quarantine backlog through every schema change in CI, asserting that known-bad stays rejected and known-good, the false rejections, now pass, which is the regression suite for the rules themselves.
class TestAdversarial:
def test_structure_not_value(self):
with pytest.raises(ValidationError) as e:
Order.model_validate({'lines': 'many'})
assert e.value.errors()[0]['loc'] == ('lines',)
Common pitfalls
- Check-then-trust validation. Boolean checks leave the raw value in circulation; parse to a typed value or the guarantees evaporate.
- First-error-only reporting. Four bad fields cost four round trips with the source; collect everything with paths.
- Silent drops. A rejection without a record is indistinguishable from data loss in the incident review.
- Side-door fixes. Hand-edited accepted rows bypass the invariant; everything enters through the validated path, including replay.
- Schema as the only validator. The database backstops structure; cross-field and external rules live in the parse layer.
- Unversioned rejections. Without the schema version recorded, rule changes make quarantine history unreadable.
Conclusion
A validation pipeline is the boundary expressed as code: parse every inbound record against an explicit schema and hand business logic a typed value it never needs to defensively check. Collect every error with paths and stable codes so one bad record produces one complete report, and aggregate rejections into the data-quality dashboard that makes sources self-sufficient. Quarantine rejects with raw payloads, reasons, and schema versions, never dropping silently, and fix both classes of defect, wrong data and wrong rules, through replay into the same validated path, which keeps the store’s invariant true and rule changes safe. Measure rejection rate, histograms, quarantine age, and false-rejection rate as boundary telemetry, and test the schema adversarially, malformed structures, boundary values, and replayed production rejects, because the inputs nobody imagined are exactly the ones the pipeline exists to catch.
Sources: Zod documentation, Pydantic documentation, MDN: 422 Unprocessable Content.
FAQ
- Validation in the schema or in the application?
- Both, at different layers. The schema enforces structural truth the database can guarantee, types, nullability, uniqueness. The application enforces business truth the database cannot express, cross-field rules, external consistency. Schema is the backstop, not the whole policy.
- Should invalid records fail the whole batch?
- Usually no. Quarantine the invalid rows, process the valid ones, and report the rejects with reasons. Whole-batch failure is for structural issues that affect every row, like a schema change in the source.
- How much validation is enough?
- Enough that downstream never needs defensive checks: every consumer can trust types, ranges, and required fields. If consumers still guard against bad data, the boundary is leaking and the validation layer needs the rule they are hand-rolling.
Report a problem with this articleOpens a pre-filled issue on GitHub.