How does Pydantic v2 validation work under the hood?

Pydantic v2 splits validation into two layers. The Python layer, which is the part you write, holds your BaseModel classes, type hints, Field constraints and validators. The engine, pydantic-core, is written in Rust. When a model class is created, Pydantic walks its annotations and builds a core schema: a tree of plain data that describes every field, type, constraint and validator. pydantic-core compiles that schema into a validator object and a serializer object, which are stored on the class. Each later call to validate data runs that compiled tree in Rust. It re-enters Python only when it reaches a custom validator or a type it cannot handle natively.

Two costs, paid at different times

  • Schema build cost is paid once: at import, when the class body runs, or when you create a TypeAdapter. For large or deeply nested models it is noticeable in startup time. It is wasted if you rebuild adapters inside request handlers.
  • Per-call validation cost is paid on every request. Tuning this cost improves throughput.

Where FastAPI validates

On the way in, FastAPI validates the request body and the path, query, header and cookie parameters against the types you declare. On the way out, if you set a response_model or a return annotation, FastAPI validates your return value against that model and then serializes it to JSON.

That outbound step is easy to overlook. Your handler may already hold fully validated model instances, and FastAPI can still check them again before sending the response. On endpoints that return large lists, this second pass can cost as much as validating the input.

 BUILD TIME: paid once (import, class creation, TypeAdapter)
 +-----------------------+    +-------------+    +------------------------+
 | Python layer          |    | core schema |    | pydantic-core (Rust)   |
 | BaseModel, hints,     |--->| tree of     |--->| compiled validator +   |
 | Field, validators     |    | plain data  |    | serializer on class    |
 +-----------------------+    +-------------+    +------------------------+
                                                             |
 REQUEST TIME: paid on every call                            | reused
                                                             v
 +--------+   +----------------------+   +---------+   +-----------------+
 | HTTP   |-->| inbound validation   |-->| handler |-->| response_model  |
 | request|   | body, path, query,   |   +---------+   | validation      |
 +--------+   | header, cookie       |                 | (often missed)  |
              +----------------------+                 +-----------------+
                                                                |
                                                                v
                                         +---------+   +-----------------+
                                         | HTTP    |<--| serialize to    |
                                         | response|   | JSON            |
                                         +---------+   +-----------------+

 Rust re-enters Python only for custom validators or unsupported types.

Pydantic v2 compiles each model into a Rust validator and serializer once at build time, and FastAPI runs them on every request for inbound parameters and again for response_model validation and serialization.

Who should tune Pydantic v2 performance, and when is it worth it?

That double validation is a real cost, but whether it matters depends entirely on what else the request is doing. Most of this article is aimed at platform and backend engineers who run FastAPI services where validation actually appears on the hot path. Typical examples include ingestion endpoints that accept large JSON bodies, internal APIs that return thousands of nested objects per call, and high-throughput services where small per-request savings add up across many workers.

For a typical CRUD endpoint, validation is rarely what makes it slow. A request that waits on a database query, calls another service over the network, and passes through authentication, logging and tracing middleware spends most of its time in those steps. Making validation twice as fast does little for that endpoint's latency if validation was only a small slice to begin with.

Profile first

The rule is simple: measure before you change models. Run a profiler against realistic traffic and realistic payload sizes, then check what share of request time goes to Pydantic and serialization. If that share is small, rewriting models, adding strict mode or restructuring unions spends engineering time and makes the code harder to read, with no gain users will notice.

Anti-patterns are different. Examples include parsing JSON into a dict and then validating it, rebuilding validators on every request, and validating the same data twice. These are cheap to fix and rarely make code worse. Fix them on sight, and leave the deeper tuning for when profiling shows validation is actually the bottleneck.

Should you use model_validate or model_validate_json, and how does TypeAdapter fit in?

When you hold raw JSON as str or bytes, call model_validate_json instead of json.loads followed by model_validate. The JSON-first path parses and validates in a single pass inside the Rust core, so it never builds an intermediate Python dict that is used once and then discarded. That saves allocations and garbage-collector work, and the savings grow with payload size.

For request bodies declared as Pydantic models, FastAPI handles parsing and validation for you. The internal path differs between versions, so do not re-parse the body in your handler. Most of the gains are in code FastAPI never sees:

  • Queue consumers that receive message bodies as bytes
  • Cache reads from Redis or similar stores that return serialized JSON
  • Outbound HTTP clients, where response.json() followed by validation does the parsing twice. Pass the response bytes straight to the JSON validator instead.

For types that are not a BaseModel, such as list[Item] or Cat | Dog, use TypeAdapter. It exposes the same validate_python and validate_json methods. Build adapters once at module level. Constructing TypeAdapter(list[Item]) inside a request handler rebuilds the core schema and validator on every call, and that build usually costs far more than validating a typical payload. Profilers tend to file this cost under schema generation, so it is easy to miss.

The trade-off is that module-level adapters and large model graphs move the build cost to import time. On long-running servers you pay it once. On serverless platforms and autoscaled containers, it adds to every cold start, so measure startup time as well as steady-state request latency.

from typing import Annotated, Literal, Union

from pydantic import BaseModel, Field, TypeAdapter


class Item(BaseModel):
    id: int
    name: str


class Cat(BaseModel):
    kind: Literal["cat"]
    lives: int


class Dog(BaseModel):
    kind: Literal["dog"]
    good_boy: bool


# Built once at import: schema and validator construction is paid here, not per call.
ItemList = TypeAdapter(list[Item])
Pet = TypeAdapter(Annotated[Union[Cat, Dog], Field(discriminator="kind")])


def handle_queue_message(body: bytes) -> Item:
    # Parse and validate in one pass; no intermediate dict from json.loads.
    return Item.model_validate_json(body)


def read_cached_items(raw: bytes) -> list[Item]:
    # Non-BaseModel type: use the module-level adapter's validate_json.
    return ItemList.validate_json(raw)


def parse_pet(raw: bytes) -> Cat | Dog:
    # The discriminator lets the validator pick Cat or Dog without trying both.
    return Pet.validate_json(raw)


# Anti-pattern: TypeAdapter(list[Item]) inside a handler rebuilds the schema on every call.

Validating raw JSON bytes directly with model_validate_json and with TypeAdapter instances for list[Item] and a discriminated union, built once at module level instead of inside each handler.

How do strict mode, constraints and validator types affect speed?

Coercion is the first cost to look at. In the default lax mode, Pydantic accepts "1" for an int field and "true" for a bool, which means extra conversion attempts on every value. Lax mode can also hide client bugs: a frontend that serialises IDs as strings keeps working, and nobody notices until another consumer is stricter. Strict mode rejects mismatched types outright. You can enable it for a whole model with model_config = ConfigDict(strict=True), or for a single field with Field(strict=True) or Annotated[int, Strict()]. Note that when you validate JSON input, strict mode still accepts the types JSON cannot represent directly, such as datetimes sent as strings.

Validator choice decides where work runs. Constraints declared through Field(gt=0, max_length=64) or Annotated metadata compile into the Rust core schema. Every field_validator or model_validator instead calls back into Python, which adds function-call overhead per value.

Mechanism Where it runs Effect on core validation
Field/Annotated constraints Rust core Built in, cheapest
before validator Python, then core Core still runs on the transformed input
after validator Core, then Python Receives already-typed values
wrap validator Python around core Calls the handler explicitly, most flexible
plain validator Python only Replaces core validation for that field

Use a constraint when it can express the same rule as a validator.

There are trade-offs. Switching to strict mode will break clients that send stringly-typed values, so roll it out behind an API version or a deprecation window. Rules that query a database or span several aggregates are often clearer in the service layer than in a model validator.

from typing import Annotated

from pydantic import BaseModel, ConfigDict, Field, Strict, ValidationError, field_validator


# Per-field strictness: order_id rejects "42", while quantity still coerces.
class OrderLax(BaseModel):
    order_id: Annotated[int, Strict()]
    quantity: int = Field(gt=0, le=1000)  # constraint compiled into the Rust core


# Per-model strictness: no field accepts mismatched types.
class OrderStrict(BaseModel):
    model_config = ConfigDict(strict=True)
    order_id: int
    sku: Annotated[str, Field(min_length=1, max_length=64)]  # stays in the core


# Same rule as the sku constraint, but each value calls back into Python.
class OrderWithValidator(BaseModel):
    sku: str

    @field_validator("sku", mode="after")
    @classmethod
    def check_length(cls, v: str) -> str:
        if not 1 <= len(v) <= 64:
            raise ValueError("sku must be 1-64 characters")
        return v


print(OrderLax(order_id=42, quantity="3"))  # lax field: "3" becomes 3

try:
    OrderStrict(order_id="42", sku="ABC-1")  # stringly-typed ID from a client
except ValidationError as exc:
    print(exc.errors()[0]["type"])  # int_type: strict mode refuses coercion

Strictness set per field with Annotated[int, Strict()] and per model with ConfigDict(strict=True), plus a Field constraint that stays in the Rust core next to an equivalent field_validator that runs in Python.

Why do discriminated unions validate faster than plain unions?

A plain Union[A, B, C] gives the core no hint about which member the input belongs to. In the default "smart" mode, pydantic-core attempts validation against the members, first looking for an exact or strict match and then falling back to lax validation, and keeps the best result. A payload that matches the last member, or nearly matches several, pays for partial validation of every candidate along the way. The cost grows with the number of members and with how deep each one goes before failing. When nothing matches, the error report contains a failure branch for every member, so a client that sent one bad field gets a page of unrelated complaints.

A discriminated union removes the search. Each variant declares a Literal tag such as kind: Literal["card"] or kind: Literal["bank_transfer"], and the union is annotated with Field(discriminator="kind"). The core builds a lookup from tag value to validator, reads kind once, and runs only the matching model. A missing or unknown tag fails immediately with a single error naming the field and the expected values. A bad field inside the chosen variant is reported only against that variant.

In FastAPI you declare the annotated union directly as the request body parameter. The generated OpenAPI schema includes the discriminator mapping, which client generators can use.

The trade-off sits in the wire format. If clients do not already send a stable tag, requiring one is a breaking change. Treat it like any other contract change: version it or accept both shapes during a migration window.

from typing import Annotated, Literal, Union

from fastapi import Body, FastAPI
from pydantic import BaseModel, Field

app = FastAPI()


class CardPayment(BaseModel):
    kind: Literal["card"]  # tag value the core uses for lookup
    card_token: str
    amount_cents: int


class BankTransferPayment(BaseModel):
    kind: Literal["bank_transfer"]
    iban: str
    amount_cents: int


# The core reads `kind` once and runs only the matching validator,
# instead of trying each member of the union in turn.
Payment = Annotated[
    Union[CardPayment, BankTransferPayment],
    Field(discriminator="kind"),
]


@app.post("/payments")
async def create_payment(payment: Annotated[Payment, Body()]) -> dict:
    # Missing or unknown `kind` -> one error naming the tag and allowed values.
    # A bad field inside the chosen variant is reported only for that variant.
    return {"kind": payment.kind, "amount_cents": payment.amount_cents}

A FastAPI endpoint that accepts a tagged union of payment models, where Field(discriminator="kind") lets pydantic-core dispatch directly to the matching variant and report errors only for that variant.

When should you avoid validation with model_construct or skip response checks?

model_construct builds an instance without running validation at all. Field values are assigned as given, defaults are filled in for missing fields, and nothing else happens. That suits data you already validated or wrote yourself, such as rows read back from your own database through a typed query, or objects rehydrated from a cache your service populated.

What you give up is everything validation does:

Concern model_validate model_construct
Type checks Enforced None
Coercion ("42" → 42) Applied Value stored as-is
Constraints and validators Run Skipped
Nested models Built recursively Nested dicts stay dicts
Schema drift detection Fails loudly Passes silently

The last row matters most. When a migration renames a column or a nullable field starts returning None, a validated model fails at the boundary where the change happened. A constructed model accepts the bad value, and the failure appears later, in a serializer, a template or a downstream consumer, far from its cause and much harder to trace.

On the response side, the bigger win is usually serialization. model_dump_json writes JSON directly in the Rust core. Calling model_dump and then passing the dict to json.dumps builds an intermediate Python object graph and encodes it a second time in slower code. If your route already returns pre-serialized bytes in a Response, FastAPI skips its own response-model processing. You lose the response contract check, though, so do this only on hot paths covered by tests.

Computed fields and custom serializers run Python code for every instance on every dump. On large lists that per-item call can cost more than the validation you avoided.

How do you measure Pydantic v2 performance honestly?

Measure in two steps, because each answers a different question.

First, microbenchmark the validation call alone with timeit, using a captured production payload rather than a toy dict. This shows whether a change such as switching to model_validate_json or adding a discriminator actually helps. Then profile a realistic request end to end, under load, with cProfile or a sampling profiler. This shows whether that gain matters next to I/O.

Step Question it answers Common trap
Microbenchmark Is variant B faster than A? Small, flat payloads exaggerate the difference
End-to-end profile Is validation a bottleneck at all? Running on a laptop with no database latency

Illustrative estimate (assumed inputs, not measured): a request takes 40 ms in total. Of that, 28 ms is database time, 8 ms is network and framework overhead, and 4 ms is validation and serialization. Halving validation saves 2 ms, which is 5% of the request. That is worth having, but it is not transformative.

Results depend on payload shape, nesting depth, list sizes and hardware. Defaults and internals also change between Pydantic and FastAPI releases, so re-run the benchmarks against the exact versions you deploy.

Prioritized checklist

  1. Profile first. Skip tuning if validation is under a few percent of latency.
  2. Use model_validate_json and reuse TypeAdapter instances. Both are cheap to adopt.
  3. Add discriminators to large unions.
  4. Move hot-path validators from Python into declarative constraints.
  5. Use model_construct or skip response checks only on tested internal paths. These options have the highest risk.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to pydantic v2 performance, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Consumers learn about a breaking change at review time rather than from production errors.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.