This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastapi-pydantic-v2-polymorphic-core-schema-precompilation-guardrail

FastAPI Pydantic v2 Polymorphic Core-Schema Precompilation Guardrail

Enforces module-level compile-time instantiation and core-schema pinning for Pydantic v2 polymorphic discriminated unions and TypeAdapters. Eliminates per-request pydantic-core SchemaValidator reconstruction and dynamic reflection overhead that causes CPU saturation and GIL bottlenecks under high-concurrency ingestion workloads.

Prohibited Anti-Pattern: Dynamic per-request TypeAdapter synthesis and unpinned polymorphic union schema regeneration

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: FastAPI Pydantic v2 Polymorphic Core-Schema Precompilation Guardrail - Enforces module-level compile-time instantiation and core-schema pinning for Pydantic v2 polymorphic discriminated unions and TypeAdapters. Eliminates per-request pydantic-core SchemaValidator reconstruction and dynamic reflection overhead that causes CPU saturation and GIL bottlenecks under high-concurrency ingestion workloads.
globs: app/**/*.py, src/**/*.py, api/**/*.py
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastapi-pydantic-v2-polymorphic-core-schema-precompilation-guardrail"
---

# FastAPI Pydantic v2 Polymorphic Core-Schema Precompilation Guardrail

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dynamic per-request TypeAdapter synthesis and unpinned polymorphic union schema regeneration

## System Constraints
You are a Principal Software Architect enforcing production-grade FastAPI and Pydantic v2 performance invariants. Your primary directive is to eliminate runtime core-schema generation and SchemaValidator rebuilds for polymorphic discriminated unions and dynamic types. You must ensure all polymorphic models, TypeAdapters, and RootModels are pre-compiled and pinned at module import time or during the FastAPI lifespan initialization, never dynamically constructed within request-response path operations or dependency providers.

## Strict Guidelines
- Engineers MUST ALWAYS instantiate `TypeAdapter` instances at the module level or bind them as static singletons during application lifespan initialization.
- Engineers MUST NOT call `TypeAdapter(...)` inside route handlers, FastAPI dependencies (`Depends`), or per-request service methods.
- Models utilizing polymorphic discriminated unions MUST explicitly define `Annotated[Union[...], Field(discriminator='...')]` or `Discriminator(...)` using static literal types.
- FastAPI route handlers consuming high-throughput polymorphic payloads SHOULD accept `fastapi.Request` directly and deserialize using precompiled `TypeAdapter.validate_json(await request.body())` to bypass redundant FastAPI dynamic signature inspect overhead.
- Application lifespan handlers MUST pre-warm and validate all polymorphic core-schemas during startup before traffic ingestion begins.
- Components NEVER dynamically evaluate `create_model` or dynamically compose polymorphic union types within the execution context of a request.

## Bad vs Good Implementations
### Module-Level Precompiled TypeAdapter vs Dynamic Per-Request Instantiation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Instantiating TypeAdapter inside the endpoint forces pydantic-core to reconstruct the Rust-backed SchemaValidator on every single invocation. Under 1,000+ RPS, this triggers extreme CPU saturation, garbage collection churn, and severe GIL contention.
```python
from typing import Annotated, Literal, Union
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel, Field, TypeAdapter

app = FastAPI()

class ClickEvent(BaseModel):
    event_type: Literal["click"]
    element_id: str

class PurchaseEvent(BaseModel):
    event_type: Literal["purchase"]
    amount_cents: int

# Anti-pattern: TypeAdapter constructed inside the path operation or dependency.
# Under heavy load, pydantic-core re-generates core schema and rebuilds SchemaValidator on every request.
@app.post("/events")
async def ingest_event(payload: dict):
    try:
        DynamicEventAdapter = TypeAdapter(
            Annotated[Union[ClickEvent, PurchaseEvent], Field(discriminator="event_type")]
        )
        event = DynamicEventAdapter.validate_python(payload)
        return {"status": "ok", "type": event.event_type}
    except Exception as exc:
        raise HTTPException(status_code=422, detail=str(exc))
```

#### Production Standard (Correct)
> **Standard**: Pinning EVENT_TYPE_ADAPTER at module load creates the Rust SchemaValidator exactly once. Deserializing raw request bytes directly with `validate_json` bypasses redundant intermediate Python dict allocations and FastAPI reflection, eliminating per-request schema reconstruction.
```python
from typing import Annotated, Literal, Union
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, Request, Response, status
from pydantic import BaseModel, Field, TypeAdapter, ValidationError

class ClickEvent(BaseModel):
    event_type: Literal["click"]
    element_id: str

class PurchaseEvent(BaseModel):
    event_type: Literal["purchase"]
    amount_cents: int

# Production Invariant: Compile and pin the SchemaValidator at module initialization time
EventUnion = Annotated[Union[ClickEvent, PurchaseEvent], Field(discriminator="event_type")]
EVENT_TYPE_ADAPTER: TypeAdapter[EventUnion] = TypeAdapter(EventUnion)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Lifespan schema pre-warming assertion
    EVENT_TYPE_ADAPTER.validator.validate_python({"event_type": "click", "element_id": "warmup"})
    yield

app = FastAPI(lifespan=lifespan)

@app.post("/events", status_code=status.HTTP_202_ACCEPTED)
async def ingest_event(request: Request) -> Response:
    raw_body = await request.body()
    try:
        # Zero-copy Rust JSON deserialization directly through the pre-compiled SchemaValidator
        event = EVENT_TYPE_ADAPTER.validate_json(raw_body)
    except ValidationError as exc:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=exc.errors())
    
    return Response(content=f'{{"status":"ok","type":"{event.event_type}"}}', media_type="application/json")
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: FastAPI Pydantic v2 Polymorphic Core-Schema Precompilation Guardrail

FastAPI Pydantic v2 Polymorphic Core-Schema Precompilation Guardrail defines an industrial-grade behavioral standard for backend engineering. Enforces module-level compile-time instantiation and core-schema pinning for Pydantic v2 polymorphic discriminated unions and TypeAdapters. Eliminates per-request pydantic-core SchemaValidator reconstruction and dynamic reflection overhead that causes CPU saturation and GIL bottlenecks under high-concurrency ingestion workloads. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Dynamic per-request TypeAdapter synthesis and unpinned polymorphic union schema regeneration Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDynamic per-request TypeAdapter synthesis and unpinned polymorphic union schema regenerationCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS instantiate `TypeAdapter` instances at the module level or bind them as static singletons during application lifespan initialization.

Engineers MUST ALWAYS instantiate `TypeAdapter` instances at the module level or bind them as static singletons during application lifespan initialization.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT call `TypeAdapter(...)` inside route handlers, FastAPI dependencies (`Depends`), or per-request service methods.

Engineers MUST NOT call `TypeAdapter(...)` inside route handlers, FastAPI dependencies (`Depends`), or per-request service methods.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Models utilizing polymorphic discriminated unions MUST explicitly define `Annotated[Union[...], Field(discriminator='...')]` or `Discriminator(...)` using static literal types.

Models utilizing polymorphic discriminated unions MUST explicitly define `Annotated[Union[...], Field(discriminator='...')]` or `Discriminator(...)` using static literal types.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

FastAPI route handlers consuming high-throughput polymorphic payloads SHOULD accept `fastapi.Request` directly and deserialize using precompiled `TypeAdapter.validate_json(await request.body())` to bypass redundant FastAPI dynamic signature inspect overhead.

FastAPI route handlers consuming high-throughput polymorphic payloads SHOULD accept `fastapi.Request` directly and deserialize using precompiled `TypeAdapter.validate_json(await request.body())` to bypass redundant FastAPI dynamic signature inspect overhead.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Application lifespan handlers MUST pre-warm and validate all polymorphic core-schemas during startup before traffic ingestion begins.

Application lifespan handlers MUST pre-warm and validate all polymorphic core-schemas during startup before traffic ingestion begins.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER dynamically evaluate `create_model` or dynamically compose polymorphic union types within the execution context of a request.

Components NEVER dynamically evaluate `create_model` or dynamically compose polymorphic union types within the execution context of a request.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is FastAPI Pydantic v2 Polymorphic Core-Schema Precompilation Guardrail critical for AI coding assistants?

Enforces module-level compile-time instantiation and core-schema pinning for Pydantic v2 polymorphic discriminated unions and TypeAdapters. Eliminates per-request pydantic-core SchemaValidator reconstruction and dynamic reflection overhead that causes CPU saturation and GIL bottlenecks under high-concurrency ingestion workloads. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Dynamic per-request TypeAdapter synthesis and unpinned polymorphic union schema regeneration) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

FastAPI