How does Pydantic v2 validation work under FastAPI?
Pydantic v2 has two layers. The Python package you import defines models, fields and validators. The validation and serialization work runs in pydantic-core, a compiled library written in Rust. When Python defines a model class, Pydantic inspects its annotations and builds a core schema, a tree that describes every field, constraint and validator. It then compiles that schema into a validator and a serializer object that live in the core.
Building the schema is a one-time cost per model or TypeAdapter. It can be noticeable at import or startup for large model graphs, but it does not recur. Validation and serialization are per-call costs. They run every time data passes through, so they are what shows up in request latency.
FastAPI triggers that per-call work at several points on each request:
- Body parsing. FastAPI reads the request bytes, decodes the JSON and validates the result against the body model. This creates model instances or raises a 422 error.
- Parameters. FastAPI also validates query, path and header values against their declared types.
- Response model filtering. If you declare a
response_modelor return type, FastAPI validates or serializes the return value against it. This drops fields the model does not declare. - Encoding. FastAPI converts the filtered data to JSON-compatible values and writes it out as bytes.
The later sections look for redundant work at each of these points. Make those changes through the public API: model_validate, model_validate_json, TypeAdapter, model_dump and model_dump_json. Code that reaches into undocumented pydantic-core objects or schema internals may work today, but those internals can change between releases without notice, which makes every upgrade riskier.
STARTUP: one-time cost per model or TypeAdapter
+----------------+ +-----------------+ +---------------------------+
| Python layer | | core schema | | pydantic-core (Rust) |
| model classes, |--->| tree of fields, |--->| compiled validator |
| fields, | | constraints, | | compiled serializer |
| validators | | validators | +-------------+-------------+
+----------------+ +-----------------+ | reused
PER REQUEST: per-call cost (* = validation/serialization) |
| request bytes |
v |
+--------------------------------+ |
| [1]* Body parsing: JSON decode |<------------------------+
| + validate body model |---> 422 on error |
| [2]* Params: query/path/header |<------------------------+
+--------------------------------+ |
| model instances |
v |
+--------------------------------+ |
| endpoint function (your code) | |
+--------------------------------+ |
| return value |
v |
+--------------------------------+ |
| [3]* response_model filtering |<------------------------+
| drops undeclared fields | |
| [4]* Encoding: JSON -> bytes |<------------------------+
+--------------------------------+
+--> response bytes
Pydantic compiles each model's core schema into a pydantic-core validator and serializer once at startup, and FastAPI reuses them on every request at the four starred points: body parsing, parameter validation, response_model filtering and encoding.
Why do most FastAPI latency wins come from avoiding redundant validation?
Validation cost scales with how many times the same data passes through a validator, more than with how fast any single validator runs. A request body is validated once on the way in, which is unavoidable and usually cheap. The waste tends to appear later. A service layer calls model_validate(obj.model_dump()) to convert between two near-identical models. A repository builds Pydantic objects from rows that a handler then rebuilds. A handler returns an already-validated UserInternal while the route declares response_model=UserPublic. In that last case, FastAPI validates the return value against the declared response model, so data you already trusted gets walked field by field a second time before serialization.
To find these paths, trace one request through a profiler such as py-spy or cProfile and count how often validation entry points appear per request. Matching that count against the number of real trust boundaries (incoming request, external API response, untrusted storage) usually exposes the extra passes quickly.
This is worth doing on high-throughput endpoints and on routes that return large lists or deeply nested payloads, where repeated passes multiply. It is often not worth doing when a request spends most of its time waiting on a database query or a downstream HTTP call. Profile before changing anything. If validation is a small share of wall time, removing it will not change latency in a way users notice.
Structural fixes also cost less engineering time. You can remove a redundant conversion once at a layer boundary, and every route that uses that layer benefits. Micro-tuning individual validators takes repeated effort for smaller gains, and those gains are easy to lose in the next refactor.
from fastapi import FastAPI, Response
from pydantic import BaseModel
app = FastAPI()
class UserInternal(BaseModel):
id: int
email: str
password_hash: str
class UserPublic(BaseModel):
id: int
email: str
def fetch_row(user_id: int) -> dict:
# Stand-in for a DB row; placeholder values only.
return {"id": user_id, "email": "user@example.com", "password_hash": "placeholder-hash"}
# Two validation passes per request:
# 1) the row is validated into UserInternal,
# 2) FastAPI validates the returned UserInternal against response_model=UserPublic.
@app.get("/v1/users/{user_id}", response_model=UserPublic)
def get_user_redundant(user_id: int):
return UserInternal.model_validate(fetch_row(user_id))
# One validation pass per request:
# the row is validated straight into the public shape at the storage boundary.
# Returning a Response means FastAPI skips response_model validation;
# `responses` keeps the schema in the OpenAPI docs.
@app.get("/v2/users/{user_id}", responses={200: {"model": UserPublic}})
def get_user_once(user_id: int) -> Response:
public = UserPublic.model_validate(fetch_row(user_id)) # extra keys are ignored by default
return Response(content=public.model_dump_json(), media_type="application/json")
# To confirm the difference, profile a running server under load, e.g.:
# py-spy record -o profile.svg -- uvicorn app:app
# then compare how often validation frames appear per request on /v1 vs /v2.
The /v1 route validates the same user data twice, once into UserInternal and again by FastAPI against response_model, while the /v2 route validates the row once into the public model and returns it as an already-serialized Response.
When should you use model_validate_json and TypeAdapter instead of model_validate?
When a request body comes through FastAPI's normal parameter handling, the framework decides how to parse it. Queue consumers, cache reads and webhook replays skip that path, and your code decides. The usual mistake is json.loads followed by model_validate. That builds a full tree of Python dicts, lists and strings, then walks the tree again to validate it. model_validate_json hands the raw bytes or str to pydantic-core, which parses and validates in a single pass and only creates Python objects for the final model. For a Redis value or a Kafka payload, pass the bytes in directly.
Some payloads are not a BaseModel at the top level: a list[Order], a discriminated union of event types, or a TypedDict. Use TypeAdapter for these. It exposes validate_python, validate_json and dump_json for arbitrary types. Building an adapter compiles a core schema, and that work is expensive compared with validating a single payload. Create the adapter once at module level and reuse it. If you create it inside a handler or a consumer loop, you rebuild the schema on every call.
| Input | Shape | Call |
|---|---|---|
| Raw JSON bytes | Single model | Model.model_validate_json |
| Already-decoded dict | Single model | Model.model_validate |
| Raw JSON bytes | List, union, TypedDict | module-level TypeAdapter(...).validate_json |
Module-level adapters move the schema-building cost to import time. Large unions and deeply nested models make that cost larger. For a long-running server this is a one-time cost and is negligible. For serverless functions and workers that restart often, it adds to every cold start, so measure import time as well as request latency.
from typing import Annotated, Literal, Union
from pydantic import BaseModel, Field, TypeAdapter
class Order(BaseModel):
id: int
sku: str
quantity: int
class OrderCreated(BaseModel):
kind: Literal["created"]
order: Order
class OrderCancelled(BaseModel):
kind: Literal["cancelled"]
order_id: int
reason: str
OrderEvent = Annotated[Union[OrderCreated, OrderCancelled], Field(discriminator="kind")]
# Built once at import time: the core schema is compiled here, not per message.
ORDER_LIST = TypeAdapter(list[Order])
ORDER_EVENT = TypeAdapter(OrderEvent)
def read_cached_order(raw: bytes) -> Order:
# Single model from a cache value: parse and validate in one pass, no json.loads.
return Order.model_validate_json(raw)
def read_cached_orders(raw: bytes) -> list[Order]:
# Top-level list is not a BaseModel, so use the module-level adapter.
return ORDER_LIST.validate_json(raw)
def handle_message(payload: bytes) -> None:
# Queue payload: the discriminator picks the event model without trying each one.
event = ORDER_EVENT.validate_json(payload)
print(type(event).__name__)
handle_message(b'{"kind": "cancelled", "order_id": 42, "reason": "out of stock"}')
Validating cache and queue payloads directly from raw bytes with model_validate_json and module-level TypeAdapters for a list of models and a discriminated union of events.
How can you improve serialization speed for large FastAPI responses?
For large payloads, the default path does more work than it appears. When an endpoint returns a model or a dict, FastAPI processes it against the response_model (filtering fields and, depending on the version, re-validating), converts it to JSON-compatible Python objects, and then encodes it to JSON. Calling model_dump() yourself adds another full walk of the object graph, because it builds a tree of Python dicts and lists that FastAPI must traverse again.
model_dump_json() avoids most of this. The Rust core goes straight from the model to a JSON string with no intermediate Python objects. If you return that string inside a Response with media_type="application/json", FastAPI sends it unchanged, so the validation, conversion and encoding steps are all skipped. The benefit grows with response size and nesting depth, because those are the factors that make each extra traversal expensive.
The trade-off: you lose response_model filtering
A raw Response bypasses response_model entirely. FastAPI does not drop undeclared fields, so whatever the model contains is sent to the client. If you serialize your internal model, values such as database IDs, password hashes, tenant keys or audit fields can leak without any error.
The safe pattern is to define dedicated public response models that contain only the fields clients should see. Map internal objects into them explicitly, or use model_validate with from_attributes=True when the field names match. Then call model_dump_json() on the public model. The serialized object is already the public shape, so you no longer depend on filtering. Keep response_model or responses metadata on the route so the OpenAPI schema still documents the output.
from fastapi import FastAPI, Response
from pydantic import BaseModel, TypeAdapter
class UserInternal(BaseModel):
# Internal shape: never serialize this directly to clients.
id: int
tenant_key: str
password_hash: str
email: str
display_name: str
class UserPublic(BaseModel):
# Public shape: only fields clients are allowed to see.
email: str
display_name: str
# Build the adapter once at import time, not on every request.
public_users = TypeAdapter(list[UserPublic])
app = FastAPI()
def load_users() -> list[UserInternal]:
return [UserInternal(id=1, tenant_key="tk_example", password_hash="$2b$12$placeholder",
email="ada@example.com", display_name="Ada")]
# response_model is kept only so OpenAPI documents the output.
# FastAPI does not filter a returned Response.
@app.get("/users", response_model=list[UserPublic])
def list_users() -> Response:
# UNSAFE: TypeAdapter(list[UserInternal]).dump_json(rows) would leak hashes and keys.
rows = load_users()
# Copy matching attributes into the public model. Fields it does not declare are dropped here.
public = [UserPublic.model_validate(u, from_attributes=True) for u in rows]
# The Rust core writes JSON bytes directly, with no intermediate dicts and no re-encoding.
body = public_users.dump_json(public)
return Response(content=body, media_type="application/json")
Maps internal users to a dedicated public model and returns JSON bytes serialized by pydantic-core in a raw Response, so the speedup does not depend on response_model filtering and cannot leak internal fields.
What do validators, strict mode and model design cost?
Every field_validator is a Python function call that runs per field, per instance. Declarative constraints such as Field(gt=0, max_length=64), pattern, or Annotated[int, Field(ge=1)] compile into the pydantic-core schema and run in Rust without crossing back into the interpreter. On a list of 10,000 items, that difference occurs 10,000 times. Use declarative constraints wherever they can express the rule. Keep Python validators for logic the schema cannot express.
| Validator mode | What runs | Relative cost | Notes |
|---|---|---|---|
Declarative (Field, Annotated) |
Core only | Lowest | Generic error messages, single field only |
before |
Python, then core | One Python call | Sees raw, unvalidated input |
after |
Core, then Python | One Python call | Sees a typed value, which is usually safest |
wrap |
Python around core | Highest | Calls the inner handler and often catches errors |
plain |
Python replaces core | One Python call | Skips built-in checks, so you own correctness |
Strict mode (ConfigDict(strict=True) on a model, or Field(strict=True) on a field) disables coercion. "42" no longer becomes 42, so pydantic-core skips conversion attempts and rejects mismatched types immediately. Enabling it globally is a risky default because many clients, including form posts, query strings, and older JavaScript, send numeric strings. Those requests start failing with 422 errors. Apply strict mode to internal or high-volume models whose producers you control.
Model shape also has a cost. Each nesting level adds a validation step and an object allocation. A plain union in smart mode may try several members before one fits. A discriminated union (Field(discriminator="kind")) reads one tag and goes straight to the matching model. The trade-off is that it needs a literal tag field on every variant. If clients don't send that field today, adding it is an API contract change.
When should you avoid model_construct and other shortcuts?
Those structural optimizations still validate the data. model_construct does not. It builds an instance by assigning the values you pass, applies defaults for missing fields, and runs none of your type checks, coercion or validators. That makes it safe only for data whose shape your own code has already guaranteed, such as rows you validated a few lines earlier or objects your service built itself.
On untrusted input the failure is silent. A request body with "quantity": "-5" passes straight through as a string, and a field_validator enforcing positivity never runs. Nested dicts are not converted into submodels, so order.customer.email raises AttributeError later, in a background task or serializer, far from the request that caused it. A crafted payload can also put values into a model that every downstream function trusts because "it's a model."
| Approach | Validates input | Safe on untrusted data | Development cost |
|---|---|---|---|
model_construct |
No | No | Bugs surface downstream. New validators are silently skipped on these paths. Every call site needs a trust argument in review. |
| Validate once at the boundary, pass the instance on | Yes, once | Yes | Low. Invariants hold everywhere after entry. |
TypeAdapter for non-model types |
Yes | Yes | Low. Uses the same rules and error format as models. |
| Default lax validation | Yes, with coercion | Yes | Lowest. Predictable behavior with little extra code. |
Shortcuts also add risk at upgrade time. A refactor that adds a validator or changes a default changes nothing on the construct paths, and no test fails until production data exercises the gap. If profiling shows that validation is the bottleneck, first remove the redundant passes. Use model_construct only where you can point to the line that already validated the data.
How do you measure Pydantic v2 performance in FastAPI on your own workload?
Measuring is what tells you whether a change like that earned its risk. Use two layers: an isolated microbenchmark, then a full endpoint under load.
Microbenchmark the validation layer
Use timeit to time model_validate, model_validate_json, the equivalent TypeAdapter calls, and model_dump_json on payloads captured from production, with sensitive data removed. Real payloads matter because cost scales with nesting depth, list length, union branches and validator count. A toy payload with three flat fields skips most of that work, so it can exaggerate how much a change helps. Run enough iterations to get stable numbers, and compare medians rather than single runs.
Confirm the gain end to end
A faster function does not guarantee a faster endpoint. Run the endpoint under a load generator at realistic concurrency, and attach a sampling profiler to see where wall time actually goes. Database calls, network I/O and middleware often dominate. Illustrative estimate: suppose validation drops from 2 ms to 0.5 ms on a request that spends 40 ms waiting on the database. Median latency improves by under 4%. That may not justify a riskier code path.
Re-measure after upgrades
Pydantic, pydantic-core and FastAPI change their internals between releases. A workaround that helped before an upgrade can become neutral or slower afterward. Keep the benchmark script in the repository and rerun it whenever those dependencies change.
This discipline saves engineering time. A few hours of measurement can rule out a week spent on shortcuts like model_construct that would not have moved production latency.
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 fastapi, 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.