PeaBox Lab › PeaLang › Learn › Chapter 15 › Lesson 5

Part III — Advanced Systems · Chapter 15 · Lesson 5 of 7 · 16 min read

Lesson 5: FastAPI Integration Patterns

Lesson level: Advanced

Purpose: This lesson shows how to host PeaLang inside a FastAPI service without losing the guarantees built in Chapters 14 and 15: one runtime per tenant policy, request-scoped limits and deadlines, contract-shaped request and response models, and a single, predictable error mapping. By the end you will have a production-shaped pricing API that wraps the PricingEngine facade from Lesson 2.

Release note: API names in this lesson follow the illustrative PeaLang v0.63 RC2 Python package (pealang, pealang.fastapi_integration). Verify exact signatures against the release documentation before adopting them.

Learning objectives

5.1 Why FastAPI needs a deliberate integration

FastAPI makes it easy to write an endpoint that loads a script and calls it. That easy version usually fails in production for four reasons. First, loading modules at import time hides startup failures until the first request and makes testing awkward. Second, a single global runtime ignores the tenant differences that Chapter 14 made explicit. Third, PeaLang evaluation is CPU-bound and synchronous, so calling it directly inside an async def endpoint blocks the event loop for every other request. Fourth, without a central error mapping, each endpoint invents its own status codes and the API contract drifts.

The integration in this lesson answers each problem with one FastAPI feature:

Keep the boundary rule from Lesson 1 in mind: FastAPI is the host. It authenticates, authorizes, validates input, and owns transport concerns. PeaLang owns only the business decision behind the exported function.

5.2 Project layout

pricing_service/
  app/
    __init__.py
    main.py              # app factory and lifespan
    settings.py          # environment-driven configuration
    engines.py           # EngineRegistry: one engine per tenant tier
    deps.py              # FastAPI dependencies
    models.py            # Pydantic models mirroring the contract
    errors.py            # exception handlers
    routes/
      quote.py
      health.py
  rules/
    pricing.pea
  contracts/
    pricing.contract.toml
  tests/
    test_quote.py
    test_errors.py
    test_health.py

The layout separates construction (engines.py), wiring (deps.py), shape (models.py), and failure policy (errors.py). Each file can be reviewed on its own, and each maps to one of the problems in 5.1.

5.3 Settings and the engine registry

Configuration comes from the environment and is validated once at startup. A typo in a limit should stop the service from starting, not surface as a strange 500 on Tuesday afternoon.

# app/settings.py
from pathlib import Path
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict

class TierLimits(BaseSettings):
    max_execution_ms: int = Field(250, ge=10, le=5_000)
    max_instructions: int = Field(2_000_000, ge=10_000)
    max_memory_bytes: int = Field(64 * 1024 * 1024, ge=1024 * 1024)
    max_output_bytes: int = Field(64 * 1024, ge=1024)

class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_prefix="PRICING_", env_nested_delimiter="__")

    rules_dir: Path = Path("rules")
    contract_path: Path = Path("contracts/pricing.contract.toml")
    use_bytecode: bool = True
    standard: TierLimits = TierLimits()
    premium: TierLimits = TierLimits(max_execution_ms=750, max_instructions=6_000_000)
    request_deadline_ms: int = Field(1_000, ge=50, le=10_000)

The engine registry builds one PricingEngine per tenant tier during startup. Each engine owns its own runtime, so a premium tenant’s larger budget never leaks into a standard tenant’s request.

# app/engines.py
from dataclasses import dataclass
from pealang import PeaRuntime, RuntimeOptions
from pricing.engine import PricingEngine          # facade from Lesson 2
from pricing.contract import load_contract
from .settings import Settings, TierLimits

@dataclass(frozen=True)
class EngineHandle:
    tier: str
    engine: PricingEngine
    limits: TierLimits

class EngineRegistry:
    def __init__(self, settings: Settings) -> None:
        self._settings = settings
        self._handles: dict[str, EngineHandle] = {}
        self.contract = load_contract(settings.contract_path)

    def start(self) -> None:
        for tier, limits in (("standard", self._settings.standard),
                             ("premium", self._settings.premium)):
            runtime = PeaRuntime(RuntimeOptions(
                permissions={"tier.read"},
                max_execution_ms=limits.max_execution_ms,
                max_instructions=limits.max_instructions,
                max_memory_bytes=limits.max_memory_bytes,
                max_output_bytes=limits.max_output_bytes,
                allow_process=False,
            ))
            engine = PricingEngine.from_runtime(
                runtime, self._settings.rules_dir, self.contract,
                bytecode=self._settings.use_bytecode,
            )
            engine.self_test()           # fail fast on a broken rule set
            self._handles[tier] = EngineHandle(tier, engine, limits)

    def get(self, tier: str) -> EngineHandle:
        try:
            return self._handles[tier]
        except KeyError:
            raise LookupError(f"no engine for tier {tier!r}") from None

    @property
    def ready(self) -> bool:
        return set(self._handles) == {"standard", "premium"}

    def close(self) -> None:
        for handle in self._handles.values():
            handle.engine.close()
        self._handles.clear()

Two details matter. engine.self_test() runs a known cart through the exported function and compares the result with the golden output stored next to the contract; a broken rule set therefore fails startup instead of production traffic. And ready is a real readiness signal that the probe in 5.9 can report honestly.

5.4 Lifespan: construction and shutdown in one place

FastAPI’s lifespan context manager runs once before the first request and once after the last. It is the right owner for anything expensive or stateful.

# app/main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
from .settings import Settings
from .engines import EngineRegistry
from .errors import install_handlers
from .routes import quote, health

def create_app(settings: Settings | None = None) -> FastAPI:
    settings = settings or Settings()

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        registry = EngineRegistry(settings)
        registry.start()
        app.state.settings = settings
        app.state.engines = registry
        try:
            yield
        finally:
            registry.close()

    app = FastAPI(title="Pricing service", version="2.3.0", lifespan=lifespan)
    install_handlers(app)
    app.include_router(quote.router)
    app.include_router(health.router)
    return app

app = create_app()

The create_app factory accepts settings so tests can build an app with a test rules directory and tiny limits. Nothing in the module body loads rules, opens files, or creates runtimes; importing app.main is cheap and side-effect free apart from building the app object.

5.5 Dependencies: tenant, engine, and request budget

Dependencies answer three questions for every request: who is calling, which engine serves them, and how much time this particular request may spend. Keeping the answers in dependencies, not in endpoint bodies, means every route gets the same policy.

# app/deps.py
import time
from dataclasses import dataclass
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Request
from .engines import EngineHandle

@dataclass(frozen=True)
class Tenant:
    id: str
    tier: str

@dataclass(frozen=True)
class RequestBudget:
    deadline: float          # monotonic seconds
    max_execution_ms: int

    def remaining_ms(self) -> int:
        return max(0, int((self.deadline - time.monotonic()) * 1000))

async def current_tenant(request: Request,
                         authorization: Annotated[str | None, Header()] = None) -> Tenant:
    claims = await request.app.state.auth.verify(authorization)   # host-owned auth
    if claims is None:
        raise HTTPException(status_code=401, detail="authentication required")
    return Tenant(id=claims["tenant_id"], tier=claims.get("tier", "standard"))

def engine_for(request: Request,
               tenant: Annotated[Tenant, Depends(current_tenant)]) -> EngineHandle:
    return request.app.state.engines.get(tenant.tier)

def request_budget(request: Request,
                   handle: Annotated[EngineHandle, Depends(engine_for)],
                   x_request_timeout_ms: Annotated[int | None, Header()] = None) -> RequestBudget:
    settings = request.app.state.settings
    ceiling = settings.request_deadline_ms
    asked = x_request_timeout_ms or ceiling
    total_ms = max(50, min(asked, ceiling))          # caller may shorten, never extend
    return RequestBudget(
        deadline=time.monotonic() + total_ms / 1000,
        max_execution_ms=min(handle.limits.max_execution_ms, total_ms),
    )

TenantDep = Annotated[Tenant, Depends(current_tenant)]
EngineDep = Annotated[EngineHandle, Depends(engine_for)]
BudgetDep = Annotated[RequestBudget, Depends(request_budget)]

The budget rule is the key idea: a caller may shorten its deadline but never extend it. The tenant tier sets the ceiling for script execution; the service setting sets the ceiling for the whole request; and the effective execution limit is the smaller of the two. FastAPI caches dependency results per request, so engine_for runs once even though both the endpoint and request_budget depend on it.

Note that the tier comes from verified claims, never from a request header or body field. Letting the caller choose its tier is the FastAPI version of the privilege-escalation mistakes listed in Chapter 14.

5.6 Pydantic models that mirror the contract

The request and response models are the HTTP face of pricing.contract.toml. They must enforce the same patterns, enumerations, and bounds, and they must reject unknown fields so the API cannot quietly accept data the contract does not describe.

# app/models.py
from decimal import Decimal
from enum import Enum
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field

class Currency(str, Enum):
    EUR = "EUR"
    GBP = "GBP"
    USD = "USD"

class Reason(str, Enum):
    NONE = "NONE"
    GOLD_100 = "GOLD_100"
    BULK_250 = "BULK_250"

Money = Annotated[Decimal, Field(ge=0, max_digits=12, decimal_places=2)]

class Item(BaseModel):
    model_config = ConfigDict(extra="forbid", frozen=True)
    sku: Annotated[str, Field(pattern=r"^[A-Z0-9-]{3,32}$")]
    qty: Annotated[int, Field(ge=1, le=10_000)]
    unit_price: Money

class QuoteRequest(BaseModel):
    model_config = ConfigDict(extra="forbid")
    customer_id: Annotated[str, Field(pattern=r"^C[0-9]{6}$")]
    currency: Currency
    items: Annotated[list[Item], Field(min_length=1, max_length=200)]

class QuoteResponse(BaseModel):
    model_config = ConfigDict(extra="forbid")
    subtotal: Money
    discount_pct: Annotated[int, Field(ge=0, le=30)]
    reason: Reason
    module_version: str

class ErrorBody(BaseModel):
    code: str
    message: str
    request_id: str

Hand-written models drift. In a real project, generate models.py from the contract in CI, or keep it hand-written but add a test that loads the contract and asserts that every field, pattern, bound, and enumeration value matches. Section 5.11 includes that test, and Lesson 6 generalizes the idea to every host language.

Validating twice is deliberate. Pydantic rejects malformed HTTP input with a 422 before any script runs, which keeps junk away from the runtime. The PricingEngine facade still validates at the language boundary, because the facade is also used by batch jobs that never pass through FastAPI.

5.7 Async endpoints over a synchronous runtime

PeaLang evaluation through the Python package is synchronous and CPU-bound. If an async def endpoint calls it directly, the event loop stops serving other requests until the script finishes. There are two correct options: declare the endpoint with plain def, which FastAPI runs in its threadpool automatically, or keep the endpoint async and hand the call to a worker thread explicitly. The second option is preferable when the endpoint also awaits other I/O, such as an audit write.

# app/routes/quote.py
import anyio
from fastapi import APIRouter, Request
from ..deps import TenantDep, EngineDep, BudgetDep
from ..models import QuoteRequest, QuoteResponse, ErrorBody
from ..errors import DeadlineExceeded

router = APIRouter(prefix="/api")

# Bound concurrent evaluations so CPU-heavy scripts cannot starve the process.
_EVAL_SLOTS = anyio.CapacityLimiter(8)

@router.post(
    "/quote",
    response_model=QuoteResponse,
    responses={400: {"model": ErrorBody}, 403: {"model": ErrorBody},
               429: {"model": ErrorBody}, 503: {"model": ErrorBody},
               504: {"model": ErrorBody}},
)
async def quote(body: QuoteRequest, request: Request,
                tenant: TenantDep, handle: EngineDep, budget: BudgetDep) -> QuoteResponse:
    remaining = budget.remaining_ms()
    if remaining < 20:
        raise DeadlineExceeded("request budget exhausted before evaluation")

    cart = body.model_dump(mode="json")
    limit_ms = min(budget.max_execution_ms, remaining)

    with anyio.fail_after(remaining / 1000):
        result = await anyio.to_thread.run_sync(
            lambda: handle.engine.quote(cart, max_execution_ms=limit_ms,
                                        tenant_id=tenant.id),
            limiter=_EVAL_SLOTS,
        )

    await request.app.state.audit.record(tenant.id, "quote", result.evidence)
    return QuoteResponse(**result.decision, module_version=result.module_version)

Read the call carefully:

Rule: an async deadline cancels waiting; only a runtime limit cancels work. Production integrations need both.

5.8 One error mapping for the whole service

Chapter 14 introduced install_exception_handlers from pealang.fastapi_integration, which maps the PeaLang runtime exceptions to the standard error codes. This service adds handlers for its domain errors and for deadline failures, and it makes sure every error body has the same three fields.

# app/errors.py
import logging
import uuid
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pealang.fastapi_integration import install_exception_handlers
from pricing.engine import InvalidCart, PricingUnavailable, RuleDefect, ContractError

log = logging.getLogger("pricing.errors")

class DeadlineExceeded(Exception):
    pass

def _body(request: Request, status: int, code: str, message: str) -> JSONResponse:
    rid = request.headers.get("x-request-id") or str(uuid.uuid4())
    return JSONResponse(status_code=status,
                        content={"code": code, "message": message, "request_id": rid},
                        headers={"x-request-id": rid})

def install_handlers(app: FastAPI) -> None:
    install_exception_handlers(app)      # PeaPermissionError, PeaResourceLimitError, PeaRuntimeError

    @app.exception_handler(RequestValidationError)
    async def _validation(request: Request, exc: RequestValidationError):
        fields = sorted({".".join(map(str, e["loc"][1:])) for e in exc.errors()})
        return _body(request, 422, "INVALID_REQUEST", "invalid fields: " + ", ".join(fields))

    @app.exception_handler(InvalidCart)
    async def _invalid(request: Request, exc: InvalidCart):
        return _body(request, 400, "INVALID_CART", str(exc))

    @app.exception_handler(RuleDefect)
    async def _defect(request: Request, exc: RuleDefect):
        log.error("rule defect", exc_info=exc)
        return _body(request, 500, "RULE_DEFECT", "pricing rules failed; operators notified")

    @app.exception_handler(ContractError)
    async def _contract(request: Request, exc: ContractError):
        log.error("contract violation on %s side", exc.side, exc_info=exc)
        return _body(request, 500, "CONTRACT_VIOLATION", "pricing contract violated")

    @app.exception_handler(PricingUnavailable)
    async def _unavailable(request: Request, exc: PricingUnavailable):
        return _body(request, 503, "PRICING_UNAVAILABLE", "pricing temporarily unavailable")

    @app.exception_handler(TimeoutError)
    @app.exception_handler(DeadlineExceeded)
    async def _deadline(request: Request, exc: Exception):
        return _body(request, 504, "DEADLINE_EXCEEDED", "pricing did not finish in time")

The resulting mapping is small enough to publish in the API documentation:

SourceStatusCodeWho must act
Pydantic validation422INVALID_REQUESTCaller fixes request
InvalidCart (facade validation)400INVALID_CARTCaller fixes request
PeaPermissionError403PEA_PERMISSION_DENIEDOperator reviews policy
PeaResourceLimitError429PEA_RESOURCE_LIMITCaller retries later or reduces cart size
PricingUnavailable503PRICING_UNAVAILABLECaller retries with backoff
DeadlineExceeded / TimeoutError504DEADLINE_EXCEEDEDCaller retries; operator checks latency
RuleDefect500RULE_DEFECTRule author fixes script
ContractError500CONTRACT_VIOLATIONHost or rule author, depending on side

Notice what the bodies do not contain: stack traces, PeaLang source lines, host function names, or tenant policy values. Those belong in logs keyed by request_id, not in responses that an attacker can read.

5.9 Health and readiness

Liveness and readiness answer different questions. Liveness asks whether the process should be restarted; readiness asks whether it should receive traffic. Mixing them causes restart loops when a dependency is slow.

# app/routes/health.py
from fastapi import APIRouter, Request, Response

router = APIRouter()

@router.get("/healthz")
async def healthz() -> dict:
    return {"status": "ok"}             # process is alive; no dependency checks

@router.get("/readyz")
async def readyz(request: Request, response: Response) -> dict:
    engines = getattr(request.app.state, "engines", None)
    ready = engines is not None and engines.ready
    if not ready:
        response.status_code = 503
    return {
        "status": "ready" if ready else "starting",
        "contract": engines.contract.version if engines else None,
        "module_version": engines.get("standard").engine.module_version if ready else None,
    }

Readiness reports the contract and module versions. During a rolling deployment, operators can see exactly which rule build each instance is serving, which is the same evidence the Java and TypeScript clients log from response bodies.

5.10 Request IDs, logging, and metrics

A thin middleware gives every request an ID and records the latency and outcome. Keep it thin: middleware runs for every route, including health probes, and must never call the runtime.

# app/observability.py
import logging, time, uuid
from starlette.middleware.base import BaseHTTPMiddleware

log = logging.getLogger("pricing.http")

class RequestContext(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        rid = request.headers.get("x-request-id") or str(uuid.uuid4())
        request.state.request_id = rid
        started = time.perf_counter()
        response = await call_next(request)
        elapsed_ms = (time.perf_counter() - started) * 1000
        response.headers["x-request-id"] = rid
        if request.url.path not in ("/healthz", "/readyz"):
            log.info("http", extra={"rid": rid, "path": request.url.path,
                                    "status": response.status_code,
                                    "elapsed_ms": round(elapsed_ms, 1)})
        return response

Register it in create_app with app.add_middleware(RequestContext). Useful metrics for a PeaLang-backed endpoint are: evaluations per tier, evaluation latency percentiles, resource-limit rejections by limit name, limiter queue wait time, and rule-defect count. A rising queue wait with flat evaluation latency means you need more workers; rising evaluation latency with a flat queue means a rule change made scripts slower.

5.11 Testing the service with TestClient

Using TestClient as a context manager runs the lifespan, so tests exercise real engine construction, real rule loading, and real error handlers. Build the app through the factory with test settings and a stub authenticator.

# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from app.main import create_app
from app.settings import Settings, TierLimits

class StubAuth:
    async def verify(self, header):
        table = {"Bearer std": {"tenant_id": "T1", "tier": "standard"},
                 "Bearer pro": {"tenant_id": "T2", "tier": "premium"}}
        return table.get(header)

@pytest.fixture
def client(tmp_path):
    settings = Settings(
        standard=TierLimits(max_execution_ms=100, max_instructions=200_000),
        request_deadline_ms=500,
        use_bytecode=False,
    )
    app = create_app(settings)
    with TestClient(app) as c:
        app.state.auth = StubAuth()
        app.state.audit = InMemoryAudit()
        yield c

CART = {"customer_id": "C000123", "currency": "EUR",
        "items": [{"sku": "AB-100", "qty": 3, "unit_price": "40.00"}]}
# tests/test_quote.py
from tests.conftest import CART

def test_quote_happy_path(client):
    r = client.post("/api/quote", json=CART, headers={"Authorization": "Bearer std"})
    assert r.status_code == 200
    body = r.json()
    assert body["subtotal"] == "120.00"
    assert body["reason"] in {"NONE", "GOLD_100", "BULK_250"}
    assert body["module_version"]

def test_unknown_field_rejected(client):
    bad = {**CART, "discount_pct": 30}            # caller tries to set the answer
    r = client.post("/api/quote", json=bad, headers={"Authorization": "Bearer std"})
    assert r.status_code == 422
    assert r.json()["code"] == "INVALID_REQUEST"

def test_caller_cannot_extend_deadline(client):
    r = client.post("/api/quote", json=CART, headers={
        "Authorization": "Bearer std", "X-Request-Timeout-Ms": "60000"})
    assert r.status_code == 200                   # clamped to 500 ms, still succeeds

def test_missing_auth(client):
    assert client.post("/api/quote", json=CART).status_code == 401

def test_readiness_reports_versions(client):
    body = client.get("/readyz").json()
    assert body["status"] == "ready"
    assert body["contract"] == "2.3.0"

Add error-path tests by swapping in a rules directory that contains deliberately faulty scripts: an infinite loop to trigger PEA_RESOURCE_LIMIT, a call to an unregistered host function to trigger PEA_PERMISSION_DENIED, and a script that returns discount_pct = 45 to trigger CONTRACT_VIOLATION. Finally, add the model-drift test promised in 5.6:

# tests/test_models_match_contract.py
from app.models import QuoteRequest, QuoteResponse
from pricing.contract import load_contract

def test_models_match_contract():
    contract = load_contract("contracts/pricing.contract.toml")
    req = QuoteRequest.model_json_schema()
    assert req["properties"]["customer_id"]["pattern"] == contract.inputs["customer_id"].pattern
    assert req["properties"]["items"]["maxItems"] == contract.inputs["items"].max_items
    resp = QuoteResponse.model_json_schema()
    reasons = set(resp["$defs"]["Reason"]["enum"])
    assert reasons == set(contract.outputs["reason"].values)
    assert resp["properties"]["discount_pct"]["maximum"] == contract.outputs["discount_pct"].max

5.12 Deployment notes

A few deployment choices follow directly from the design:

5.13 Common mistakes

MistakeConsequenceFix
Loading rules at module import timeStartup failures appear on first request; tests are slow and order-dependentBuild engines in the lifespan through an app factory
Calling the runtime directly in an async endpointEvent loop blocks; unrelated requests stallUse a threadpool call with a capacity limiter, or a plain def endpoint
Relying only on an async timeoutThread keeps burning CPU after the client gets a 504Pass the remaining budget into the runtime execution limit
Taking the tier or limits from request inputCallers grant themselves larger budgetsDerive tier from verified claims; allow callers only to shorten deadlines
Models with extra fields allowedCallers send fields the contract never definedSet extra="forbid" and test models against the contract
Exposing script errors in response bodiesLeaks rule logic and host detailsReturn code, message, and request_id; log details server-side
Readiness that always returns 200Traffic reaches instances with broken rulesReport ready only after engines start and self-tests pass

Guided practice

Hands-on lab

Build the pricing service described in this lesson. It must use the app factory and lifespan, one engine per tier, the three dependencies, Pydantic models with forbidden extra fields, a bounded threadpool call, the full error mapping, health and readiness probes, and request-ID middleware. Write at least twelve tests covering the happy path, every error code in the mapping table, deadline clamping, and contract-model drift.

Deliverable: the pricing_service project, a passing test run, and a one-page note recording p50 and p95 latency for 20 concurrent clients with limiter sizes of 2, 4, and 8.

Review questions

Applied challenge

Add a batch endpoint, POST /api/quotes, that accepts up to 50 carts and returns one result or error per cart. The whole batch shares a single request budget, evaluations run through the same capacity limiter, and one failing cart must not fail the others. Decide how to report partial results, document the response shape, and prove with tests that a batch cannot exceed the budget of a single request.

Lesson summary

A FastAPI host for PeaLang works best when each concern has one owner. The lifespan constructs engines and fails fast on broken rules. Dependencies identify the tenant, select its engine, and compute a request budget that callers can shorten but never extend. Pydantic models mirror the contract and reject unknown fields. Synchronous evaluation runs in a bounded threadpool with the remaining budget passed to the runtime itself. A single set of exception handlers turns every failure into a stable code, and honest health and readiness probes make deployments observable.

Transition to Lesson 6

Every host so far has converted values with a blunt tool: model_dump(mode="json") in Python, Jackson defaults in Java, and JSON parsing in TypeScript. Lesson 6 replaces these with typed embedding contracts and explicit, versioned converters for decimals, timestamps, identifiers, and enumerations, so that a value means the same thing in every language.

Lesson status: Ready for review.

← Previous Next →