skip to content

Would you make Pydantic 2's strict mode the team default for inbound models, and what would that policy cost your services?

level: principalimportance: should knowfreq 24%

answer

  1. silent conversion versus loud refusal
  2. text-native sources
  3. a strict base model
  4. measure before you flip

basics

~20 s

Pydantic 2's strict mode suits JSON contracts between services you own, validated with model_validate_json; text-native inputs usually need lax mode. Most teams land on strict risky fields plus a strict base model, rolled out after measuring rejections.

solid answer

~40 s

Lax mode hides producer bugs: `'off'` becomes `False`, `True` becomes `1` in an `int`, a numeric string passes for a count. Strict mode surfaces them, but it refuses `'5'` for an `int` everywhere, which breaks text-native inputs such as query strings, headers, form fields and CSV, and in Python mode it refuses date and Decimal strings from `json.loads`. I would not flip it globally. I would put `StrictBool`, `StrictInt` or `Field(strict=True)` on the fields where conversion is dangerous, use a shared base model with `ConfigDict(strict=True)` for JSON contracts between our own services, validated through `model_validate_json`, and keep lax models at text-native edges. Before flipping a model, I would run a shadow `model_validate(data, strict=True)` beside the lax call and count failures by error type.

go deeper

for a junior

Recall that strict mode refuses conversions such as '5' to 5, and that it can be set per model, per field or per call.

for a middle

Explain which inputs strict mode breaks, text-native sources and Python-mode dates, and which lax conversions hide real bugs.

for a senior

Show the rollout mechanics: shadow strict validation by error type, Field(strict=False) exceptions, and model_validate_json so JSON rules apply.

for a principal

Own the tradeoff per input source: strict contracts where you control both ends, lax at text-native edges, and a review rule that new models inherit the base.

## What the policy decides Pydantic 2 converts input by default (**lax mode**) and refuses conversions only where **strict mode** is switched on, by model, field or call. A team default decides which failure you prefer: a silently converted value that may be wrong, or a rejected request that may have been fine. There is no single right answer; there is a right answer per input source. ## The case for strict by default - **Producer bugs surface.** In lax mode `'off'` becomes `False`, `True` becomes `1` in an `int` field, and a numeric string passes for a count. In a payment feed each of those can be a bug in the sender that lax mode turns into plausible data. - **Contracts become literal.** A strict model documents exactly what goes over the wire, and a JSON Schema consumer sees the same thing the validator enforces. - **Unions get more predictable.** With fewer lax matches, smart-mode union selection has fewer candidates to choose between. ## The cost - **Text-native sources break.** Query strings, headers, form fields, CSV rows and environment variables are strings by nature. Strict mode refuses `'5'` for an `int`, so those models need lax mode or explicit relaxation. (How a web framework binds such parameters, and how settings are read, are covered in their own lessons.) - **Python-mode surprises.** Strict mode in Python mode wants instances, so a dict from `json.loads` with ISO date or `Decimal` strings fails, while the same document through `model_validate_json` passes. Teams that parse JSON themselves get errors they did not expect. - **Nested models are not covered.** Configuration does not propagate into nested models, so a strict outer model with lax nested models gives a false sense of safety unless every model inherits the strict base. - **Existing callers fail.** Inputs that were quietly converted for years start returning errors on the day you flip the switch. ## Middle paths | Option | Protects | Costs | |---|---|---| | Lax everywhere | nothing beyond type shape | hides producer bugs | | Strict on risky fields only | flags, counts, money | per-field discipline in review | | Strict base model for owned JSON contracts | service-to-service payloads | must use `model_validate_json`; nested models must inherit | | Strict everywhere | everything | breaks text-native inputs; needs many `Field(strict=False)` exceptions | ## A rollout plan 1. **Measure first.** Beside the normal lax validation, call `model_validate(data, strict=True)` in a `try`, discard the result, and count `ValidationError` entries by error type and field. That shows exactly which producers send what. 2. **Fix or document.** For each rejection, either get the producer fixed or mark the field `Field(strict=False)` with a comment saying why. 3. **Introduce a strict base model.** Give inbound JSON contract models a common base with `model_config = ConfigDict(strict=True)`; subclasses merge its config, and nested models inherit it too if they derive from the same base. 4. **Validate JSON as JSON.** Route bodies through `model_validate_json` so strict JSON rules apply, with dates, UUIDs and Decimals accepted as strings. 5. **Flip per model** once its shadow failures reach zero, watching error rates after each deploy. ## Signals that the policy is working A strictness policy is only as good as what it catches and what it costs. Useful signals to track after rollout: - **Rejections by producer and error type**, so a spike in `int_type` from one sender is a conversation with that team, not a mystery. - **The count of `Field(strict=False)` exceptions**, which should shrink as producers are fixed rather than grow as a way around the rule. - **Support tickets from callers** whose previously accepted requests now fail, which measures the cost of strictness falling on others. - **Incidents traced to converted data**, the bug class strict mode exists to prevent. ## Where I would land For a team owning both ends of its service-to-service JSON, I would adopt the strict base model for those contracts, strict types on dangerous fields everywhere, and lax models at text-native edges. I would revisit the policy when a new producer joins, because the cost of strictness falls on whoever sends the data. Adjacent defaults, such as forbidding unknown keys, are a separate decision made on the same evidence.

  • Why does a strict Pydantic 2 base model not protect a nested line-item model?
    Configuration is not propagated into fields typed as other models; each model is its own configuration boundary. A nested model inherits strictness only if it also subclasses the strict base or sets `ConfigDict(strict=True)` itself, so the policy has to say every inbound model derives from the base.
  • What does a shadow strict check in Pydantic 2 look like, and what does it cost?
    After the normal lax validation, call `model_validate(data, strict=True)` inside a `try`, ignore the result, and record each error's `type` and `loc`. It validates every input twice, so it adds CPU per request; sampling a fraction of traffic keeps the cost bounded while still showing which producers would break.

  • Strict mode should be on everywhere because it has no downside.
  • Strict mode breaks every JSON date field, so it is unusable for APIs.
  • Setting strict on the outer request model covers every nested model.
  • You cannot measure strict-mode impact without enabling it in production.
  • Lax mode accepts any garbage, so it is never the right choice.