Tutorial

How to Write Pydantic Validators for Custom Rules

Add field and model validators in Pydantic v2 for rules the types cannot express so validation lives in the schema not the handler.

On this page

  1. Introduction
  2. Define the contract as a schema
  3. Validate at the boundary
  4. Detect drift between producer and consumer
  5. Handle migration without breaking
  6. Reconcile on a schedule
  7. Test the invariant end to end
  8. Common pitfalls
  9. Conclusion

Introduction

How to Write Pydantic Validators for Custom Rules is where write decides whether the rest of the design holds together. When write is misconfigured, pydantic degrades silently and the failure surfaces far downstream, often as a timeout in a service that looked unrelated. The fix is to make the decision explicit at the boundary, before validators enters the hot path, and to emit a metric the moment the decision changes so the operator can see it rather than infer it.

The pitfall in the overall approach is assuming write is enough. In practice, pydantic interacts with validators in ways that only surface under concurrent failure: a timeout that fires during a retry that fires during a partial deployment. Test the combination, not the pieces in isolation, because the pieces pass and the combination fails. A chaos test that injects the failure you fear is the cheapest way to find the seam before production does.

Define the contract as a schema

Define the contract as a schema is where write decides whether the rest of the design holds together. When write is misconfigured, pydantic degrades silently and the failure surfaces far downstream, often as a timeout in a service that looked unrelated. The fix is to make the decision explicit at the boundary, before validators enters the hot path, and to emit a metric the moment the decision changes so the operator can see it rather than infer it.

Measure write before optimizing Define the contract as a schema. The metric that matters is the one the user feels — a tail latency, an error rate, a time to first byte — not the one that is easy to graph. A pydantic that looks healthy on the average can hide a validators that ruins the experience for the slowest ten percent. Instrument the tail, alert on the tail, and optimize the tail, because the average lies and the tail tells the truth about custom.

import { z } from 'zod';

const writeContract = z.object({
  id: z.string().uuid(),
  pydantic: z.string().min(1),
  updatedAt: z.string().datetime(),
});

function checkwrite(raw: unknown): string[] {
  const r = writeContract.safeParse(raw);
  return r.success ? [] : r.error.issues.map(i => `${i.path.join('.')}: ${i.message}`);
}
test('write reports every contract violation', () => {
  const errs = checkwrite({ id: 'bad', pydantic: '', updatedAt: 'no' });
  expect(errs.length).toBeGreaterThanOrEqual(2);
});

The test pins the behavior. A how to write pydantic validators for custom rules that passes this test degrades on purpose instead of by accident.

Validate at the boundary

Most teams reach for write when the real lever is pydantic. The difference is where the cost lands: write pushes the cost onto every call, while pydantic pays once at the boundary and lets the fast path run unguarded. For Validate at the boundary, the second shape wins because the check is amortized and the hot loop stays tight. Reaching for the first shape is the reflex; resisting it is the engineering.

Validate at the boundary fails when write and pydantic disagree about the contract. The caller sends a shape the callee no longer accepts, and the error message points at a field that exists in one version and not the other. Pin the contract with a schema, version the schema, and refuse the deploy that breaks the consumers. A broken validators is a production incident; a refused deploy is a conversation, and the conversation is cheaper.

Detect drift between producer and consumer

Detect drift between producer and consumer pays off when write is the constraint. Before that, it is overhead that makes the code harder to read and the path harder to follow. The discipline is to add it when the metric says pydantic is the bottleneck, and to remove it when the metric says it no longer is. Code that carries validators for a problem it no longer has is debt, and debt compounds until nobody remembers why the guard exists.

Detect drift between producer and consumer is a boundary, and boundaries are where untrusted data becomes trusted. The moment write crosses the boundary, every downstream branch assumes it is valid and stops checking. That is the point, and it is also the risk: if the boundary check is wrong, the wrongness propagates everywhere at once. Test the boundary with the inputs that almost pass, because those are the ones that find the off-by-one in the check that everything else depends on.

Handle migration without breaking

Keep Handle migration without breaking small enough to audit. A write that spans three files and twenty branches is a write nobody understands, and the next change breaks it in a way the tests do not catch because the tests were written for the old shape. Extract the decision into one function, test that function exhaustively, and let the callers stay thin. The complexity has to live somewhere; put it where it is visible and tested, not where it is implicit and assumed.

The order of operations in Handle migration without breaking matters more than the operations themselves. Checking write before pydantic is cheap and rejects early; checking after is expensive and does work that is about to be thrown away. Put the cheap, rejecting checks first, the expensive, transforming checks last, and never do I/O before the cheap checks pass. The order is the performance, and it is the correctness, because a check that runs after the mutation cannot reject the mutation.

Reconcile on a schedule

Do not conflate Reconcile on a schedule with pydantic. They look similar from the outside but the failure modes differ: write fails fast and the caller knows, while pydantic fails slow and the caller guesses. Choose the one whose failure mode your system can absorb, and document the choice at the call site. A reader who sees validators without knowing which failure mode it carries will treat it as the wrong one, and the bug will surface in the path that was not reviewed.

Reconcile on a schedule is not a feature you add once. It is a property you maintain as the system grows. The write that works today breaks when pydantic changes its shape, when validators adds a new code path, when the traffic doubles and the assumption of low load no longer holds. Pin the property with a test that runs on every change, and when the test fails, treat it as the system telling you the assumption expired, not as a flaky test to be silenced.

Test the invariant end to end

Test the invariant end to end composes only if the pieces agree on the failure contract. If write throws and pydantic returns null, the caller writes two branches and misses a third. Define one error shape at the module boundary, convert everything to it, and let the callers write one branch. The consistency is worth more than the local fidelity, because the caller’s code is where the bugs live and the bugs live in the missed branch.

Test the invariant end to end has a half-life. The write that was correct when the service ran on one box is wrong when it runs on fifty, and the pydantic that was safe at one hundred requests per second is dangerous at ten thousand. Review the assumptions on a schedule, not just when they break, because breaking is the expensive way to learn the assumption expired. A quarterly read of the load-bearing validators is cheaper than the incident that teaches the same lesson.

Common pitfalls

The test for the common pitfalls is the one most teams skip. It is the test that drives write to the failing condition and asserts the system degrades gracefully rather than crashing. Write it with a fake clock so the time-based logic is deterministic, a stubbed pydantic so the failure is injected not waited for, and an assertion on the user-visible outcome not the internal state. A test that passes by timing out is not a test; it is a hope.

  • Skipping the boundary check so write enters unvalidated.
  • Assuming pydantic is fast without measuring the tail latency.
  • Letting validators fail silently instead of failing loudly with a metric.
  • Testing only the happy path so the custom failure surfaces in production.
  • Sharing state across requests so one bad write poisons the next.

Conclusion

the conclusion is a boundary, and boundaries are where untrusted data becomes trusted. The moment write crosses the boundary, every downstream branch assumes it is valid and stops checking. That is the point, and it is also the risk: if the boundary check is wrong, the wrongness propagates everywhere at once. Test the boundary with the inputs that almost pass, because those are the ones that find the off-by-one in the check that everything else depends on.

Self-check: write a test that drives write to the failing condition and assert the system degrades gracefully. Then how to write pydantic validators for custom rules is a property you maintain, not a feature you hope for.

Sources: Zod, Pydantic.

FAQ

Why does write fail under pydantic?
It fails because pydantic violates an assumption that write was designed under. The fix is to make the assumption explicit, test it, and degrade gracefully when it breaks rather than crashing.
What is the right threshold for validators?
Start from observed data, not a guess. Measure the current distribution, pick the threshold that rejects the bad validators without tripping on the normal, and tune from there as traffic shifts.
Should custom be sync or async?
Async if custom touches I/O or can block, sync if it is pure computation under a microsecond. The choice is about not holding the event loop, not about fashion.

Related Examples