← Back to FastAPI, page 5

fastapi-0088 · Hard senior

How do you get good performance from Pydantic v2 in a FastAPI service: TypeAdapter reuse, model_validate_json, strict mode and avoiding double validation?

Pydantic v2 validates in a Rust core, so most cost comes from avoidable work around it. Build TypeAdapters and models once at import time, not per request, use model_validate_json to parse and validate bytes in one pass, prefer simple types and strict mode where coercion is not needed, avoid re-validating data you just validated (response models, model_construct only for trusted data), and set a return annotation so FastAPI serialises through Pydantic directly. Measure with realistic payloads before tuning.

Full answer

Where time goes: building a validator (schema compilation) is expensive; running it is cheap. Per-request building is the most common mistake.

Practical rules:

  1. Create TypeAdapter(list[Student]) at module level. Calling TypeAdapter(...) inside a request handler rebuilds the core schema every time. The same applies to defining models inside functions.
  2. Parse bytes directly: Model.model_validate_json(raw) avoids creating an intermediate Python dict from json.loads. In FastAPI the framework already parses the body for you, but for custom reads (webhooks, queue messages, files) this saves memory and time.
  3. Strict mode: ConfigDict(strict=True) or Field(strict=True) skips coercion paths (and rejects "5" for an int), which is faster and safer for internal service-to-service payloads. For public JSON APIs lax mode is usually what clients expect.
  4. Avoid double validation: with response_model or a return annotation FastAPI validates and serialises your return value, so returning an already-validated model means the work happens twice. For hot endpoints, return plain dicts that match the schema, or return a Response object yourself with response_model=None when bytes are prebuilt (cached JSON).
  5. model_construct() skips validation: use it only for data you trust (rows from your own database, already validated), never for client input.
  6. Choose cheaper types: concrete list[int] beats Sequence[int], Literal beats custom validators, built-in constraints beat Python validators. Python field_validator functions run per item and cost the most. mode="before" validators run extra code on every call.
  7. from_attributes=True for ORM objects reads attributes; load only the columns you need (select(Student.id, Student.name)) and return rows mapped to a lean model.
  8. Serialisation: model_dump_json() writes JSON bytes in Rust and is faster than json.dumps(model.model_dump()). FastAPI uses this path when a return type or response model exists, so deprecated custom response classes such as ORJSONResponse are no longer needed.
  9. Large payloads: stream NDJSON, paginate, and limit list sizes to protect memory.

Measure: use timeit/pyperf on production-shaped payloads and profile endpoints under load (py-spy). The database and network usually dominate, so do not trade readability for micro-gains without evidence.

python
import json

from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, validate_call


class Student(BaseModel):
    roll_no: str
    marks: int


class StrictStudent(BaseModel):
    model_config = ConfigDict(strict=True)
    roll_no: str
    marks: int


STUDENTS = TypeAdapter(list[Student])                      # built once, reused for every call

raw = b'[{"roll_no": "BCA-1", "marks": "81"}, {"roll_no": "BCA-2", "marks": 64}]'
parsed = STUDENTS.validate_json(raw)                       # bytes in, validated models out
print(parsed)
print("same result via json.loads:", parsed == STUDENTS.validate_python(json.loads(raw)))

try:
    StrictStudent.model_validate({"roll_no": "BCA-1", "marks": "81"})
except ValidationError as exc:
    print("strict mode:", exc.errors()[0]["type"])

trusted = Student.model_construct(roll_no="BCA-3", marks="not-an-int")      # no validation at all
print("model_construct keeps bad data:", repr(trusted.marks))

print("serialised:", STUDENTS.dump_json(parsed).decode())


@validate_call
def percent(marks: int, total: int = 100) -> float:
    return round(marks * 100 / total, 1)


print(percent("45", total=50))

Standalone script. Run it with `python file.py`; no server is needed. Timing is deliberately not printed because it varies by machine. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): [Student(roll_no='BCA-1', marks=81), Student(roll_no='BCA-2', marks=64)] same result via json.loads: True strict mode: int_type model_construct keeps bad data: 'not-an-int' serialised: [{"roll_no":"BCA-1","marks":81},{"roll_no":"BCA-2","marks":64}] 90.0

Key points

  • Build TypeAdapters and models once at import time
  • model_validate_json parses and validates bytes in one pass
  • Strict mode avoids coercion work when clients are trusted
  • Avoid validating the same data twice; model_construct only for trusted data
  • Python validators are the slowest part; measure before tuning

Common mistakes

  • Creating TypeAdapter or models inside request handlers
  • Calling json.loads then model_validate when model_validate_json works
  • Returning validated models and also paying for response_model validation on hot paths
  • Using model_construct on client input
  • Optimising before measuring with real payloads

Follow-ups

  • How do you profile a FastAPI endpoint under load?
  • What does defer_build do?
  • When would you use RootModel?

Tips

  • List 3 concrete optimisations
  • Say measure first
  • Mention Rust core