Skip to content

Lesson 5 of 9 · 21m

Validation, Invariants, and Partial Failure

Where validation belongs, how to enforce cross-field invariants, and why batch APIs need explicit atomicity semantics.

Validation looks easy until you ask who owns an invariant. The client validates email syntax, the API validates resource existence, the database enforces uniqueness, and a background worker discovers that discount rules changed after submission. If those layers disagree, the user sees a 500 or worse, silent corruption.

Validate shape early, meaning late

There are two different questions:

  1. Is the payload well-formed? Types, required fields, string lengths, enum membership.
  2. Is the operation valid right now? Resource exists, transition is allowed, quota remains, referenced objects are compatible.
{
  "email": "not-an-email",
  "plan": "enterprise",
  "seats": -2
}

The first layer can reject all three syntactic problems without touching the database. The second must happen inside the same transaction or consistency boundary as the write, because another request can change state after you checked it.

Cross-field invariants belong on the server

Client-side validation is a user experience optimization, not a security boundary. Server code must enforce combinations such as trial_ends_at requiring a trialing status, refund amount not exceeding captured amount, or shipping country being supported for a physical product.

The payment flow is a useful model:

create intent -> confirm -> capture -> webhook confirms final state

Each transition checks current state and rejects impossible moves. A state machine table beats a pile of boolean flags because impossible states are unrepresentable instead of merely discouraged.

Batch endpoints must declare atomicity

Does POST /invoices/bulk-update apply all changes or the valid subset? Both are legitimate; being vague is not.

{
  "atomic": false,
  "operations": [
    {"op": "update", "id": "inv_1", "patch": {"status": "void"}},
    {"op": "update", "id": "inv_2", "patch": {"status": "void"}}
  ]
}

If atomic, use one transaction and return one failure for the whole batch. If non-atomic, return per-item results with stable correlation IDs. Never silently stop halfway and report 200.

Consistency windows are part of the API

A write followed by a read may hit a replica. If your system is eventually consistent, document it and provide handles clients can use: monotonic object versions, read-after-write tokens, or synchronous endpoints where required. Otherwise every mobile client invents its own sleep-and-retry ritual.

GET /invoices/inv_9Zk2
X-Minimum-Version: 41

Returning 409 or 202 with retry guidance is more honest than pretending stale data is current.

Field notes

  • Validate input size before parsing unbounded JSON arrays; memory exhaustion is a validation failure too.
  • Prefer one validation library and schema shared across handlers, but never expose internal schema errors verbatim.
  • If two fields disagree, name both fields in the error when possible.
  • Invariants that cannot fit in a transaction usually need a workflow state, not a comment saying "eventually consistent".

Was this lesson helpful?

Sign in to rate