13A.5 Architecture Patterns for AI Applications

Ship & get hiredLesson 5 of 815,789 words9 parts
Module 13A · 0 of 8 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8

Lessons 13A.2 to 13A.4 designed how an AI feature should feel: streamed output that doesn't stutter, trust signals that calibrate rather than decorate, and failure states that tell the truth. This lesson is about the system that has to exist for those designs to be real. An AI application is not a prompt plus an API call. It is a layered system — clients, a backend-for-frontend, an application API, orchestration, a model gateway, retrieval, tools, storage, jobs, observability, safety and configuration — where every layer exists because a specific AI-specific problem demands it: non-determinism, long latency, unbounded cost, prompt injection, and the fact that the model is stateless and probabilistic. This lesson gives you the reference architecture, the core patterns that recur across every AI product, the API and storage decisions that keep the system honest, the non-functional budgets that keep it affordable, and the documentation habits (ADRs, C4 diagrams) that keep it maintainable — ending with reference architectures for the three capstones in lessons 13B.2 to 13B.5.

What you'll learn

  • The reference architecture of an AI application, layer by layer, and which earlier module owns each layer
  • The core patterns: backend-for-frontend and streaming gateway (including how to scale and drain the streaming edge), synchronous vs streaming vs async jobs vs event-driven pipelines, workflow vs agent orchestration, bounded services, plugin registries, model gateways, durable execution, multi-tenancy, configuration and feature flags, caching, idempotency across boundaries, and the transactional outbox
  • State and storage for AI systems: conversations, memory, documents, vectors, job state, audit logs and feedback — and when Postgres with pgvector is enough
  • API design for AI features: contract stability while models change underneath you, meta blocks, webhooks, rate limits, errors as data, and OpenAPI
  • Non-functional budgets: how to allocate latency, cost, availability, quality and safety budgets across the stages of a request
  • When a monolith is right, and how to structure one with ports and adapters so the model, the vector store and the tools can be faked in tests
  • How to document architecture: ADRs, the C4 model, threat-model overlays and runbooks
  • Reference architectures for the three capstones, and the anti-patterns that quietly sink AI products

What you don't need

  • API keys. The package code in this lesson (ai_product/ports.py, ai_product/app.py, ai_product/jobs.py) runs entirely against in-memory fakes and a fake clock — no provider is contacted. Samples that would call a provider are labelled illustrative.
  • A running database, queue, Temporal server or vector store. Every store and broker is represented by a port (a small interface) with an in-memory fake; production choices are decision tables, not setup instructions.
  • Anything from Modules 03 to 12 re-taught. Each pattern links to the lesson that owns the detail; this lesson is about how the pieces fit together.

Setup

The code in this lesson needs Python 3.11+ and FastAPI for the application skeleton. The package files themselves (ports.py, jobs.py) use only the standard library. If you haven't created a project yet, run uv init ai-product --bare --python 3.13 (see lesson 03.1, Part 4 for the full setup), then:

bash
uv add fastapi uvicorn pydantic httpx
# or: pip install fastapi uvicorn pydantic httpx

(The samples were checked against fastapi 0.162.0, uvicorn 0.54.0, pydantic 2.14.3 and httpx 0.28.1, the versions lesson 01B.7 and lesson 03.3 use, as of November 2026. A plain install gives you the newest release; if a newer FastAPI or uvicorn changes a default or deprecates an import, check its release notes.) There is no .env in this lesson: nothing here calls a provider. The ai_product package grows across lessons 13A.2 to 13B.1; this lesson introduces ports.py, app.py and jobs.py, and the file listing at the end shows the package as it stands after this lesson.


What you must be able to do after this lesson#

  • Name the layers of an AI application architecture
  • Choose between sync call, streaming, async job and event pipeline
  • Place a BFF and a model gateway and say what each must own
  • Allocate latency, cost and quality budgets across a request
  • Structure a monolith with ports and adapters so the model can be faked in tests

Why this matters for an AI engineer#

Every previous module taught you a component. This lesson teaches you the system they live in — the thing you will actually be hired to design.

You'll hear... You'll understand it after...
"Put the model calls behind one gateway." 2.6 Model gateway and provider abstraction
"Should this be a workflow or an agent?" 2.3 Workflow vs agent orchestration
"That job takes three minutes — don't hold the request open." 2.2 Four ways to answer a request
"We need durable execution for the refund flow." 2.7 Durable execution and human-in-the-loop engines
"Every tenant needs isolated prompts, caches and quotas." 2.8 Multi-tenancy
"Ship dark behind a feature flag." 2.9 Configuration, prompt registry and feature flags
"Is Postgres enough for our vectors?" 3.4 Choosing a store for each kind of state
"The API contract must survive the next model swap." Part 4: API design for AI features
"What's our latency budget for a RAG-with-tools request?" Part 5: Non-functional budgets
"Monolith first — but where are the seams?" Part 6: Monolith first
"Why do we write an ADR for this?" Part 7: Documenting architecture
"This looks like the support copilot from 13B.2." Part 8: Reference architectures

Part 1: From components to a system#

1.1 What an AI application actually is#

Strip away the marketing and an AI application is an ordinary distributed system with three unusual properties:

  1. A component that is non-deterministic. The same input can produce different outputs, at different latencies, at different costs, and occasionally unsafe ones. Every deterministic assumption your backend was built on — "same request, same answer", "response time is roughly constant", "errors are exceptions" — needs re-examination at the boundary where the model is called.
  2. A component that is stateless and forgetful. The model remembers nothing between calls (lesson 02.7). Whatever the product "remembers" — conversation history, user preferences, documents, job progress — lives in your storage and is re-sent or re-fetched on every turn.
  3. A component whose failure modes are semantic. A 200 OK can still contain a wrong, hallucinated, refused or prompt-injected answer (lesson 02.10). Your system's correctness boundary is not the HTTP status line; it is the output contract plus the validation and guardrails around it.

Everything in this lesson follows from those three properties. The architecture exists to contain non-determinism behind stable interfaces, to own all state the model lacks, and to make semantic failure a first-class, typed, observable outcome rather than a silent one.

1.2 The reference architecture in layers#

Here is the reference architecture this lesson uses. Every box maps to a module that owns the detail; this lesson owns the arrangement.

flowchart TB
    subgraph clients ["Clients"]
        WEB["Web / mobile app"]
        APIc["Third-party API clients"]
    end

    subgraph edge ["Edge"]
        CDN["CDN / static assets"]
        BFF["Backend-for-frontend<br/>(session, aggregation, SSE fan-out)"]
    end

    subgraph app ["Application API"]
        GW["API gateway / app server<br/>(auth, rate limits, request IDs)"]
        ORCH["Orchestration<br/>(conversation, workflow or agent loop)"]
    end

    subgraph ai ["AI services"]
        MGW["Model gateway<br/>(provider abstraction, routing, fallback)"]
        RAG["Retrieval service<br/>(RAG pipeline, bounded context)"]
        TOOL["Tool / integration layer<br/>(registry, policy, approvals)"]
    end

    subgraph data ["Data and jobs"]
        STORE[("Primary store<br/>conversations, jobs, audit, users")]
        VEC[("Vector store<br/>documents, embeddings")]
        DOCS[("Object storage<br/>uploads, generated files")]
        QUEUE["Job queue / durable engine<br/>(async work, HITL waits)"]
    end

    subgraph ext ["External"]
        PROV["Model providers<br/>OpenAI · Anthropic · Gemini · OpenRouter"]
        SAAS["SaaS integrations<br/>(ticketing, payments, email)"]
    end

    subgraph ops ["Cross-cutting"]
        OBS["Observability<br/>traces, metrics, evals"]
        SAFE["Safety layer<br/>guards, PII, policy, approvals"]
        CFG["Config<br/>prompts, flags, model aliases, secrets"]
    end

    WEB --> CDN
    WEB --> BFF
    APIc --> GW
    BFF --> GW
    GW --> ORCH
    ORCH --> MGW
    ORCH --> RAG
    ORCH --> TOOL
    ORCH --> SAFE
    ORCH --> STORE
    RAG --> VEC
    TOOL --> SAAS
    MGW --> PROV
    ORCH --> QUEUE
    QUEUE --> STORE
    QUEUE --> ORCH
    OBS -.-> GW
    OBS -.-> ORCH
    OBS -.-> MGW
    CFG -.-> ORCH
    CFG -.-> MGW
    SAFE -.-> MGW
    SAFE -.-> TOOL

Read it as a request path and an offline path:

  • Online (a user asks something): client → edge/BFF → application API → orchestration → model gateway → provider, with retrieval, tools, safety and storage consulted as the orchestration decides.
  • Offline (ingestion, batch work, long jobs): ingestion pipelines and job runners feed the stores; the queue carries work that outlives a request; observability watches both paths.

1.3 Who owns each layer#

Layer What it is for Owned by
Clients Render the UX of 13A.2 to 13A.4 This module (wireframes, event contract); 13B.2 to 13B.5 for the capstones
Edge / BFF Session handling, fan-out of streams to many viewers, adapting the API to each client 03.3 (SSE mechanics), 01B.7 (the API service)
Application API Auth, rate limits, request IDs, typed errors, versioning 01B.7, 03.8, this lesson Part 4
Orchestration Decide the shape of the answer: one call, a workflow, or an agent loop 08A.9 (workflow vs agent), 08A.2 (the loop), this lesson 2.3
Model gateway One seam to all providers: canonical types, routing, fallback, cost attribution 03.11, 11C.3
Retrieval Turn the question into grounded context 07 end to end; 07.11 for the bounded service
Tools / integrations Give the model bounded, validated actions on your systems 08A.6, 08E.1
Safety Guards, injection defence, PII handling, approvals 12 end to end
Storage Conversations, memory, documents, vectors, jobs, audit, feedback 05 (documents), 06.5 (vectors), this lesson Part 3
Jobs / durable execution Work that outlives a request; waits for humans 03.9 (batch), this lesson 2.2 and 2.7
Observability Traces, metrics, SLOs, evals, cost 11A.1, 11A.2, 10
Config Prompts, flags, model aliases, secrets, budgets 04.10, 11C.2

The discipline this table enforces: each layer has one owner module, and this lesson never re-teaches it. When you design your own system, you will fill each box with the concrete choice that module taught you — the point here is knowing the box exists and what breaks when you skip it.

1.4 Why layers earn their place#

A common failure of first AI systems is collapsing everything into one deployable function: parse request → call model → return text. That works for a demo and fails in production for predictable reasons:

  • No gateway means provider SDK calls scattered through handlers, each with its own retry and error logic — the first anti-pattern in 9.1.
  • No orchestration boundary means "is this a workflow or an agent?" gets re-litigated in every endpoint, and agent loops appear where a fixed pipeline would do.
  • No job layer means a three-minute document analysis dies at the proxy's 30-second timeout, and the user stares at a spinner.
  • No safety layer as a seam means guardrails get bolted on per call site and drift apart.
  • No config layer means prompt strings and model IDs are hard-coded, so a prompt fix requires a deploy and a model swap is a search-and-replace across the codebase.

Each layer below exists because removing it produces one of those failures. The patterns in Part 2 are the reasons the layers are shaped the way they are.

1.5 What this means for you as an engineer#

Before you write any AI feature code, draw the layered diagram for your system and label each box with the module (or your own choice) that fills it. If a box has no owner, that is your first architecture task — not the model call. The capstones in Part 8 show three complete drawings you can adapt.


Part 2: Core patterns#

Each pattern below gets the same treatment: the problem it solves, when to use it and when not to, the trade-offs, and where the detail lives in earlier modules. Sequence diagrams show the request flows.

2.1 Backend-for-frontend and the streaming gateway#

The problem. Your product has more than one client shape: a web app, a mobile app, an internal tool, maybe an API for partners. Each wants a different view of the same AI capability — the web wants SSE token streams, the mobile app wants a resumable job, the partner API wants a single JSON document. If each client talks to the model gateway directly, every client re-implements auth, prompt assembly, guardrails and cost accounting.

The pattern. A backend-for-frontend (BFF) sits between clients and your application services. It owns the client-specific concerns — session auth, request shaping, fan-out, protocol translation — and exposes one or more tailored APIs. For AI features the BFF (or the application API behind it) typically also owns the streaming gateway role: it opens the provider stream, runs it through your smoother and event contract (lesson 13A.2), and re-emits events the client can render.

sequenceDiagram
    participant C as Client (browser)
    participant BFF as BFF / app API
    participant ORCH as Orchestration
    participant GW as Model gateway
    participant P as Provider

    C->>BFF: POST /v1/ask (question)
    BFF->>ORCH: canonical request + tenant + request_id
    ORCH->>GW: complete(messages, model_alias)
    GW->>P: provider stream
    P-->>GW: token deltas
    GW-->>ORCH: canonical stream events
    ORCH-->>BFF: typed events (status, token, citation, done)
    BFF-->>C: SSE: data: {...} events
    Note over BFF,C: BFF may buffer/smooth per client,<br/>translate to polling for mobile,<br/>or aggregate for partner API

When to use it. Almost always, once you have more than one client or more than one protocol concern. Even a single web app benefits from the BFF owning auth and the event contract, because the alternative is provider-shaped responses leaking into your UI code.

When not to. A pure server-to-server product (an API-only product) may collapse BFF and application API into one layer — the "BFF" is just your public API. A single internal tool can call services directly. The pattern earns its keep when client diversity or client-specific logic exists.

Trade-offs. The BFF is a hop: it adds latency (usually small, since it mostly proxies and transforms) and a deployable to maintain. It pays for itself by preventing N clients × M concerns of duplicated logic.

Scaling the streaming edge. An open stream is an open connection that your process holds for seconds to minutes, so the edge has capacity rules that ordinary request-response services lack:

  • Async servers hold many idle connections cheaply, but each stream also holds a provider connection, memory for buffered text and a slot in every concurrency limit. Cap concurrent streams per process and per tenant, and return a typed "busy" error (13A.4's warn.overloaded) instead of accepting work you cannot finish (11C.3, Part 4).
  • Load balancers and proxies must not buffer or cut the stream. Disable response buffering for the stream route, send heartbeats, and set idle timeouts above your longest expected silence (03.3, 11.7). Over HTTP/1.1 browsers also cap SSE connections per domain (13A.2, 6.4).
  • Deploys and scale-in kill live streams. Drain: stop accepting new streams, let in-flight ones finish (with a deadline), and have the client treat a premature close as a resumable event, not an error.
  • Resume needs shared state. If a reconnecting client may reach a different instance, the events it missed must live somewhere every instance can read, such as a short-lived per-request event buffer in Redis or your primary store, keyed by request_id and the SSE id: sequence from 13A.2. Without it, Last-Event-ID resume only works when the client lands on the same process; the fallback is the restart-and-reset recovery of 13A.2, 2.5.
  • Billing continues after disconnects. The server should cancel the upstream provider call when the client goes away (and decide whether to keep generating into the buffer for resume); otherwise you pay for answers nobody receives (03.3, 8.5).

What this means for you as an engineer: put auth, session, request-ID propagation and stream protocol translation in the BFF; put "what should happen next" in orchestration; never let a client see a provider-shaped stream.


2.2 Four ways to answer a request#

Not every AI request should be answered inside an HTTP request. The shape of the response path is a first-order architecture decision, and getting it wrong is the most common cause of "the demo worked, production timed out".

Shape Request path Use when Watch out for
Synchronous request-response Client → API → model → response, one HTTP call Short, interactive answers where the user is watching (chat, autocomplete-adjacent, single-shot extraction) Latency must fit the client's patience and every proxy timeout en route (typically 30–60 s at CDNs/load balancers; verify your platform's limits)
Streaming Same, but the response body is an event stream (SSE or chunked) Anything where perceived latency matters — chat, agent progress, long generations The connection is still bounded by timeouts; streams that run for minutes need heartbeats and resumability (03.3, 13A.2)
Async job Client submits → gets a job ID → polls or gets a webhook → retrieves result Work measured in tens of seconds to hours: document processing, batch extraction, report generation, voice session summaries You must build job state, status endpoints, result storage, expiry and idempotent submission — this lesson's jobs.py is the minimal version
Event-driven pipeline Producers emit events; consumers process them independently; state lives in stores and the event log Continuous flows: ingestion → chunk → embed → index; document → extract → validate → publish; feedback → eval case → regression suite Ordering, duplicates and replay become your problems; you need idempotent consumers and a dead-letter path

The four are not mutually exclusive. A document-intelligence app (13B.3) uses a job for the heavy processing and streams progress events while it runs. A support copilot (13B.2) streams chat answers synchronously but writes refund actions to a job queue that a worker executes after approval.

sequenceDiagram
    participant C as Client
    participant API as App API
    participant Q as Job queue
    participant W as Worker
    participant DB as Store

    C->>API: POST /v1/jobs (Idempotency-Key: k1)
    API->>DB: insert job (pending, key=k1)
    API-->>C: 202 {job_id, status: "queued"}
    API->>Q: enqueue job_id
    W->>Q: dequeue job_id
    W->>DB: claim job (pending → running)
    W->>W: process (model calls, tools)
    W->>DB: write result + events
    W->>DB: status → succeeded
    C->>API: GET /v1/jobs/{id} (poll) or webhook
    API-->>C: {status: "succeeded", result: {...}}

Decision rule: estimate the p95 latency of the operation including retries and provider degradation. Under ~10 s and interactive → synchronous or streaming. Over ~30 s, or the user can walk away → async job. Continuous or fan-out work → event-driven. When in doubt, prefer the async shape: a job can always be made to feel synchronous with polling, but a held-open request cannot be un-timeout'd.

What this means for you as an engineer: decide the response shape per endpoint before you write the handler, and write it down in the API contract. "This endpoint may take 90 s" is an architecture decision, not an implementation detail.


2.3 Workflow vs agent orchestration#

Lesson 08A.9 owns the deep treatment: the definitions, the decision framework, and every workflow pattern (prompt chaining, routing, parallelization, orchestrator-workers, evaluator-optimizer, map-reduce, HITL checkpoints, fallback chains). This lesson adds only the architectural consequence: the choice determines what your orchestration layer must be able to do.

If orchestration is... Your orchestration layer needs Your durability needs
A fixed workflow (known steps, known order) A pipeline of typed stages; each stage is testable in isolation Restart/resume at stage boundaries; idempotent stages
A bounded agent loop (model chooses among tools, within a budget) The canonical loop from 08A.2 behind a port; loop budgets and detection Persist loop state if it must survive restarts; otherwise in-memory is fine
An open-ended agent (model plans across many steps, maybe hours) Durable execution (2.7): every step checkpointed, waits are first-class The engine is your durability layer
A hybrid (workflow with agentic sub-steps) Workflows composed of sub-workflows and bounded agent loops Per-sub-flow durability; the outer flow is deterministic

The product-level consequence you own: the same user-visible feature can be implemented at any point on the spectrum, and the choice is reversible only with effort. Choosing "agent" for a problem that is really "extract these five fields" buys you non-determinism, cost and debugging pain you didn't need. Choosing "workflow" for a problem that genuinely needs exploration paints you into a corner where every new case is a code change.

flowchart LR
    Q["User request"] --> D{"Known shape<br/>and order?"}
    D -- "yes" --> W["Workflow:<br/>fixed stages"]
    D -- "no, bounded choices" --> A["Agent loop:<br/>model picks tools,<br/>budget caps steps"]
    D -- "no, open-ended,<br/>long-running" --> E["Durable agent:<br/>engine checkpoints<br/>every step"]
    W --> R["Result + trace"]
    A --> R
    E --> R

What this means for you as an engineer: the workflow-vs-agent decision is an architecture decision (it determines your durability and testing strategy), not just a prompting decision. Make it explicitly, record it in an ADR (7.2), and revisit it when the feature's scope changes.


2.4 The RAG service as a bounded service#

Lesson 07.11 built the production docs_qa service: a FastAPI app owning auth, request IDs, concurrency caps, edge timeouts, SSE framing and feedback capture, with every RAG decision behind seams in docs_qa.pipeline. The architectural pattern to carry forward is bounded context: the retrieval-augmented generation capability is a service with its own contract, its own store (the vector index), its own eval suite and its own failure modes — not a function scattered across handlers.

Why bound it:

  • Different scaling profile. Retrieval is memory/IO-heavy (vector search, reranking) and benefits from different hardware and caching than the orchestration layer.
  • Different trust boundary. Retrieved content is untrusted input (12.2); isolating it behind a service means the injection surface is one audited place.
  • Different ownership. The corpus, chunking strategy and index lifecycle (05.9) change on a data-engineering cadence, not a feature cadence.
  • Reusable. The same retrieval service can feed chat, batch extraction, and eval harnesses without duplication.

The contract is the lesson-07 Answer + Trace types (07.1): the service returns grounded text with its citations and provenance, and the caller decides what to do with it. The service never calls the user-facing model directly — or if it does, that choice is explicit in its contract ("answer mode" vs "context mode").

sequenceDiagram
    participant C as Client
    participant ORCH as Orchestration
    participant RAG as Retrieval service
    participant VDB as Vector index
    participant GW as Model gateway

    C->>ORCH: POST /v1/ask (question, tenant)
    ORCH->>RAG: retrieve(query, tenant_id) — context mode
    RAG->>VDB: ANN search filtered by tenant ACL
    VDB-->>RAG: top-k chunks + scores
    RAG-->>ORCH: RetrievedChunk list with provenance
    ORCH->>GW: complete(assembled prompt) — or RAG answer mode
    GW-->>ORCH: answer text
    ORCH-->>C: answer + citations + meta
    Note over RAG,VDB: untrusted retrieved content is filtered<br/>inside the boundary, never bypassed

What this means for you as an engineer: treat retrieval as a service with a typed contract even if it starts as a function in the same deployable. The boundary is what matters; the deployment topology can start monolithic (Part 6).


2.5 Tool and integration layer: the plugin registry#

Lesson 08A.6 taught tool design; 08E.1 taught MCP for exposing tools across processes. This lesson's architectural addition is the plugin registry: a single place where every tool the model can call is registered, described, authorized and audited.

python
from __future__ import annotations  # ToolSpec and ToolResult are only named, not imported (see below)

# Conceptual shape of the product-level registry — deliberately NOT a
# copy of the earlier lessons' registries. 08A.2's "ToolRegistry" is the
# support_tools.REGISTRY dict (name -> ToolSpec) plus its execution path,
# with ToolResult(call_id, name, output, is_error); 08A.6's ToolRegistry is
# a class whose dispatch(name, args, *, idempotency_key=...) returns
# (result, is_error) — and 08A.6 itself warns the two are not
# interchangeable. This is the port-level seam 6.3's ToolsPort
# formalises; an adapter translates whichever real registry you have.
# ToolSpec: 08A.2/08A.3's tool description; ToolResult: 6.3's ports.py.
class ToolRegistry:
    def register(self, spec: ToolSpec) -> None: ...
    async def dispatch(self, name: str, args: dict, *,
                       tenant_id: str,
                       request_id: str | None = None) -> ToolResult: ...

The real registries are 08A.2's REGISTRY mapping and 08A.6's ToolRegistry; neither is async or ToolResult-shaped exactly as above, so the capstone adapters wrap them behind ToolsPort.dispatch — orchestration never imports either concrete shape.

The registry is where the architecture earns its keep:

  • One authorization point. Every call passes through policy (08A.14's policy.py pattern): risk tier, argument validation, approval gate (13A.3), rate limits.
  • One observability point. Every call emits a span with tool name, latency, outcome — the data 11A.2's metrics and 10's evals need.
  • One place to add capabilities. A new integration is a new ToolSpec, not a new code path through orchestration.
  • MCP as the boundary. When tools live in other processes or third-party servers, MCP is the wire protocol (08E.1); your registry can hold both in-process tools and MCP client proxies behind the same dispatch interface.
flowchart LR
    M["Model emits tool_call"] --> D["Registry.dispatch(name, args, ctx)"]
    D --> P{"Policy gate:<br/>risk tier, tenant allowance,<br/>rate limit, arg validation"}
    P -- "deny" --> E["ToolResult(ok=False, error)"]
    P -- "needs approval" --> A["ApprovalGate (13A.3)"]
    A -- "approved / edited" --> X["Execute tool"]
    A -- "rejected / expired" --> E
    P -- "allow" --> X
    X --> AU["Audit event written"]
    AU --> R["ToolResult returns to model"]
    E --> R

Trade-offs. A registry adds a layer of indirection; the payoff is that "what can the model do?" becomes a queryable, auditable list instead of an emergent property of the code. For a single-tool product, a registry is overkill — but the interface (a dispatch(name, args) seam) is worth keeping even then, because it is what makes tools fakeable in tests (6.2).

What this means for you as an engineer: every tool call in your system should be traceable to a registry entry with a risk tier and an owner. If you can't list your tools, you don't know your attack surface (12.1).


2.6 Model gateway and provider abstraction#

Lesson 03.11 built provider_agnostic: canonical types, adapters for OpenAI Responses, Chat Completions (covering OpenRouter), Anthropic Messages and Gemini, normalized streaming, and hooks for logging and metrics. Lesson 11C.3 added the reliability layer: circuit breakers, bulkheads, deadlines, fallback chains and the degradation ladder. The model gateway is the deployed form of those two lessons: one seam through which every model call in your system passes.

flowchart LR
    ORCH["Orchestration"] --> GW["Model gateway"]
    GW --> R1["Route: primary model + provider"]
    GW --> R2["Route: cheaper/faster model"]
    GW --> R3["Route: fallback provider"]
    R1 --> P1["OpenAI"]
    R2 --> P2["Anthropic / Gemini"]
    R3 --> P3["OpenRouter / self-hosted"]
    GW --> LOG["Trace + cost + eval hooks"]

What the gateway owns (and nothing else should):

  • Canonical request/response types — orchestration never imports a provider SDK (03.11).
  • Model aliases — code says model="support-draft", config maps that to claude-haiku-5-5 today and something else next month. Model IDs are configuration, not code (02.9, 11C.2).
  • Routing and fallback — primary → cheaper → different provider, with the degradation ladder from 11C.3, 6.3.
  • Resilience — timeouts, retries (one layer owns them: 03.8, 5.5), circuit breakers, bulkheads (11C.3).
  • Observability — every call emits a trace span with model, tokens, cost, latency, outcome (11A.1).
  • Policy hooks — data-classification rules ("this tenant's data may only go to provider X"), budget caps, safety pre-checks.

Build vs buy vs gateway-service. 03.11, 1.4 laid out the options: your own thin wrapper (what provider_agnostic is), a hosted gateway product (several exist; evaluate as of November 2026 against your data-residency and cost needs), or a self-hosted proxy such as the LiteLLM proxy used in 03.1, Part 12. The architectural requirement is the same regardless: one seam, canonical types, no provider SDK outside it.

What this means for you as an engineer: draw a hard line around model calls. If you can grep your codebase and every client.messages.create / responses.create / generate_content lives inside the gateway package, you have the pattern. Everything else calls complete().


2.7 Durable execution and human-in-the-loop engines#

Some AI workflows cannot finish inside a request or a simple job: they wait on humans (an approval that may come in two days), they span many steps with side effects that must not repeat, and they must survive deploys and crashes mid-flight. This is the domain of durable execution: workflow engines that persist every step's state so a run can pause for days and resume exactly where it left off.

What they give you:

  • Checkpointed steps. Each activity (a model call, a tool call, a human approval) is recorded; a crash resumes from the last completed step, not from the beginning.
  • First-class waits. "Wait for approval up to 7 days, then escalate" is a primitive, not a polling hack.
  • Versioning. Long-running workflows outlive deploys; engines like Temporal let you patch workflow code so in-flight runs finish on the old version while new runs use the new one.
  • Visibility. Every run is queryable: which step, which attempt, which inputs and outputs — the audit trail regulators and incident reviews ask for.

The landscape as of November 2026. Temporal is the best-known durable-execution engine, with an official Python SDK (temporalio, version 1.35.0 as tested for this path; 1.36.0 followed on 11 November 2026) where workflows are ordinary Python functions and "activities" are the side-effecting steps. Cloud-managed options exist from the major clouds, and queue-based designs (a jobs table plus workers, or a managed queue like SQS/Pub-Sub plus a state machine) cover a surprising share of needs at lower complexity. The honest advice: start with the job runner in jobs.py (Part 6); adopt a durable engine when you have a real multi-day, multi-step, human-waiting flow — typically the "act" tier features from 13A.1 and the capstone builds' approval flows.

sequenceDiagram
    participant API as App API
    participant ENG as Durable engine
    participant W as Worker
    participant H as Human reviewer
    participant DB as Store

    API->>ENG: start workflow (refund_request, args)
    ENG->>W: step 1: validate request
    W->>DB: write validation result
    ENG->>W: step 2: draft refund
    W->>DB: write draft
    ENG->>H: signal: approval required (waits up to 7d)
    H->>ENG: approve (or reject / edit)
    ENG->>W: step 3: execute refund (idempotent)
    W->>DB: write outcome
    ENG->>DB: workflow status → completed

When not to use it. Durable engines add operational weight (a server or cloud service, worker processes, the discipline of deterministic workflow code). A request-scoped agent loop that finishes in minutes does not need one; 08A.14 covers making ordinary loops reliable with budgets, policies and tracing. The trigger for durable execution is elapsed time and human waits, not step count.

What this means for you as an engineer: map your features onto the autonomy tiers from 13A.1. Anything in the "act" tier with irreversible side effects and a human wait is a durable-execution candidate; everything else is a job or a synchronous call.


2.8 Multi-tenancy#

Multi-tenancy means one deployment serves many customers (tenants) while keeping their data, prompts, caches, quotas and abuse controls separate. For AI applications it is harder than for ordinary SaaS because the model itself is a shared, stateful-cost resource: one tenant's giant document can blow your context window and your bill; one tenant's prompt-injection attempt can poison a shared cache.

The isolation options, from strongest to weakest:

Model How it works When
Silo (separate deployment per tenant) Each tenant gets its own services and stores Regulated enterprise deals, very large tenants; expensive
Pool with row-level security Shared services; every query filtered by tenant_id; Postgres RLS enforces it The default for most B2B products
Pool with schema-per-tenant Shared services; separate schemas/databases per tenant Middle ground; migration and connection-pool complexity
Bridge (shared everything, app-level filtering) Tenant scoping only in application code Prototypes and internal tools only — one missed WHERE is a breach

Lesson 06.6 owns the retrieval-side mechanics: ACL filtering patterns, payload indexes, group explosion, and the "LLM is not a security boundary" rule. Lesson 11B.3 covers cache-key tenancy (never share exact-match or semantic caches across tenants without scoping the key). Lesson 12.7 covers the supply-chain side.

The AI-specific additions this lesson owns:

  • Tenant-scoped prompts and model aliases. A tenant may be contractually limited to certain providers (12.9); your config layer must resolve "which model may this tenant use" per request, not per deployment.
  • Tenant-scoped budgets. Cost caps per tenant per day are a product feature (13A.6 owns the economics; the enforcement point is the gateway's policy hook, 2.6).
  • Tenant-scoped memory. 08B.2 memory must carry tenant (and usually user) identity end to end; a memory lookup that forgets the tenant is a data breach.
  • Noisy-neighbour control. Per-tenant concurrency caps and bulkheads (11C.3, Part 4) so one tenant's batch job cannot starve interactive traffic.
flowchart TD
    REQ["Request arrives<br/>(tenant_id resolved from session)"] --> GW["Model gateway:<br/>resolve tenant policy"]
    GW --> Q1{"Model/provider<br/>allowed for tenant?"}
    Q1 -- "no" --> ERR["Typed policy error"]
    Q1 -- "yes" --> B{"Tenant budget<br/>remaining today?"}
    B -- "exhausted" --> DEG["Degraded mode:<br/>cheaper model / cached answer"]
    B -- "ok" --> ORCH["Orchestration"]
    ORCH --> STORES["Stores: every query carries<br/>tenant_id or RLS policy"]
    ORCH --> CACHE["Caches: key includes<br/>tenant + prompt version + model"]
    ORCH --> MEM["Agent memory: scoped by<br/>tenant and user"]

What this means for you as an engineer: decide the tenancy model before you write the first query, put tenant_id in every store's primary key or RLS policy, and make the gateway resolve tenant policy per request. Retrofitting tenancy is one of the most expensive migrations in AI systems.


2.9 Configuration, prompt registry and feature flags#

Three kinds of "things that change without a code change" converge here: configuration (model aliases, endpoints, budgets, timeouts), prompts (templates, versions, aliases), and feature flags (which capabilities are on for which users). Lesson 04.10 owns the prompt library; 11C.2 owns the release pipeline. This lesson owns the architectural seam: all three resolve through one config layer that the whole system reads.

flowchart LR
    REPO["Repo: prompts/, config/*.yaml,<br/>flags definitions"] --> CI["CI: render tests,<br/>eval gates, snapshots"]
    CI --> REG["Prompt registry /<br/>config service"]
    REG --> ORCH["Orchestration"]
    REG --> GW["Model gateway"]
    FLAGS["Flag service /<br/>env config"] --> ORCH
    FLAGS --> GW

Design rules:

  • Prompts are versioned artefacts, not string literals. In 04.10 each prompt file carries a PromptSpec (its name, e.g. support/draft_reply, and an immutable semantic version), and the prompt registry resolves a name plus an alias such as production to one pinned version at request time. The resolved prompt name and version go into every trace and every response meta block (Part 4: meta.prompt_id is the PromptSpec.name). This is what makes "which prompt produced this answer?" answerable.
  • Model aliases, not model IDs, in code. model="cheap-extract" resolves through config to a concrete model per environment; the alias is the contract, the ID is the deployment detail (11C.2, 6.1).
  • Flags gate capabilities, not just UI. An AI feature flag should control the capability (retrieval on/off, tools enabled, agent mode) so you can kill a bad rollout without a deploy — and pair with a kill switch (11C.4, 1.6).
  • Secrets never in config files that ship. Keys come from the environment or a secrets manager (12.7, Part 3); config holds references, not values.
  • Budgets are config. Per-request token caps, per-tenant daily spend caps, per-feature concurrency limits — all resolve through the same layer so they can be tuned without deploys.

What this means for you as an engineer: if changing a prompt, a model or a flag requires editing code and redeploying, your config seam is in the wrong place. The test: can you ship a prompt fix at 2 a.m. without a build?


2.10 Caching layers#

Lesson 11B.3 owns the full caching stack — provider prompt caching, exact-match response caching, semantic caching, embedding caches, retrieval caches, tool-result caches, CDN caching — with economics and per-tenant keying. The architectural point for this lesson is narrower: caching is a cross-cutting layer with its own correctness rules, and AI caches are easier to get wrong than HTTP caches.

The rules that matter at the architecture level:

  • Every cache key carries its tenancy and versioning dimensions. Tenant, user ACL scope, prompt version, model alias, retrieval corpus version — a cached answer that ignores any of these is a correctness or security bug, not a hit-rate win.
  • Cached model output is still model output. A cached wrong answer is a wrong answer served faster; cached PII is a leak served faster. Invalidation must follow the data lifecycle (12.4).
  • Streaming and caching conflict by nature. You can cache the completed response and replay it, or bypass the cache for streams — 11B.3, 3.7 covers the trade-off; architecturally, decide per endpoint whether replay is acceptable (usually only for deterministic-ish, low-stakes answers).
  • Prompt-cache awareness shapes your prompts. Stable prefixes hit the provider's prompt cache (02.7, 11B.3, Part 2); your orchestration should assemble prompts so the stable part (system prompt, retrieved context template) precedes the volatile part (user message, timestamps).
flowchart TD
    REQ["Request"] --> KEY["Cache key = tenant + ACL scope<br/>+ prompt version + model alias<br/>+ normalised query"]
    KEY --> HIT{"Cache hit<br/>and fresh?"}
    HIT -- "yes" --> OUT["Return cached answer<br/>meta marks cache_hit"]
    HIT -- "no / stale" --> CALL["Model call via gateway"]
    CALL --> SAVE["Store result with TTL;<br/>invalidation follows the<br/>data lifecycle (12.4)"]
    SAVE --> OUT2["Return answer + meta"]

What this means for you as an engineer: treat each cache as a component with a key schema, a TTL policy and an invalidation story — documented, like everything else in this lesson. "We added Redis" is not a caching strategy.


2.11 Idempotency and retries across boundaries#

Every boundary in the architecture — client→API, API→gateway, gateway→provider, orchestrator→tool, worker→store — can deliver an operation twice or lose the response after the work succeeded. Lesson 01B.9 owns the mechanics (idempotency keys, backoff, deadlines); 03.8 owns the LLM-specific error taxonomy and the "one layer owns retries" rule. The architectural addition: idempotency is a property of the operation, designed into the API and the job model, not a retry detail.

The patterns:

  • Idempotency keys on every mutating endpoint. POST /v1/jobs, POST /v1/refunds, POST /v1/messages accept a client-supplied Idempotency-Key; the server stores (key, tenant, request_hash) and replays the stored response on duplicate submission — and rejects the key when it arrives with a different body, because silently returning the first job for a different request is the confused-deputy bug the pattern exists to prevent (this is what jobs.py implements in miniature). Stripe popularised the pattern; it is now table stakes for any API with side effects.
  • Natural idempotency where possible. PUT semantics, "set state to X" operations, and lookups are naturally idempotent — prefer them over "do thing Y" operations that accumulate.
  • Retries owned at one layer per boundary. The provider SDK retries inside the gateway; your orchestrator does not also retry the gateway call; your client does not retry the API call blindly. Each boundary has exactly one retry owner with its own budget (03.8, 5.5).
  • At-least-once delivery + idempotent consumers. Queues redeliver; workers must tolerate seeing the same job twice. The claim-check pattern (job row with status transitions) makes this safe: a second delivery finds the job already running or succeeded and no-ops.
  • Side effects after the model call need their own idempotency. The model call itself is read-only-ish (it costs money but changes nothing); the tool call it triggers — create ticket, issue refund — is the side effect that must be idempotent at the tool layer (08A.6, 4.3).
sequenceDiagram
    participant C as Client
    participant API as App API
    participant DB as Job store
    participant W as Worker

    C->>API: POST /v1/jobs (Idempotency-Key k, body B)
    API->>DB: lookup (tenant, k)
    alt first submission
        DB-->>API: no existing job
        API->>DB: insert job, request_hash = H(kind + B)
        API-->>C: 202 {job_id, status: queued}
    else duplicate, same body
        DB-->>API: existing job, hash matches
        API-->>C: 202 {same job_id} — replay, no new work
    else duplicate, different body
        DB-->>API: existing job, hash mismatch
        API-->>C: 409 — key reused with a different request
    end
    W->>DB: claim_next_queued (atomic)
    W->>W: run handler — side effects idempotent
    W->>DB: store result, status -> succeeded
python
# The contract, in one line: same key + same body → same response,
# forever (or until the stored response expires).
# jobs.py in Part 6 implements this for the job runner.

What this means for you as an engineer: when you design an endpoint or a job, ask "what happens if this runs twice?" before "how do I retry it?". The answer should be "nothing bad" — that is idempotency. Everything else is mechanics.

2.12 The transactional outbox: do not write state and enqueue work separately#

The job diagram in 2.2 shows the API inserting a job row and then enqueueing the job. That is a dual write: two systems (your database and your queue) must both succeed, and nothing makes them atomic. If the process dies between the two, you get a job row that no worker will ever see (a lost job) or, in the reverse order, a queued message pointing at a row that was never committed. The same hazard appears whenever "save the approval decision" must be followed by "execute the refund" or "emit the webhook".

Two standard fixes, both small:

Pattern How it works When to use it
The database is the queue The job row is the work item: workers claim queued rows with SELECT ... FOR UPDATE SKIP LOCKED (the claim_next_queued port method in 6.3). There is no second system to disagree with The default for most AI products: one Postgres, modest throughput, no extra infrastructure. This is what jobs.py models
Transactional outbox In one database transaction, write the state change and a row in an outbox table describing the message to send. A separate relay process reads unsent outbox rows, publishes them to the broker or webhook, and marks them sent When you must publish to an external broker, send webhooks or call another service after a state change. Delivery is at-least-once, so consumers must be idempotent (2.11)

Two details that matter. First, the relay can crash after publishing and before marking the row sent, so a message may be delivered twice; the idempotent consumer from 2.11 absorbs that. Second, an outbox row carries tenant_id, request_id and the event type, so the same table doubles as your audit source (3.6). The "job outbox" in the support copilot's state shape (8.4) refers to this idea: an approved refund action should be recorded and scheduled in the same transaction, so an approval can never exist without its action being scheduled, or the reverse. The keyless capstone builds model it with in-memory job records and the claim path above; a literal outbox table is what you add when you move to Postgres and an external broker.


Part 3: State and storage#

Deep-dive

3.1 The model is stateless; your system is not#

Lesson 02.7, Part 3 proved the model forgets everything between calls. Every piece of "memory" an AI product appears to have is state your system owns and re-supplies: conversation history re-sent each turn, retrieved documents fetched per query, user preferences loaded into the prompt, job progress polled from a table. This inversion — the model is the stateless compute, your stores are the state — is the single most important architectural fact about AI applications.

3.2 Inventory: what state an AI product holds#

State Examples Lifetime Sensitivity
Conversation state Messages, turns, pending clarifications Session to months (user-visible history) High — user content
User memory Preferences, facts the user told the assistant Persistent, user-controlled High — personal data (12.4)
Documents / corpus Uploaded files, parsed chunks, source metadata Until deleted or re-ingested Varies — often confidential
Vectors / index state Embeddings, index versions, aliases Until re-embedded Derived from documents — same sensitivity
Job state Queued/running/finished work, results, progress events Hours to days Contains user content
Audit / event log Who did what, model+prompt versions, tool calls, approvals Retention-policy bound (months–years) High — security-relevant
Feedback Thumbs, edits, "what was wrong" labels, eval cases derived Indefinite (it's training data for your evals) Contains user content
Caches Exact/semantic response caches, prompt-cache warmth Minutes to days Same as the answers they hold
Config state Prompt versions, flags, model aliases, budgets Per environment Low, but changes behaviour

3.3 The storage decision framework#

You will not store all of this in one technology. The decision per state type:

Need Default choice Alternative when...
Conversation messages, users, jobs, audit, feedback Relational (Postgres) — rows, JSONB for flexible payloads, strong consistency for job state machines Document store when messages are deeply nested per-aggregate and you never query across them
Vectors + metadata filtering Postgres + pgvector for most products (one store, joins with your relational data, ACID); dedicated vector DB (Qdrant, Pinecone, Chroma, Elasticsearch/OpenSearch kNN — verify current versions per 06.5) when scale, latency or feature needs exceed it 06.5's decision table is the authority
Original files, generated artifacts, large blobs Object storage (S3-compatible) with metadata in Postgres Never in the relational DB
Event log / audit Append-only table in Postgres first; event-sourcing infrastructure only if the domain demands it (3.6) Kafka/Kinesis-class log for very high volume or multi-consumer replay
Ephemeral coordination Redis for locks, rate-limit counters, short-lived cache —

3.4 Choosing a store for each kind of state#

A worked allocation for a typical B2B AI product (support copilot scale):

  • Postgres: users, tenants, conversations, messages (JSONB payloads), jobs, job_events, audit_log, feedback, prompt_aliases (or the registry's store), idempotency_keys. One database, one backup story, one RLS policy surface.
  • pgvector in the same Postgres: document_chunks(tenant_id, doc_id, chunk_index, content, embedding vector(1536), metadata JSONB) with an HNSW index — the dimension depends on your embedding model (06.1 owns model choice).
  • Object storage: uploaded PDFs/exports, generated reports, voice recordings if any.
  • Redis (optional): rate-limit counters, short-TTL exact cache, pub/sub for live job progress to connected clients.

3.5 Data lifecycle and deletion#

AI products accumulate derived copies of user data — chunks, embeddings, cached answers, eval cases, fine-tuning exports, logs, traces — and a deletion request must reach all of them. Lesson 12.4 maps the leak points; 05.9 owns the ingestion-side lifecycle. The architecture requirements:

  • A deletion registry. Every store that can hold user-derived data registers a delete(tenant_id, user_id) hook. When a user is deleted, the registry runs all hooks and records completion — this is the only way to prove erasure covered the vector index and the caches, not just the messages table.
  • Tombstones over silent drops. Deleting a document should leave a tombstone (doc ID + deletion timestamp) so re-ingestion doesn't resurrect it and so "was this ever indexed?" is answerable.
  • Retention as configuration. Audit logs, job history, feedback and caches each have a TTL; the config layer (2.9) owns the values so legal can change them without a deploy.
  • Backups honour deletion. A backup that restores deleted PII is a leak with a delay; your deletion runbook (11C.4's erasure runbook pattern) must state how backups expire or are scrubbed.

3.6 Event sourcing for audit#

Event sourcing means storing events ("user asked X", "model Y answered Z with prompt v3", "tool W was called with args A", "human approved") as the primary record, and deriving current state by replaying them. You don't need it everywhere, but AI audit trails benefit enormously: "why did the system do that?" is answered by the event log, not by reconstructing from mutable rows.

The pragmatic version for most products: an append-only audit_events table written at each decision point (orchestration choice, model call metadata, tool dispatch, approval decision, guardrail trip) with request_id, tenant_id, actor, event_type, payload, created_at. Full event sourcing — where the event log is the state — is justified when you need temporal queries ("what did the system believe on March 3rd?"), multi-consumer replay, or regulatory reconstruction. 11C.4 owns the incident-side use; 12.10 the compliance side.

3.7 Conversation state specifically#

The highest-volume state in most AI products. The design questions:

  • Who owns the transcript — client or server? Server-side (your store) enables cross-device history, audit, eval capture and memory features; client-side (send full history each call, as the raw APIs require anyway) is simpler but loses you the product features. Most products do server-side storage and re-send the relevant window each call — the store is the source of truth, the wire carries the context (02.7, Part 3.3).
  • What gets stored vs what's ephemeral? Store messages and metadata; don't store provider-internal reasoning unless you need it for debugging (and then with retention limits — reasoning can contain sensitive scratch work).
  • Branching and edits. "Edit and resend" (13A.2) implies conversation trees, not linear history; model messages as a tree or store sibling branches.
  • Context-window budgeting. You can't store-and-send everything forever; 04.7 owns the strategies (summarisation, sliding windows, retrieval-augmented history). Architecturally, the conversation service should expose "give me the context for turn N" as an operation, not make every caller reimplement windowing.

What this means for you as an engineer: list your state types, assign each a store and a lifecycle (including deletion), and put tenant_id/user_id on everything. The store choices will feel boring — that is the point. AI novelty lives above the storage layer.


Part 4: API design for AI features#

Deep-dive

4.1 The contract must survive model changes#

Your public API is a contract with your clients; the model behind it is a dependency that will change — new versions monthly, deprecations, capability differences, price changes. The API design rules that make the contract durable:

  • Version the API, not the model. /v1/ask is your contract; model="support-draft" inside it resolves to whatever the gateway currently maps that alias to. Clients never see a model ID unless you deliberately expose one in meta.
  • meta blocks carry provenance. Every AI response includes a meta object: request_id, model_alias and resolved model_id, prompt_id/prompt_version, finish_reason-equivalent, usage (tokens in/out/cached), latency_ms, and degraded: true when a fallback fired. This is the difference between "the answer was wrong" and "the answer came from the fallback model with prompt v7" — the debugging and billing data your operators and your clients both need.
  • Additive changes only within a version. New optional fields in responses, new optional parameters in requests. Removing or retyping a field is a new version. AI APIs evolve fast; clients pinned to /v1 should never break because you swapped gpt-6-luna for gpt-6.1-terra.
  • Deprecation is a process, not an event. Sunset headers, migration windows, and meta.api_version in responses so clients can detect they're on an old version (11C.2 covers the release mechanics).

4.2 Errors as data#

A model call has failure modes an HTTP status code can't express: the model refused, the output was truncated, a guardrail blocked it, retrieval found nothing, the answer is low-confidence. Lesson 13A.4 owns the user-facing mapping; the API-level rule is: the HTTP status says whether the request succeeded; a typed error/outcome field in the body says what happened to the task.

json
{
  "answer": "I couldn't find that in the handbook...",
  "outcome": "insufficient_evidence",
  "meta": {"request_id": "req_...", "model_id": "...", "retrieval_hits": 0}
}

vs a transport failure:

json
{"error": {"type": "provider_unavailable", "retryable": true, "retry_after_ms": 2000}}

The taxonomy: 2xx + outcome for completed-but-imperfect results (refusal, low confidence, partial); 4xx/5xx + typed error for request/transport failures. Never return 200 with an empty body for a failure, and never return 500 for "the model said no".

4.3 Long outputs: pagination and jobs#

Model outputs can be long (a generated report, a full contract review). For synchronous endpoints, cap output length and offer continuation (continue_from token or message ID) rather than unbounded streams. For anything beyond ~a screenful or ~30 s, use the job pattern (2.2): submit → poll/webhook → fetch paginated result. Paginate results, not tokens — a client asking for "page 2" of an answer wants the next section, not tokens 800–1600.

4.4 Webhooks for async completion#

When jobs finish, don't make clients poll forever. Webhooks (HTTP callbacks to a client-registered URL) are the standard: POST to their endpoint with the job result, signed (HMAC) so they can verify it came from you. Design rules: sign payloads, include event_id + event_type for idempotent processing on their side, retry with backoff, and document the verification recipe. This is ordinary webhook hygiene — the AI-specific part is that the payload contains model output, so treat it as sensitive in transit and at rest on their side.

4.5 Rate limits and quotas exposed to clients#

Rate limiting protects you; exposing it protects the client relationship. Return 429 with Retry-After (the header semantics are in 03.8), document per-tier limits, and include quota state in meta for expensive endpoints (quota: {requests_remaining, resets_at}). For AI specifically, rate limits are also cost limits — a per-tenant token budget enforced at the gateway is the same mechanism pointed at your COGS.

4.6 SDK ergonomics and OpenAPI#

Your FastAPI app generates OpenAPI automatically (01B.7); keep it accurate — response models, error envelopes, examples — because SDK generators and docs sites consume it. For AI endpoints specifically: document the meta contract, the event stream format (with an example SSE session), the idempotency-key semantics, and the webhook signature scheme. A generated SDK that hides meta is a bug; clients need provenance.

What this means for you as an engineer: the API contract is where model volatility meets client stability. Version the API, hide the model behind aliases, put provenance in meta, type your outcomes, and treat every mutating endpoint as idempotent. Clients should be able to upgrade models for months without noticing — except in meta.model_id, where noticing is the point.


Part 5: Non-functional budgets#

5.1 Budgets are architecture, not optimisation#

Every AI feature has implicit budgets — how long the user waits, what the request costs, how often it may fail, how wrong it may be — and implicit budgets become incidents. Making them explicit is an architecture activity: you allocate a budget across the stages of a request, enforce it in code, and measure it against SLOs (11A.2 owns SLO mechanics).

The five budget dimensions for an AI request:

Dimension Question Typical allocation concern
Latency How long until first useful output / final result? TTFT vs total; where the time goes (retrieval, prompt size, model speed, retries)
Cost What does one request/task cost, at p50 and p95? Input tokens dominate for RAG; output for generation; retries multiply both
Availability What fraction of requests succeed end-to-end? Provider outages, rate limits, guardrail blocks, timeouts — each is a failure mode
Quality How good is the answer, and how wrong is acceptable? Eval scores, groundedness, task success — owned by 10 and product metrics by 13A.6
Safety What must never happen? Policy violations, PII leaks, injection success — owned by 12

5.2 Allocating a latency budget: a worked example#

Take a RAG-with-tools support answer (the 13B.2 shape). Budget: p95 total latency ≤ 12 s, TTFT ≤ 2.5 s (perceived-speed thresholds are in 13A.2).

Stage p95 budget Notes
Auth + rate limit + request ID 50 ms Middleware; reject fast
Conversation load + context assembly 150 ms Store reads; prompt-cache-friendly ordering
Retrieval (embed + search + rerank) 800 ms Vector search is fast; reranking is the wildcard
Safety pre-checks (injection screen, PII) 200 ms Guardrail latency is a real cost — measure it
Model call (TTFT portion) 1,300 ms Depends on model tier; reasoning models blow this. The five rows down to here add up to 2,500 ms, the TTFT budget
Model call (rest of generation) 6,000 ms Streaming hides most of it; budget the total
Tool call (if invoked) 1,500 ms External APIs vary wildly; timeout + degrade
Post-processing (citations, safety scan, meta) 300 ms Output guardrails, citation linking
SSE framing + network 500 ms Depends on client distance
Buffer 1,200 ms For retries within a stage, not whole-request retries
Total 12,000 ms Stage budgets sum to 10,800 ms plus the 1,200 ms buffer. A request with no tool call has about 1.5 s of slack. Leaves the user in "acceptable for complex task" territory

Two rules this table teaches:

  1. Budgets are per-stage, and stages are measured separately. "The API is slow" is not actionable; "reranking p95 is 1.8 s against an 800 ms budget" is.
  2. Retries consume the buffer, not the stage. A stage that retries internally must fit its retries inside its own budget — which is why one-layer retry ownership (2.11) matters for latency, not just correctness.

5.3 Cost budgets per request and per tenant#

Cost budgeting is the same exercise with dollars. For a RAG answer: cost = (input_tokens × input_price) + (cached_input × cached_price) + (output_tokens × output_price) + retrieval_cost + tool_costs. 11B.1 owns the levers; 13A.6 owns the product economics. The architecture-level rules:

  • Every model call emits cost telemetry through the gateway (2.6) so per-request, per-feature and per-tenant cost is a query, not an estimate.
  • Caps are enforced, not hoped for. max_tokens, context budgets, per-tenant daily spend caps — enforced at the gateway/orchestration layer, surfaced to the user as graceful degradation (13A.4) when hit.
  • The expensive paths are visible. Agent loops multiply cost by step count; map-reduce multiplies by document count. Budget the loop, not the call (08A.2, 1.4).

5.4 SLOs for AI features#

An SLO (service level objective) is a target on a measurable indicator; an SLA is the contract consequence. 11A.2 owns the machinery. The AI-specific SLO set for a product like the support copilot:

Indicator SLO example Why it matters
Availability (requests completing without transport error) 99.5% monthly Baseline reliability
TTFT p95 ≤ 2.5 s Perceived speed
Total latency p95 ≤ 12 s for chat; ≤ 5 min for jobs User patience per shape
Task success rate (eval + acceptance) ≥ target per feature Quality is an SLO too
groundedness / citation accuracy ≥ threshold on sampled evals The AI-specific quality SLO
safety violation rate < 0.1% (and zero for defined-critical classes) Non-negotiable floor
cost per successful task ≤ $X Unit economics as an operational metric

What this means for you as an engineer: write the budget table for your feature before building it, put the numbers in config (2.9), emit the telemetry to measure them (11A.1/11A.2), and review them when the model or prompt changes — because a "free" model upgrade that doubles latency is a budget breach, not a win.


Part 6: Monolith first#

6.1 The decision#

The layered architecture in Part 1 describes logical layers, not deployables. The default correct answer for a new AI product is one deployable: a modular monolith where the layers are packages with clean interfaces. Split into services only when a specific pressure forces it.

Split when... Keep monolith when...
A component needs different scaling (vector search CPU/memory profile vs API) Team is small; deployment complexity dominates
A component has a different availability requirement (batch workers vs interactive API) Latency between components would dominate (in-process calls are ~free)
A component is owned by a different team with different release cadence You don't yet know the right boundaries — premature splitting guesses wrong
Regulatory isolation demands it (silo tenancy, data residency) Cost of running N services > benefit
A component is a managed service you don't operate anyway (provider APIs, managed vector DB) — this isn't a split, it's an external dependency

The failure mode to avoid is distributed monolith: multiple deployables that must deploy together anyway, paying network and ops costs for none of the independence benefits. If you can't articulate why a boundary must be a network hop, keep it in-process.

6.2 Ports and adapters inside the monolith#

The monolith's discipline is ports and adapters (a.k.a. hexagonal architecture): business logic depends on ports (small interfaces), and adapters implement them (real provider SDK, real Postgres, real vector store — or fakes for tests). This is exactly the pattern 07.1 used for docs_qa (LLM callable, retriever contract) and 03.10 teaches for testability. The ports for a typical AI app:

  • ModelPort — complete(messages) → response; implemented by the provider_agnostic gateway adapter in production, FakeModel/ScriptedModel in tests.
  • RetrieverPort — retrieve(query, tenant) → chunks; implemented by docs_qa/pgvector adapter or fake.
  • ToolsPort — dispatch(name, args, ctx) → result; implemented by the ToolRegistry (08A.2/08A.3).
  • StorePort — conversation/message/job/audit persistence; implemented by Postgres adapter or InMemoryStore. It extends a narrower JobStorePort (job records plus the atomic claim_next_queued) that JobRunner codes against, so the runner never sees methods it doesn't need — and a StorePort can always drive a runner, but a bare job store cannot drive the app.
  • Clock/Sleeper — time and waiting, injectable so tests and demos control them (the jobs.py pattern).

The payoff: the whole application runs in tests and demos with zero network, zero keys, zero services — which is exactly how this lesson's code works, and how the capstones' keyless paths (13B.2–13B.5) will run.

6.3 ai_product/ports.py — the interfaces#

This is the file the rest of the package codes against. Pure standard library: typing.Protocol, dataclasses. Nothing here imports FastAPI, a provider SDK, or a database driver — that is the point.

python
# ai_product/ports.py
"""Ports: the seams every ai_product component codes against.

A port is a small interface (typing.Protocol). Production adapters live in
your app (provider_agnostic for ModelPort, docs_qa/pgvector for
RetrieverPort, ToolRegistry for ToolsPort, Postgres for StorePort).
Tests and demos use the in-memory fakes in app.py and jobs.py.

Nothing in this file imports a provider SDK, FastAPI or a database driver.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Protocol, runtime_checkable


# ---------------------------------------------------------------------------
# Canonical message and response shapes (provider-neutral, like 03.11's types)
# ---------------------------------------------------------------------------

@dataclass(frozen=True)
class Message:
    """One chat message. Provider adapters translate this to wire format."""
    role: str            # "system" | "user" | "assistant" | "tool"
    content: str
    name: str | None = None        # tool name for role="tool"
    tool_call_id: str | None = None


@dataclass(frozen=True)
class Completion:
    """What a model call returns. Deliberately minimal: orchestration adds
    citations, provenance and meta on top."""
    text: str
    model_id: str
    stop_reason: str = "end_turn"   # normalized: "end_turn" | "max_tokens" | "tool_use" | "refusal"
    usage: dict[str, int] = field(default_factory=dict)
    raw: Any = None                  # provider-native object, for debugging only


@dataclass(frozen=True)
class RetrievedChunk:
    """One retrieval result with provenance — the citation unit."""
    chunk_id: str
    doc_id: str
    text: str
    score: float
    metadata: dict[str, Any] = field(default_factory=dict)


@dataclass(frozen=True)
class ToolResult:
    """What a tool call returns to the model. `ok=False` is a normal outcome
    the model can read and react to — not an exception (08A.6, 3.4)."""
    ok: bool
    output: Any = None
    error: str | None = None


# ---------------------------------------------------------------------------
# Ports
# ---------------------------------------------------------------------------

@runtime_checkable
class ModelPort(Protocol):
    """One seam to every model. Implemented by the provider_agnostic gateway
    in production; by FakeModel/ScriptedModel in tests."""

    async def complete(
        self,
        messages: list[Message],
        *,
        model_alias: str | None = None,
        max_output_tokens: int | None = None,
        request_id: str | None = None,
    ) -> Completion: ...

    async def stream(
        self,
        messages: list[Message],
        *,
        model_alias: str | None = None,
        request_id: str | None = None,
    ) -> Any:
        """Async iterator of canonical stream events. `Any` here keeps this
        file SDK-free; the concrete type is provider_agnostic's StreamEvent."""
        ...


@runtime_checkable
class RetrieverPort(Protocol):
    """The bounded retrieval service (2.4). Tenant-scoped by contract."""

    async def retrieve(
        self,
        query: str,
        *,
        tenant_id: str,
        k: int = 5,
    ) -> list[RetrievedChunk]: ...


@runtime_checkable
class ToolsPort(Protocol):
    """The tool/integration layer (2.5). One dispatch seam; the registry
    enforces policy, approvals and audit inside the implementation."""

    async def dispatch(
        self,
        name: str,
        args: dict[str, Any],
        *,
        tenant_id: str,
        request_id: str | None = None,
    ) -> ToolResult: ...

    def list_tools(self) -> list[dict[str, Any]]:
        """Tool specs for the model — names, descriptions, JSON schemas."""
        ...


@runtime_checkable
class JobStorePort(Protocol):
    """Persistence for jobs only — the narrow seam JobRunner codes
    against, so the runner never sees conversation or audit methods it
    doesn't need. `claim_next_queued` is the multi-worker claim: a
    Postgres adapter implements it as SELECT ... FOR UPDATE SKIP LOCKED
    (or an UPDATE ... WHERE status='queued' ... RETURNING) so two workers
    can never claim the same job."""

    async def save_job(self, job: "JobRecord") -> None: ...
    async def get_job(self, job_id: str, tenant_id: str) -> "JobRecord | None": ...
    async def find_job_by_key(self, idempotency_key: str, tenant_id: str) -> "JobRecord | None": ...
    async def claim_next_queued(self) -> "JobRecord | None": ...


@runtime_checkable
class StorePort(JobStorePort, Protocol):
    """Persistence for conversations, jobs and audit. Tenant-scoped.
    Extends JobStorePort, so anything that is a StorePort can drive a
    JobRunner — but the runner only depends on the narrow port."""

    async def append_message(
        self,
        conversation_id: str,
        tenant_id: str,
        message: Message,
        *,
        request_id: str | None = None,
    ) -> None: ...

    async def get_messages(
        self,
        conversation_id: str,
        tenant_id: str,
        *,
        limit: int = 100,
    ) -> list[Message]: ...

    async def audit(self, event: "AuditEvent") -> None: ...


@dataclass(frozen=True)
class JobRecord:
    """A unit of async work. The store owns the state machine; jobs.py drives it."""
    job_id: str
    tenant_id: str
    kind: str
    status: str                    # "queued" | "running" | "succeeded" | "failed" | "cancelled"
    payload: dict[str, Any]
    idempotency_key: str | None = None
    request_hash: str | None = None  # sha256 of canonical kind+payload; idempotent replay compares it (2.11)
    result: Any = None
    error: str | None = None
    created_at: float = 0.0
    updated_at: float = 0.0
    attempts: int = 0


@dataclass(frozen=True)
class AuditEvent:
    """One append-only audit record (3.6)."""
    event_id: str
    tenant_id: str
    actor: str                     # "user", "system", "model", "tool:<name>", "human:<id>"
    event_type: str
    request_id: str | None
    payload: dict[str, Any]
    created_at: float

6.4 ai_product/jobs.py — the in-process job runner#

The minimal async-job pattern from 2.2, complete enough to run: states, idempotency keys, injectable clock, registered handlers. Pure standard library — run it and see real output.

python
# ai_product/jobs.py
"""An in-process job runner: states, idempotency keys, injectable clock.

This is the minimal version of the async-job pattern (2.2). Production
replaces InProcessJobStore with a Postgres-backed StorePort and the
in-process loop with a real queue/worker — the states, transitions and
idempotency semantics stay identical.

Run the demo:  uv run python -m ai_product.jobs
"""

from __future__ import annotations

import asyncio
import hashlib
import itertools
import json
import time
import uuid
from dataclasses import dataclass, replace
from typing import Any, Awaitable, Callable

from .ports import JobRecord, JobStorePort

# Job handler signature: (payload, ctx) -> result. Handlers must be safe to
# retry — a job that fails mid-flight may run again (at-least-once, 2.11).
JobHandler = Callable[[dict[str, Any], "JobContext"], Awaitable[Any]]


class JobError(Exception):
    """A job failure that should mark the job 'failed' (not retried here)."""


@dataclass
class JobContext:
    """What a handler can see: identity, a progress hook, the clock."""
    job_id: str
    tenant_id: str
    clock: Callable[[], float]
    progress: Callable[[str, dict[str, Any]], Awaitable[None]]


class InProcessJobStore:
    """JobStorePort, in memory. Same semantics a Postgres adapter must
    preserve: idempotency-key lookup, tenant scoping, and an atomic claim
    (production: SELECT ... FOR UPDATE SKIP LOCKED)."""

    def __init__(self, *, clock: Callable[[], float] = time.time) -> None:
        self._jobs: dict[str, JobRecord] = {}
        self._by_key: dict[tuple[str, str], str] = {}   # (tenant, key) -> job_id
        self._lock = asyncio.Lock()
        self._clock = clock

    async def save_job(self, job: JobRecord) -> None:
        async with self._lock:
            self._jobs[job.job_id] = job
            if job.idempotency_key is not None:
                self._by_key[(job.tenant_id, job.idempotency_key)] = job.job_id

    async def get_job(self, job_id: str, tenant_id: str) -> JobRecord | None:
        job = self._jobs.get(job_id)
        return job if job and job.tenant_id == tenant_id else None

    async def find_job_by_key(self, key: str, tenant_id: str) -> JobRecord | None:
        job_id = self._by_key.get((tenant_id, key))
        return await self.get_job(job_id, tenant_id) if job_id else None

    async def claim_next_queued(self) -> JobRecord | None:
        """The worker seam (JobStorePort): atomically pick the oldest queued
        job, mark it running (attempts += 1) and return it — None when the
        queue is empty. The lock makes select+update atomic in-process; a
        Postgres adapter does the same in one statement so two workers can
        never claim the same job."""
        async with self._lock:
            queued = [j for j in self._jobs.values() if j.status == "queued"]
            if not queued:
                return None
            job = min(queued, key=lambda j: j.created_at)
            claimed = replace(job, status="running",
                               updated_at=self._clock(),
                               attempts=job.attempts + 1)
            self._jobs[job.job_id] = claimed
            return claimed


class JobRunner:
    """Drives registered handlers through the job state machine.

    States: queued -> running -> succeeded | failed | cancelled.
    A handler exception -> failed (this runner does not auto-retry; retries
    are the queue/worker layer's job in production — see 2.11).
    """

    def __init__(
        self,
        store: JobStorePort,
        *,
        clock: Callable[[], float] = time.time,
    ) -> None:
        self.store = store
        self.clock = clock
        self._handlers: dict[str, JobHandler] = {}
        self._events: dict[str, list[dict[str, Any]]] = {}
        self._ids = itertools.count(1)

    def register(self, kind: str, handler: JobHandler) -> None:
        self._handlers[kind] = handler

    @staticmethod
    def _request_hash(kind: str, payload: dict[str, Any]) -> str:
        """Canonical fingerprint of the submission — what the idempotency
        contract (2.11) compares on replay. sort_keys makes dict ordering
        irrelevant; default=str tolerates values JSON can't serialise."""
        canonical = json.dumps({"kind": kind, "payload": payload},
                               sort_keys=True, separators=(",", ":"),
                               default=str)
        return hashlib.sha256(canonical.encode()).hexdigest()

    async def submit(
        self,
        kind: str,
        payload: dict[str, Any],
        *,
        tenant_id: str,
        idempotency_key: str | None = None,
    ) -> JobRecord:
        """Submit a job. Same (tenant, key, request_hash) returns the
        existing job; same key with a DIFFERENT body raises JobError —
        silently replaying it is the confused-deputy bug idempotency
        exists to prevent (2.11)."""
        if kind not in self._handlers:
            raise JobError(f"no handler registered for kind {kind!r}")
        request_hash = self._request_hash(kind, payload)
        if idempotency_key is not None:
            existing = await self.store.find_job_by_key(idempotency_key, tenant_id)
            if existing is not None:
                if existing.request_hash not in (None, request_hash):
                    raise JobError(
                        "idempotency key already used with a different request")
                return existing
        now = self.clock()
        job = JobRecord(
            job_id=f"job_{uuid.uuid4().hex[:12]}",
            tenant_id=tenant_id,
            kind=kind,
            status="queued",
            payload=payload,
            idempotency_key=idempotency_key,
            request_hash=request_hash,
            created_at=now,
            updated_at=now,
        )
        await self.store.save_job(job)
        self._events[job.job_id] = []
        return job

    async def events(self, job_id: str) -> list[dict[str, Any]]:
        """Progress events for SSE/status endpoints."""
        return list(self._events.get(job_id, []))

    async def _emit(self, job_id: str, kind: str, data: dict[str, Any]) -> None:
        self._events.setdefault(job_id, []).append(
            {"seq": len(self._events.get(job_id, [])) + 1,
             "type": kind, "at": self.clock(), "data": data}
        )

    async def run_one(self) -> bool:
        """Claim and run the oldest queued job once. Returns False when the
        queue is empty — this is the loop body a worker calls repeatedly."""
        job = await self.store.claim_next_queued()
        if job is None:
            return False
        await self._emit(job.job_id, "status", {"status": "running"})
        ctx = JobContext(
            job_id=job.job_id,
            tenant_id=job.tenant_id,
            clock=self.clock,
            progress=lambda k, d: self._emit(job.job_id, k, d),
        )
        try:
            result = await self._handlers[job.kind](job.payload, ctx)
        except Exception as exc:  # noqa: BLE001 — job boundary: record, don't crash worker
            await self._transition(job, "failed", error=f"{type(exc).__name__}: {exc}")
            await self._emit(job.job_id, "status", {"status": "failed", "error": str(exc)})
            return True
        await self._transition(job, "succeeded", result=result)
        await self._emit(job.job_id, "status", {"status": "succeeded"})
        return True

    async def run_all(self) -> int:
        n = 0
        while await self.run_one():
            n += 1
        return n

    async def _transition(
        self,
        job: JobRecord,
        status: str,
        *,
        result: Any = None,
        error: str | None = None,
    ) -> None:
        """The ONLY place the runner changes status — the state machine in
        one method, for the terminal transitions (claim_next_queued owns
        queued -> running). Reads the latest record through the port —
        the caller's `job` may be stale — and writes through save_job."""
        current = await self.store.get_job(job.job_id, job.tenant_id)
        if current is None:
            return
        updated = replace(
            current, status=status,
            result=result if result is not None else current.result,
            error=error if error is not None else current.error,
            updated_at=self.clock())
        await self.store.save_job(updated)


# ---------------------------------------------------------------------------
# Demo — fake clock, fake work, real state machine
# ---------------------------------------------------------------------------

async def _demo() -> None:
    now = [1_000.0]
    store = InProcessJobStore(clock=lambda: now[0])
    runner = JobRunner(store, clock=lambda: now[0])

    async def summarize(payload: dict[str, Any], ctx: JobContext) -> dict[str, Any]:
        """Fake 'extract invoice fields' job: emits progress, 'works' for
        simulated seconds, returns a result. Fails on demand for the demo."""
        doc = payload["document"]
        await ctx.progress("parse", {"bytes": len(doc)})
        now[0] += 2.5                       # simulated work; fake clock
        if payload.get("explode"):
            raise JobError("parser choked on page 3")
        await ctx.progress("extract", {"fields": ["vendor", "total", "date"]})
        return {"vendor": "Acme Ltd", "total": "123.45", "currency": "USD"}

    runner.register("extract_invoice", summarize)

    # 1. Submit twice with the same idempotency key -> ONE job.
    j1 = await runner.submit("extract_invoice",
                             {"document": "INV-0042 ..."},
                             tenant_id="t_acme", idempotency_key="inv-0042")
    j2 = await runner.submit("extract_invoice",
                             {"document": "INV-0042 ..."},
                             tenant_id="t_acme", idempotency_key="inv-0042")
    print(f"submit x2 same key -> same job? {j1.job_id == j2.job_id} ({j1.job_id})")

    # 2. A different tenant with the same key is a DIFFERENT job.
    j3 = await runner.submit("extract_invoice",
                             {"document": "INV-0042 ..."},
                             tenant_id="t_globex", idempotency_key="inv-0042")
    print(f"other tenant, same key -> different job? {j1.job_id != j3.job_id}")

    # 2b. Same key + DIFFERENT body -> rejected, not silently replayed.
    try:
        await runner.submit("extract_invoice", {"document": "DIFFERENT doc"},
                            tenant_id="t_acme", idempotency_key="inv-0042")
        print("same key, different body -> NOT rejected (bug)")
    except JobError as exc:
        print(f"same key, different body -> rejected: {exc}")

    # 3. Run the queue; watch a success and a failure.
    bad_job = await runner.submit("extract_invoice",
                                  {"document": "bad scan", "explode": True},
                                  tenant_id="t_acme", idempotency_key="inv-bad")
    ran = await runner.run_all()
    for jid, tenant in ((j1.job_id, "t_acme"), (j3.job_id, "t_globex")):
        job = await store.get_job(jid, tenant)
        print(f"{job.job_id}: {job.status} attempts={job.attempts} "
              f"result={job.result} error={job.error}")
    bad = await store.get_job(bad_job.job_id, "t_acme")
    print(f"{bad.job_id}: {bad.status} error={bad.error}")
    print(f"events recorded for {j1.job_id}: {len(await runner.events(j1.job_id))}")
    print(f"jobs run this pass: {ran}")


if __name__ == "__main__":
    asyncio.run(_demo())
Output · job IDs are random per run8 lines
submit x2 same key -> same job? True (job_83d8fb6d5b6f)
other tenant, same key -> different job? True
same key, different body -> rejected: idempotency key already used with a different request
job_83d8fb6d5b6f: succeeded attempts=1 result={'vendor': 'Acme Ltd', 'total': '123.45', 'currency': 'USD'} error=None
job_520af13a489e: succeeded attempts=1 result={'vendor': 'Acme Ltd', 'total': '123.45', 'currency': 'USD'} error=None
job_c4a72f2813a2: failed error=JobError: parser choked on page 3
events recorded for job_83d8fb6d5b6f: 4
jobs run this pass: 3

Note what this deliberately omits, and what production adds: real queueing (the in-process run_one loop stands in for a worker polling a queue), retries with backoff (the handler boundary is where they'd attach), cancellation, result expiry, priority, and a database-level guarantee for idempotency (submit looks the key up and then inserts, which two simultaneous requests could both pass; a real store enforces a unique index on (tenant_id, idempotency_key) and treats the loser's insert failure as "return the existing job") — and the multi-worker claim is already a port method (claim_next_queued on JobStorePort), which a Postgres adapter implements as SELECT ... FOR UPDATE SKIP LOCKED so two workers can never claim the same job. Notice the runner never touches store._jobs: it claims, transitions and reads through the port only, which is what lets a real store replace the fake without touching the state machine. The semantics — states, transitions, idempotency, tenant scoping, progress events — are the part that must be right everywhere.

6.5 ai_product/app.py — the wired application#

The FastAPI app factory that ties the ports together: dependency-injected ports, health route, request IDs, the job endpoints, and the SSE event stream. This is the skeleton the capstones extend.

python
# ai_product/app.py
"""FastAPI app factory: ports in, HTTP out.

create_app() takes the four ports (ModelPort, RetrieverPort, ToolsPort,
StorePort) plus a JobRunner. Production wires real adapters; tests and the
capstone keyless paths wire the in-memory fakes below.

Both SSE endpoints emit the 13A.2 event contract (events.py): status,
token, usage, error and done events framed as spec-correct SSE
(`event:`/`id:`/`data:`), with internal job-runner progress translated
into the same vocabulary rather than leaked raw. _ContractEncoder below
is a dict-level stand-in for events.SSEEncoder — same wire format,
plain-dict payloads — so this file needs only FastAPI beyond the standard
library; in your own project swap it (and the dicts) for events.SSEEncoder
and the typed StreamEvent models from 13A.2.

Run:  uv run uvicorn ai_product.app:demo_app --reload
"""

from __future__ import annotations

import asyncio
import json
import logging
import time
import uuid
from contextlib import asynccontextmanager, suppress
from typing import Any, AsyncIterator

from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field

from .jobs import InProcessJobStore, JobError, JobRunner
from .ports import (
    AuditEvent, Completion, Message, RetrievedChunk, StorePort,
    ToolResult,
)

log = logging.getLogger("ai_product.app")


# ---------------------------------------------------------------------------
# Fakes — the whole app runs with zero network, zero keys, zero services.
# Swap these for real adapters in your composition root.
# ---------------------------------------------------------------------------

class FakeModel:
    """ModelPort fake: deterministic completions for demos and tests.
    Production: provider_agnostic's client behind the same interface."""

    def __init__(self, replies: dict[str, str] | None = None) -> None:
        self.replies = replies or {}
        self.calls: list[list[Message]] = []

    async def complete(self, messages, *, model_alias=None,
                       max_output_tokens=None, request_id=None) -> Completion:
        self.calls.append(list(messages))
        last = messages[-1].content if messages else ""
        text = self.replies.get(last, f"[fake model] echo: {last[:60]}")
        return Completion(text=text, model_id="fake-1",
                          usage={"input_tokens": 0, "output_tokens": 0})

    async def stream(self, messages, *, model_alias=None, request_id=None):
        """Yields contract-shaped dicts — stand-ins for 13A.2's typed
        StreamEvent objects (TokenEvent, UsageEvent, ...). The port's
        return type is Any precisely so fakes and the provider_agnostic
        adapter can differ; _ContractEncoder accepts both."""
        completion = await self.complete(messages, model_alias=model_alias,
                                         request_id=request_id)
        # Minimal stand-in for the canonical stream: one token event per word.
        for word in completion.text.split(" "):
            yield {"type": "token", "text": word + " "}
        yield {"type": "usage",
               "input_tokens": completion.usage.get("input_tokens"),
               "output_tokens": completion.usage.get("output_tokens"),
               "model": completion.model_id}


class FakeRetriever:
    """RetrieverPort fake: substring match over a fixed corpus."""

    def __init__(self, chunks: list[RetrievedChunk]) -> None:
        self.chunks = chunks

    async def retrieve(self, query, *, tenant_id, k=5):
        q = query.lower()
        hits = [c for c in self.chunks
                if q.split() and any(w in c.text.lower() for w in q.split())]
        return hits[:k]


class FakeTools:
    """ToolsPort fake: two harmless tools, registry-shaped."""

    async def dispatch(self, name, args, *, tenant_id, request_id=None):
        if name == "lookup_order":
            return ToolResult(ok=True, output={"order_id": args.get("order_id"),
                                               "status": "shipped"})
        return ToolResult(ok=False, error=f"unknown tool {name!r}")

    def list_tools(self):
        return [
            {"name": "lookup_order",
             "description": "Look up an order's status by ID.",
             "parameters": {"type": "object",
                            "properties": {"order_id": {"type": "string"}},
                            "required": ["order_id"]}},
        ]


class InMemoryStore:
    """StorePort fake: conversations + jobs + audit in dicts.
    Production: Postgres adapter with tenant scoping (3.4)."""

    def __init__(self) -> None:
        self._messages: dict[tuple[str, str], list[Message]] = {}
        self._audit: list[AuditEvent] = []
        self.jobs = InProcessJobStore()

    async def append_message(self, conversation_id, tenant_id, message,
                             *, request_id=None) -> None:
        self._messages.setdefault((tenant_id, conversation_id), []).append(message)

    async def get_messages(self, conversation_id, tenant_id, *, limit=100):
        return list(self._messages.get((tenant_id, conversation_id), []))[-limit:]

    # Job/audit methods delegate to the job store or append locally.
    async def save_job(self, job): await self.jobs.save_job(job)
    async def get_job(self, job_id, tenant_id): return await self.jobs.get_job(job_id, tenant_id)
    async def find_job_by_key(self, key, tenant_id):
        return await self.jobs.find_job_by_key(key, tenant_id)
    async def claim_next_queued(self): return await self.jobs.claim_next_queued()

    async def audit(self, event: AuditEvent) -> None:
        self._audit.append(event)

    def audit_events(self) -> list[AuditEvent]:
        return list(self._audit)


# ---------------------------------------------------------------------------
# Request/response models
# ---------------------------------------------------------------------------

class AskRequest(BaseModel):
    question: str = Field(min_length=1, max_length=8000)
    conversation_id: str | None = None
    model_alias: str | None = None


class JobSubmitRequest(BaseModel):
    kind: str
    payload: dict[str, Any] = Field(default_factory=dict)


class Meta(BaseModel):
    """Provenance block — Part 4's contract. Every AI response carries it."""
    request_id: str
    model_id: str | None = None
    prompt_id: str | None = None
    finish_reason: str | None = None
    usage: dict[str, int] = Field(default_factory=dict)
    latency_ms: float
    degraded: bool = False


class AskResponse(BaseModel):
    conversation_id: str
    answer: str
    outcome: str = "completed"          # "completed" | "insufficient_evidence" | "refused" | ...
    meta: Meta


# ---------------------------------------------------------------------------
# App factory
# ---------------------------------------------------------------------------

def create_app(
    *,
    model: Any,                # ModelPort
    retriever: Any,            # RetrieverPort
    tools: Any,                # ToolsPort
    store: StorePort,          # StorePort (InMemoryStore in the demo)
    runner: JobRunner,
    tenant_id: str = "demo-tenant",
) -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        app.state.model = model
        app.state.retriever = retriever
        app.state.tools = tools
        app.state.store = store
        app.state.runner = runner

        # Demo stand-in for a real queue worker: poll run_one() until
        # shutdown. Production replaces this with a worker pool consuming
        # a real queue (2.2, 2.11).
        stop = asyncio.Event()

        async def job_worker() -> None:
            while not stop.is_set():
                if not await runner.run_one():
                    await asyncio.sleep(0.05)

        worker = asyncio.create_task(job_worker())
        yield
        stop.set()
        worker.cancel()
        with suppress(asyncio.CancelledError):
            await worker

    app = FastAPI(title="ai_product demo", lifespan=lifespan)

    # -- middleware: request IDs on every request and every audit event ------
    @app.middleware("http")
    async def request_context(request: Request, call_next):
        request_id = request.headers.get("x-request-id") or f"req_{uuid.uuid4().hex[:12]}"
        request.state.request_id = request_id
        start = time.perf_counter()
        response = await call_next(request)
        response.headers["x-request-id"] = request_id
        response.headers["x-latency-ms"] = f"{(time.perf_counter() - start) * 1000:.1f}"
        return response

    async def audit(request: Request, event_type: str, payload: dict) -> None:
        await store.audit(AuditEvent(
            event_id=f"evt_{uuid.uuid4().hex[:12]}",
            tenant_id=tenant_id, actor="user",
            event_type=event_type, request_id=request.state.request_id,
            payload=payload, created_at=time.time(),
        ))

    # -- routes ---------------------------------------------------------------

    @app.get("/health")
    async def health() -> dict[str, str]:
        return {"status": "ok"}

    @app.post("/v1/ask", response_model=AskResponse)
    async def ask(body: AskRequest, request: Request) -> AskResponse:
        """Synchronous Q&A, minimal orchestration: history -> retrieve ->
        assemble -> complete -> persist -> meta. Production swaps the
        retrieve/assemble steps for the docs_qa pipeline (07.11)."""
        t0 = time.perf_counter()
        conv_id = body.conversation_id or f"conv_{uuid.uuid4().hex[:12]}"
        chunks = await retriever.retrieve(body.question, tenant_id=tenant_id, k=3)
        context = ([Message(role="system", content=(
            "Answer using only this context:\n"
            + "\n\n".join(f"[{c.doc_id}] {c.text}" for c in chunks)))]
            if chunks else [])
        history = list(await store.get_messages(conv_id, tenant_id))
        messages = context + history + [Message(role="user", content=body.question)]
        completion: Completion = await model.complete(
            messages, model_alias=body.model_alias,
            request_id=request.state.request_id)
        await store.append_message(conv_id, tenant_id,
                                   Message(role="user", content=body.question),
                                   request_id=request.state.request_id)
        await store.append_message(conv_id, tenant_id,
                                   Message(role="assistant", content=completion.text),
                                   request_id=request.state.request_id)
        await audit(request, "ask", {"question": body.question[:200]})
        return AskResponse(
            conversation_id=conv_id,
            answer=completion.text,
            meta=Meta(request_id=request.state.request_id,
                      model_id=completion.model_id,
                      finish_reason=completion.stop_reason,
                      usage=completion.usage,
                      latency_ms=(time.perf_counter() - t0) * 1000))

    @app.post("/v1/ask/stream")
    async def ask_stream(body: AskRequest, request: Request) -> StreamingResponse:
        """The event stream endpoint: same request shape as /v1/ask, SSE
        answer. Emits the 13A.2 contract's minimal subset — status, token,
        usage, error, done — each payload valid against events.py's
        discriminated union."""
        conv_id = body.conversation_id or f"conv_{uuid.uuid4().hex[:12]}"
        chunks = await retriever.retrieve(body.question, tenant_id=tenant_id, k=3)
        context = ([Message(role="system", content=(
            "Answer using only this context:\n"
            + "\n\n".join(f"[{c.doc_id}] {c.text}" for c in chunks)))]
            if chunks else [])
        history = list(await store.get_messages(conv_id, tenant_id))
        messages = context + history + [Message(role="user", content=body.question)]

        async def events() -> AsyncIterator[str]:
            enc = _ContractEncoder()
            yield enc.encode({"type": "status", "message": "Starting answer"})
            try:
                async for ev in model.stream(messages,
                                             model_alias=body.model_alias,
                                             request_id=request.state.request_id):
                    yield enc.encode(ev)
            except Exception:  # stream errors are events, not HTTP codes
                # The real exception goes to the server log, never onto the
                # wire: exception text can leak internals (13A.4, copy is a
                # security surface). The client gets a stable code instead.
                log.exception("stream failed request_id=%s", request.state.request_id)
                yield enc.encode({"type": "error",
                                  "message": "The answer stream failed.",
                                  "retryable": True, "code": "stream_error"})
                yield enc.encode({"type": "done", "status": "failed",
                                  "reason": "stream error"})
                return
            yield enc.encode({"type": "done", "status": "completed"})

        return StreamingResponse(events(), media_type="text/event-stream",
                                 headers={"cache-control": "no-cache",
                                          "x-accel-buffering": "no"})

    @app.post("/v1/jobs", status_code=202)
    async def submit_job(body: JobSubmitRequest, request: Request,
                         idempotency_key: str | None = Header(default=None)):
        """Async job submission. The Idempotency-Key header makes retries
        safe: same key + same body replays the job; same key + different
        body is a 409, not a silent wrong-job (2.11)."""
        try:
            job = await runner.submit(body.kind, body.payload,
                                      tenant_id=tenant_id,
                                      idempotency_key=idempotency_key)
        except JobError as exc:
            raise HTTPException(status_code=409, detail=str(exc)) from exc
        await audit(request, "job_submit", {"job_id": job.job_id, "kind": job.kind})
        return {"job_id": job.job_id, "status": job.status}

    @app.get("/v1/jobs/{job_id}")
    async def get_job(job_id: str, request: Request):
        job = await store.get_job(job_id, tenant_id)
        if job is None:
            raise HTTPException(status_code=404, detail="job not found")
        return {"job_id": job.job_id, "kind": job.kind, "status": job.status,
                "result": job.result, "error": job.error,
                "created_at": job.created_at, "updated_at": job.updated_at}

    @app.get("/v1/jobs/{job_id}/events")
    async def job_events(job_id: str, request: Request) -> StreamingResponse:
        """SSE feed of job progress in the 13A.2 contract vocabulary — the
        BFF's translation job (2.1) in miniature: internal runner events
        never reach the client un-normalised."""
        job = await store.get_job(job_id, tenant_id)
        if job is None:
            raise HTTPException(status_code=404, detail="job not found")

        async def events() -> AsyncIterator[str]:
            enc = _ContractEncoder()
            seen = 0
            terminal = {"succeeded": "completed", "failed": "failed",
                        "cancelled": "cancelled"}
            # Demo-grade: in production this tails job_events rows or a pub/sub.
            while True:
                evs = await runner.events(job_id)
                for ev in evs[seen:]:
                    yield enc.encode(_job_event_contract(ev))
                    seen += 1
                current = await store.get_job(job_id, tenant_id)
                if current and current.status in terminal:
                    yield enc.encode({"type": "done",
                                      "status": terminal[current.status],
                                      "reason": current.error})
                    return
                await asyncio.sleep(0.05)

        return StreamingResponse(events(), media_type="text/event-stream")

    return app


class _ContractEncoder:
    """Stand-in for 13A.2's events.SSEEncoder: identical WHATWG frame format
    (`event:`/`id:`/`data:` + blank line, monotonically increasing id) but
    accepts plain dicts as well as typed StreamEvent models, so this file
    runs without importing events.py. In your own project prefer
    events.SSEEncoder with typed events — the models validate payloads
    against the contract."""

    def __init__(self) -> None:
        self._seq = 0

    def encode(self, event: Any) -> str:
        self._seq += 1
        if hasattr(event, "model_dump_json"):        # a 13A.2 StreamEvent
            etype = event.type
            data = event.model_dump_json(exclude_none=True)
        else:                                        # contract-shaped dict
            etype = str(event.get("type", "message"))
            data = json.dumps({k: v for k, v in event.items()
                               if v is not None})
        return f"event: {etype}\nid: {self._seq}\ndata: {data}\n\n"


def _job_event_contract(ev: dict[str, Any]) -> dict[str, Any]:
    """Translate a JobRunner progress record ({seq, type, at, data}) into a
    13A.2 contract event. The runner's vocabulary ('parse', 'extract',
    'status') is internal; clients only ever see contract events — the
    BFF's protocol-translation job (2.1), in miniature."""
    kind = ev.get("type", "status")
    data = ev.get("data") or {}
    if kind == "status":
        state = {"running": "running", "succeeded": "done",
                 "failed": "failed"}.get(data.get("status", ""), "running")
        message = f"Job {data.get('status', 'update')}"
        if data.get("error"):
            message += f": {data['error']}"
        return {"type": "status", "message": message, "state": state}
    return {"type": "status", "message": f"Job step: {kind}",
            "state": "running"}


# ---------------------------------------------------------------------------
# A runnable demo app — fakes only, no keys.
# ---------------------------------------------------------------------------

def build_demo_app() -> FastAPI:
    store = InMemoryStore()
    # The runner codes against JobStorePort — the full StorePort satisfies
    # it, so the app passes the store, not a private corner of the fake.
    runner = JobRunner(store)

    async def demo_extract(payload, ctx):
        await ctx.progress("parse", {"bytes": len(str(payload))})
        return {"fields": {"vendor": "Acme Ltd", "total": "123.45"}}

    runner.register("extract_invoice", demo_extract)
    runner.register("summarize_doc", demo_extract)

    model = FakeModel(replies={
        "What is the refund policy?":
            "Refunds are available within 30 days of purchase [demo].",
    })
    retriever = FakeRetriever([
        RetrievedChunk(chunk_id="c1", doc_id="handbook", score=0.9,
                       text="Refund policy: 30 days from purchase date."),
        RetrievedChunk(chunk_id="c2", doc_id="handbook", score=0.7,
                       text="Shipping takes 5-7 business days."),
    ])
    return create_app(model=model, retriever=retriever, tools=FakeTools(),
                      store=store, runner=runner)


demo_app = build_demo_app()

This file is the composition root in miniature: it shows the four ports, the middleware every production app needs (request IDs — 11A.1's trace context starts here), typed response models with the meta provenance block, jobs with idempotency keys, and SSE endpoints that emit the 13A.2 event contract — _ContractEncoder is a dict-level stand-in for events.SSEEncoder (identical event:/id:/data: framing) that keeps this file dependency-light (in your own project, use events.SSEEncoder and the typed events from 13A.2), and internal job-runner progress is translated into the same vocabulary rather than leaked raw. The lifespan worker is the demo stand-in for a real queue worker: it polls runner.run_one() until shutdown — in production a worker pool consumes a real queue. What it deliberately omits, and production adds: real auth (the tenant_id here is a constant — production resolves it from the session per request, as 07.11, 1.4 does), real adapters, rate limiting, graceful shutdown of in-flight streams and jobs, persistence of streamed turns (only /v1/ask writes messages to the store here), and structured logging. Not run while writing: app.py needs FastAPI and uvicorn, and this module was written without installing packages, so the file was read line by line but never started. Run it in the app phase from the project root: uv run uvicorn ai_product.app:demo_app --port 8000; in a second terminal curl -s localhost:8000/health, then curl -s -X POST localhost:8000/v1/ask -H 'content-type: application/json' -d '{"question": "What is the refund policy?"}' (expect a JSON body with an answer and a meta block), curl -sN -X POST localhost:8000/v1/ask/stream -H 'content-type: application/json' -d '{"question": "hello"}' (expect SSE frames ending in done), and Exercise 7's job calls. One more demo shortcut: a failed job's error string (exception type and text) is returned to the client as-is; production stores the detail in the audit log and returns a typed error code, for the same reason the stream endpoint above logs its exception instead of sending it.

6.6 What this means for you as an engineer#

The monolith-with-ports pattern gives you the two things that matter: testability (the whole app runs on fakes — the capstones prove it) and reversibility (swap an in-memory store for Postgres, a fake model for provider_agnostic, without touching orchestration). Every "should we split this into a service?" question becomes "does this port need a different deployment?" — a question you can answer with evidence instead of taste.


Part 7: Documenting architecture#

Deep-dive

7.1 Why document at all#

Architecture documentation for AI systems is unusually perishable: the model landscape shifts monthly, the "right" pattern changes as provider features land, and team members join who weren't there for the original reasoning. The documentation this lesson recommends is deliberately small and modular — documents that get updated because they're cheap to update, not comprehensive wikis nobody reads. Michael Nygard's ADR post (2011) makes the case that still holds: record the decisions and their rationale, not the whole system.

7.2 ADRs: architecture decision records#

An ADR (architecture decision record) is a short document — one to two pages — capturing one significant decision: the context (forces at play), the decision, the status, and the consequences. Keep them in the repo (docs/adr/NNNN-title.md), numbered sequentially, never reused; supersede rather than delete.

Template:

markdown
# ADR NNNN: <short noun phrase>

- Status: proposed | accepted | deprecated | superseded by ADR-XXXX
- Date: YYYY-MM-DD
- Deciders: <names/roles>

## Context
The forces at play: technical, product, regulatory, team. State facts
neutrally — no justification yet.

## Decision
"We will ..." — one decision, stated plainly.

## Consequences
Positive, negative and neutral. What becomes easier, what becomes harder,
what constraints this creates for future decisions.

Worked example 1 — "streaming gateway vs direct provider calls" (the exercise in this lesson asks you to write this one):

markdown
# ADR 0007: Streaming responses via a server-side gateway

- Status: accepted
- Date: 2026-10-14
- Deciders: A. Rivera (eng), M. Okafor (product)

## Context
The support copilot streams answers to the agent console. Three client
surfaces are planned (web console, Slack app, partner API). Providers emit
incompatible stream dialects (03.3). Prompt assembly, guardrails and cost
accounting must be identical across surfaces. Direct browser-to-provider
calls would expose API keys and bypass all of that.

## Decision
We will proxy all model streaming through the FastAPI app: the client
opens an SSE connection to our `/v1/ask/stream`, the server opens the
provider stream, normalises it to the 13A.2 event contract, and re-emits.
No client ever holds a provider key or sees a provider event shape.

## Consequences
- Positive: one place for auth, prompts, guardrails, cost metering; one
  event contract for all clients; provider swaps are invisible to clients.
- Negative: our servers hold every open stream (connection limits matter);
  we own SSE reliability (heartbeats, reconnects); one extra network hop
  adds ~50-150 ms to first event.
- Neutral: mobile clients that can't hold SSE will poll job status instead
  (same contract, different transport).

Worked example 2 — "Postgres+pgvector vs dedicated vector DB" (the other exercise):

markdown
# ADR 0012: Vectors in Postgres via pgvector

- Status: accepted
- Date: 2026-10-02
- Deciders: A. Rivera (eng)

## Context
Corpus: ~40k handbook chunks, ~5 QPS peak retrieval, B2B multi-tenant.
Postgres is already the system of record. pgvector 0.8.7 supports the
needed distance metrics and HNSW indexes; managed Postgres offers it
preinstalled. A dedicated vector DB adds a second datastore, its own
backup/HA story, and per-tenant filtering complexity (06.6).

## Decision
We will store embeddings in a `document_chunks` table in the primary
Postgres with an HNSW index on `embedding vector(1024)`, filtered by
`tenant_id`. Revisit if corpus exceeds ~1M chunks or p95 retrieval
exceeds the 800 ms budget in the latency table (13A.5, 5.2).

## Consequences
- Positive: one datastore, joins between chunks and documents, ACID
  ingestion, one backup; tenant isolation via the same RLS as everything
  else.
- Negative: vector queries share resources with OLTP; very large corpora
  or exotic index types may force a migration later (the RetrieverPort
  boundary makes that a config change, not a rewrite).
- Neutral: embedding model changes require re-embedding — same as any
  vector store.

7.3 The C4 model for AI systems#

The C4 model (Simon Brown, c4model.com) is a notation for architecture diagrams at four zoom levels: system context (your system and its users/external systems), container (the deployable applications and data stores inside it), component (modules inside a container), and code (classes inside a component — rarely needed). For AI systems the levels map cleanly:

  • Context: users, your product, model providers, SaaS integrations, identity provider.
  • Container: web app, FastAPI monolith, Postgres(+pgvector), object storage, queue/worker, (optional) model gateway service.
  • Component: inside the monolith — orchestration, model gateway adapter, retriever, tool registry, safety guards, job runner.
flowchart TB
    subgraph sys ["Support Copilot (system context)"]
        AGENT(["Support agent"])
        CUST(["Customer (via widget)"])
        subgraph prod ["Our platform"]
            WEB["Agent console (web)"]
            API["FastAPI app (monolith)"]
            DB[("Postgres + pgvector")]
            OBJ[("Object storage")]
            WRK["Job worker"]
        end
        EXT1["Model providers"]
        EXT2["Ticketing SaaS"]
        IDP["Identity provider"]
    end
    AGENT --> WEB
    CUST --> WEB
    WEB --> API
    API --> DB
    API --> OBJ
    API --> WRK
    API --> EXT1
    API --> EXT2
    WEB -.-> IDP

Draw the context diagram first — it forces you to name every external dependency (including the model providers, which are easy to forget are external systems with their own outages and policies). Then the container diagram shows deployables. Mermaid renders C4-style diagrams adequately for docs; dedicated tools (Structurizr, Mermaid's C4 support) exist if you want strict notation.

7.4 Threat-model overlay#

Architecture diagrams and threat models are the same picture with a different lens. Lesson 12.1 owns the full method (assets, actors, trust boundaries, STRIDE-for-LLM, the lethal trifecta). The architectural habit: draw trust boundaries on your container diagram — every arrow crossing a boundary is a place untrusted data enters. For an AI app the critical boundaries are:

  • client → API (user input is untrusted)
  • API → model provider (your data leaves; their output is untrusted-ish)
  • retrieval → prompt (retrieved documents are untrusted content — 12.2)
  • model → tools (model output can trigger actions — the tool args are validated at the registry, 2.5)
  • tools → external SaaS (credentials and PII cross here)
  • everything → logs/traces (secrets and PII leak through observability — 12.4)

Annotate each boundary crossing with the control that governs it (auth, validation, guardrail, encryption, redaction). The diagram then doubles as a security-review artefact and an onboarding doc.

7.5 Runbooks#

A runbook is the operational companion to the architecture: for each failure class, what to check, what to do, what to escalate. 11C.4 owns runbook anatomy and provides templates for provider outage, rate-limit exhaustion, cost spike, quality regression, retrieval failure, injection incident, PII leak, runaway agent and leaked key. The architecture-level requirement: every component in your diagram has a named owner and a runbook entry for its known failure modes. If you can't write "when the vector store is down, retrieval degrades to keyword-only and the banner says so" for a component, you don't understand that component well enough to operate it.

7.6 What this means for you as an engineer#

Document decisions, not descriptions. One ADR per significant choice, one C4 diagram set per system, trust boundaries on the container diagram, runbooks per failure class. The whole pack should fit in an afternoon to write and ten minutes to update — if it doesn't, it's already stale.


Part 8: Reference architectures for the capstones#

Reference

The three capstones (13B.2 support copilot, 13B.3 document intelligence, 13B.5 voice agent) share the Part 1 skeleton and differ in exactly the dimensions that should drive architecture: latency class, state shape, risk tier and data flows. This section gives each a container-level diagram and the deltas; the capstone lessons fill in the detail.

8.1 Capstone A: the support copilot (13B.2)#

Interactive chat + tools + approvals. Synchronous streaming answers; jobs only for long-running actions.

flowchart TB
    AGENT(["Support agent"]) --> WEB["Agent console (web)"]
    WEB --> API["FastAPI app"]
    API --> ORCH["Orchestration:<br/>answer | draft-reply | action"]
    ORCH --> RET["Retrieval service<br/>(handbook, tickets)"]
    ORCH --> GW["Model gateway"]
    ORCH --> REG["Tool registry:<br/>lookup_order, create_ticket,<br/>issue_refund (approval-gated)"]
    ORCH --> SAFE["Safety: injection screen,<br/>PII redaction, policy"]
    RET --> VEC[("pgvector: handbook + tickets")]
    API --> DB[("Postgres: conversations,<br/>jobs, audit, feedback")]
    API --> OBJ[("Object storage: attachments")]
    GW --> PROV["Model providers"]
    REG --> TICK["Ticketing/order SaaS"]

Key architectural choices: SSE streaming for chat (13A.2 contract); ApprovalGate (13A.3) sits inside the tool registry so issue_refund cannot execute without approval; retrieval is tenant-scoped; feedback events flow to eval cases (13A.6 and Module 10A).

8.2 Capstone B: the document intelligence app (13B.3)#

Upload → parse → extract → review. Job-centric: uploads are async jobs with progress events; extraction results are structured output reviewed by a human.

flowchart TB
    USER(["User"]) --> WEB["Web app"]
    WEB --> API["FastAPI app"]
    API --> JOBS["Job runner<br/>(parse → chunk → extract → validate)"]
    JOBS --> STORE[("Postgres: documents,<br/>extractions, review state")]
    JOBS --> OBJ[("Object storage: uploads,<br/>page images")]
    JOBS --> GW["Model gateway<br/>(vision + text models)"]
    JOBS --> SAFE["Safety: doc injection screen,<br/>PII handling, schema validation"]
    API --> SSE["SSE progress feed"]
    WEB -.-> SSE
    GW --> PROV["Model providers"]

Key architectural choices: everything heavy is a job (2.2); progress events use the same SSE contract as chat; extraction is schema-constrained structured output (03.4) validated in layers; human review is a first-class state in the job model, not an afterthought.

8.3 Capstone C: the realtime voice agent product (13B.5)#

Low-latency bidirectional audio. WebSocket media streams; the orchestration is a realtime speech-to-speech or STT→LLM→TTS pipeline depending on provider capabilities (09.6, 09.7 own the details).

flowchart TB
    USER(["User (voice)"]) --> WEB["Web/mobile client<br/>WebSocket audio"]
    WEB --> EDGE["Media edge / BFF<br/>(audio framing, VAD, barge-in)"]
    EDGE --> PIPE["Voice pipeline:<br/>STT to orchestrator to TTS,<br/>or a realtime speech model"]
    PIPE --> GW["Model gateway<br/>(realtime + chat models)"]
    PIPE --> STORE[("Postgres: sessions,<br/>transcripts, consent records")]
    PIPE --> SAFE["Safety: real-time guardrails,<br/>consent, recording policy"]
    GW --> PROV["Model providers"]

Key architectural choices: the latency budget is brutal (turn-taking ~sub-second; 09.7); the edge/BFF owns media framing so the core services stay transport-agnostic; transcripts and consent records are stored for audit and compliance; graceful degradation (text fallback, canned responses) is designed in, not improvised.

8.4 Comparison#

Dimension Support copilot Document intelligence Voice agent
Latency class Interactive, streaming (TTFT ~1–3 s) Async jobs (seconds–minutes) Realtime (sub-second turn-taking)
Dominant response shape SSE stream + sync Job + progress events Bidirectional WebSocket
State shape Conversations + job outbox Documents + extraction records Sessions + transcripts
Risk tier Draft + act-with-approval Extract + human review Assist (lowest autonomy)
Data flows Retrieval heavy; tools touch SaaS Files in, structured data out Audio in/out; PII-heavy
Key architectural risk Tool side-effects, injection via tickets Large-doc cost, extraction errors at scale Latency budget, consent/compliance

What this means for you as an engineer: the capstones are the same skeleton with different emphases. If you can draw all three from memory, you understand which architectural choices are universal (ports, gateway, jobs, safety seam, config) and which are driven by the product's latency class, state shape and risk tier.


Reference

Each row is a real architecture failure, what it looks like in production, and the pattern that prevents it.

Anti-pattern What it looks like The fix
Provider SDK calls scattered in handlers client.messages.create in six files; retries, timeouts and error mapping differ per call site; a provider swap is a multi-day search One ModelPort behind the gateway (2.6); grep should find SDK calls in exactly one package
Prompt strings in code f"You are a helpful assistant... {user_input}" inline; prompt fixes need deploys; no version tracking; evals can't reproduce Prompt registry + PromptSpec (2.9, 04.10); prompts are versioned artefacts
One giant agent for everything A single agent loop handles chat, extraction, refunds and reports; budgets are global; a bad tool poisons every feature Workflow vs agent per feature (2.3, 08A.9); bounded contexts per capability
Synchronous long jobs behind a proxy timeout Document processing holds the HTTP request open; CDN kills it at 30 s; user sees a spinner then an error Job + status + webhook/SSE progress (2.2); jobs.py is the pattern
Shared cache across tenants Tenant A's cached answer served to tenant B; or a semantic cache hit returns another customer's data Tenant-scoped cache keys (2.10, 11B.3, 06.6)
No trace/request IDs "The answer was wrong" is unanswerable: which prompt, which model, which retrieval, which tool calls? Request ID middleware → trace → meta block (Part 4, 11A.1)
Tools with ambient authority The model can call any tool with any args the user could; a prompt injection becomes a real refund Tool registry + policy + approvals + least privilege (2.5, 08A.14, 12.6)
Model IDs hard-coded throughout Upgrading a model is a code change in 14 places; A/B testing models is impossible Model aliases in config (2.9); meta.model_id for observability
Conversation state in the client only Users can't see history on a second device; you can't eval real conversations; memory features impossible Server-side conversation store (3.7)
Retries at every layer Client retries API, API retries gateway, gateway retries provider, provider SDK retries internally — a transient blip becomes 16 calls and a cost spike One retry owner per boundary (2.11, 03.8)
Guardrails bolted on per endpoint Each handler does its own PII check; they drift; one endpoint forgets Safety as a seam in orchestration (Part 1 diagram)
"We'll add tenancy later" Every query, cache key, prompt and memory lookup needs retrofitting; the retrofit is the most expensive migration in AI systems tenant_id in every store's key/RLS from day one (2.8)
The demo architecture ships Prototype's single-file app.py with inline prompts becomes production; no ports, no jobs, no budgets Monolith-with-ports from day one (Part 6); the capstone rubric (13B.1) checks this
Failure User sees System cause Detection
Provider outage Errors or slow responses No fallback chain Circuit breaker + degraded mode (11C.3)
Rate limit hit Throttling errors No per-tenant quota Gateway policy + 429/Retry-After (4.5)
Cost spike Feature throttled or degraded No budget caps Per-tenant spend caps + alerting (5.3, 11A.2)
Wrong model silently Plausible but off answers Alias misconfiguration meta.model_id in traces + eval regression (11C.2)
Prompt regression Quality drops after "fix" No prompt versioning/eval gate Prompt registry + eval gates (2.9)
Cache poisoning Wrong/stale answers served fast Missing invalidation Cache versioning + TTL policy (2.10)
Job lost User's document never processed No durable job state Job state machine + reconciliation (2.2, jobs.py)
Duplicate side effect Double refund, double ticket Non-idempotent tool call Idempotency keys at every boundary (2.11)
Tenant leak Tenant A sees tenant B's data Missing tenant filter RLS + port-level tenant scoping (2.8)
Stream dies mid-answer Truncated response No heartbeat/reconnect SSE heartbeats + resumable streams (13A.2, 03.3)

9.3 The architecture checklist#

Copy this into your project and tick honestly:

markdown
## AI architecture checklist

### Layers and seams
- [ ] Every model call goes through one gateway/port (no SDK imports elsewhere)
- [ ] Orchestration is a separate layer from transport (BFF/API)
- [ ] Retrieval is a bounded service with a typed contract
- [ ] Tools go through a registry with policy + audit
- [ ] Safety checks are a seam, not scattered ifs

### Response shapes
- [ ] Each endpoint's shape (sync/stream/job/event) is decided and documented
- [ ] Long operations return job IDs, not held-open requests
- [ ] Every mutating endpoint accepts an Idempotency-Key
- [ ] Errors are typed: outcome field for task results, error envelope for transport

### State and storage
- [ ] Every state type has an owner, a store and a lifecycle (incl. deletion)
- [ ] tenant_id is in every store's key or RLS policy
- [ ] Conversation history is server-side; context windowing is an operation
- [ ] Audit events are append-only with request_id + model/prompt versions

### API contract
- [ ] API is versioned; changes within a version are additive
- [ ] Every response carries meta: request_id, model_id, prompt version, usage
- [ ] Webhooks are signed; polling endpoints document their semantics
- [ ] Rate limits and quotas are exposed to clients (429 + Retry-After)

### Non-functionals
- [ ] Latency/cost/availability/quality/safety budgets written per feature
- [ ] Per-stage p95 budgets exist and are measured
- [ ] Per-tenant cost caps are enforced at the gateway
- [ ] SLOs defined for the AI-specific indicators (quality, safety, cost/task)

### Operations
- [ ] Request IDs flow through every hop (client → API → gateway → provider)
- [ ] Every component has a named owner and a runbook entry
- [ ] Feature flags gate capabilities; kill switches exist
- [ ] ADRs written for every significant decision
- [ ] C4 context + container diagrams exist and are current
- [ ] Threat boundaries drawn on the container diagram

9.4 What this means for you as an engineer#

The anti-patterns are all omissions, not exotic mistakes: someone didn't draw the boundary, didn't write the idempotency key, didn't put tenant_id in the schema. The checklist is the defence — run it at design review, not after the incident.


Where you'll use this#

  • 13B.2 — Capstone A, the support copilot is this lesson's reference architecture in miniature: BFF + streaming gateway (2.1), synchronous chat plus job-shaped refund actions (2.2), bounded retrieval over docs_qa (2.4), the tool registry with its approval gate (2.5, 2.7), model aliases and capability flags (2.9), tenant_id in every store and cache key (2.8), and the ai_product ports from Part 6.
  • 13B.3 — Capstone B, the document intelligence app leans hardest on the async-job and event-driven shapes (2.2), the job runner with idempotent submission and the claim seam (2.11, jobs.py), per-tenant isolation (2.8) and the latency/cost budgets of Part 5.
  • 13B.5 — Capstone C, the voice agent product turns the BFF into a realtime media edge: tighter latency budgets, durable waits for human handoffs (2.7), and the same ports underneath.
  • 13B.6 — Shipping and operating your capstone uses the ADRs, C4 diagrams, threat overlay and checklist from Parts 7 and 9 as the launch-review artefacts.
  • In industry you will meet these patterns under product names — API gateways, durable workflow engines (Temporal and managed equivalents), RAG services, MCP tool layers — but the seams drawn here are the same ones.

Common misconceptions#

Misconception Reality
"An AI app is just an API call to a model." It's a layered system where the model is one non-deterministic, stateful-cost dependency behind a gateway. The architecture exists to contain that.
"Microservices are required for AI applications." The opposite is usually true at the start: a modular monolith with ports and adapters gives you testability and reversibility without distributed-systems overhead. Split only when a specific pressure demands it.
"The model remembers the conversation, so we don't need to store it." The model is stateless (02.7); every apparent memory is your storage re-supplied per call.
"Streaming means the response can't time out." Streams are still bounded by proxy and connection timeouts; long streams need heartbeats, resumability and a job fallback.
"Retries are always safe." Retrying a non-idempotent side effect (a refund, a ticket) is how you get double charges. Idempotency is designed into the operation, not bolted onto the retry.
"A vector database is required for RAG." Postgres + pgvector covers most products (corpus ≲1M chunks, ordinary QPS); dedicated vector DBs earn their complexity at scale or with exotic query needs (06.5).
"The API contract is the provider's API." Your contract is yours: versioned, aliased, with meta provenance. Provider APIs change monthly; your clients shouldn't notice.
"Feature flags are for frontend rollout." For AI they gate capabilities — retrieval, tools, agent mode, model tier — so a bad model or prompt can be killed without a deploy.
"Multi-tenancy is a WHERE tenant_id problem." It's a design constraint on every layer: stores, caches, prompts, memory, budgets, quotas. Retrofitting is the most expensive migration in AI systems.
"Durable execution is for everything long-running." It's for flows with human waits and multi-day elapsed time. A 3-minute job needs a job runner, not Temporal.
"Architecture diagrams are documentation debt." Small, modular docs (ADRs, C4 diagrams) are the cheapest insurance against the highest-cost AI failure: nobody remembering why a decision was made.
"If it works on the demo data, the architecture is fine." The demo path exercises none of the failure modes — timeouts, retries, tenant isolation, cost caps, job recovery. The architecture is proven by the checklist and the fakes, not the happy path.

Key takeaways#

  • An AI application is a layered system: clients → BFF/edge → application API → orchestration → model gateway → providers, with retrieval, tools, safety, storage, jobs, observability and config as cross-cutting layers. Each layer exists because a specific AI property (non-determinism, statelessness, semantic failure, per-token cost) demands it.
  • Four response shapes — synchronous, streaming, async job, event-driven — and the choice is an architecture decision made per endpoint before code is written.
  • Workflow vs agent is an architecture decision: it determines your durability, testing and budget strategy, not just your prompting style (08A.9).
  • Bounded services: retrieval is a service with a contract; tools go through a registry with policy; the model goes through one gateway with canonical types, aliases, routing and resilience.
  • Durable execution (Temporal-style engines or queue-based state machines) is for human waits and multi-day flows; a job runner covers minutes-long work.
  • Multi-tenancy is a per-layer constraint — tenant_id in every store, cache key, prompt resolution and budget — decided on day one.
  • Config is a seam: prompts, model aliases and flags resolve through one layer so changes don't need deploys.
  • Caching is cross-cutting with AI-specific correctness rules: tenant-scoped keys, versioned prompts, invalidation that follows the data lifecycle.
  • Idempotency is a property of the operation: every mutating endpoint and every side-effecting tool accepts keys; retries have exactly one owner per boundary.
  • The model is stateless; your stores are the state: conversations, memory, jobs, audit, vectors and feedback each get a store, a lifecycle and a deletion path.
  • API contracts outlive models: version the API, hide models behind aliases, carry provenance in meta, type outcomes separately from transport errors.
  • Budgets are allocated per stage: latency, cost, availability, quality and safety budgets are written down, enforced in config, and measured against SLOs.
  • Monolith first, with ports: one deployable, clean interfaces (ModelPort, RetrieverPort, ToolsPort, StorePort), fakes for everything — testable and reversible.
  • Document decisions: ADRs for significant choices, C4 diagrams for the system shape, trust boundaries on the container diagram, runbooks per failure class.
  • The three capstones share one skeleton and differ in latency class, state shape, risk tier and data flows — learn to see which choices are universal and which are driven by those four dimensions.

Terms introduced in this lesson#

Term One-line definition
Reference architecture The layered blueprint this lesson uses: the standard arrangement of an AI application's components
Backend-for-frontend (BFF) A server layer tailored to each client that owns session, aggregation and protocol translation
Streaming gateway The BFF/API role that normalises provider stream dialects into your event contract
Async job Work submitted for later execution, tracked by a job ID, with status polling or webhooks
Event-driven pipeline Services reacting to events independently, with state in stores and the event log
Orchestration The layer that decides the shape of the answer: one call, a workflow, or an agent loop
Bounded service / bounded context A capability isolated behind its own contract, store and failure modes
Plugin registry The single place tools are registered, described, authorized and audited
Model gateway The one seam for all model calls: canonical types, aliases, routing, fallback, telemetry
Model alias A stable code-level name (support-draft) resolved to a concrete model via config
Durable execution Workflow engines that checkpoint every step so runs survive crashes and human waits
Multi-tenancy One deployment serving many customers with isolated data, prompts, caches and quotas
Silo / pool / bridge tenancy Separate deployments / shared services with enforced filtering / shared everything (prototype only)
Feature flag (capability flag) A switch that gates an AI capability, not just UI, so bad rollouts die without deploys
Prompt registry The versioned store that resolves prompt aliases to pinned versions at request time
Idempotency key A client-supplied token making a mutating operation safe to retry
At-least-once delivery Queue semantics where a message may be delivered more than once; consumers must be idempotent
Non-functional budget An allocated allowance (latency, cost, availability, quality, safety) per request or stage
Latency budget Per-stage p95 time allocations summed to a total the user will tolerate
SLO / SLA Service level objective (internal target) / agreement (contractual consequence)
Ports and adapters Code depends on small interfaces (ports); implementations (adapters) are swappable
In-memory fake A test double implementing a port with deterministic local behaviour
Job runner The component driving job state machines: queued → running → succeeded/failed
Job state machine The defined set of states and legal transitions a unit of async work moves through
ADR (architecture decision record) A short document capturing one significant decision, its context and consequences
C4 model A four-level notation for architecture diagrams: context, container, component, code
Trust boundary A point where untrusted data crosses into your system; annotated with its control
Runbook Operational doc per failure class: what to check, what to do, what to escalate
Event sourcing Storing events as the primary record and deriving state by replay
Audit event An append-only record of who did what, with request/model/prompt provenance
Distributed monolith Multiple deployables that must ship together anyway — the worst of both worlds
meta block The provenance object in every AI response: request_id, model, prompt version, usage
Outcome vs error Task-level result classification (completed/refused/insufficient) vs transport failure

All terms are also collected in the glossary.


Exercises#

  1. Draw the C4 container diagram for your own AI product idea (or one of the three capstones). Label every external system — including the model providers — and mark the trust boundaries.
  2. Write an ADR for "streaming gateway vs direct provider calls" for a product you know. Use the template in 7.2; the worked example there is the support copilot's answer — argue the other side honestly in Context.
  3. Allocate budgets for a document-intelligence job: p95 total time for a 50-page PDF through parse → chunk → extract → validate. Which stage dominates, and what would you measure first?
  4. Find the anti-patterns in this deliberately flawed listing: a handler that calls anthropic.Anthropic().messages.create directly inside POST /v1/extract, builds the prompt with an f-string, has no timeout, retries three times in a loop, returns {"result": model_text} with no meta, and stores nothing. List every violation and map each to the pattern that fixes it.
  5. Design the job model for "user uploads a contract; we extract 12 fields; a human reviews; we notify". What states does the job need? Where does the human wait live — job state or durable workflow? Justify with 2.2 and 2.7.
  6. Tenant isolation audit: given the ai_product ports in this lesson, list every place tenant_id must appear for the support copilot to be safely multi-tenant. Check the store methods, cache keys (imagined), prompt resolution and budget enforcement.
  7. Keyless run: create the ai_product package (ports.py, jobs.py, app.py from this lesson) in a uv project and run uv run python -m ai_product.jobs. Then start the demo server (uv run uvicorn ai_product.app:demo_app) and, with httpx, POST /v1/jobs with a JSON body such as {"kind": "extract_invoice", "payload": {"document": "INV-1"}} (the demo registers the kinds extract_invoice and summarize_doc; send the same Idempotency-Key header twice, then once more with a different payload — watch the 409), GET /v1/jobs/{id} until it succeeds, and stream GET /v1/jobs/{id}/events to see the contract events. No keys needed.
  8. API contract review: take any AI API you have used. Does it carry meta-style provenance? Are errors typed? Is there an idempotency story? Write the gap list.
  9. Dual-write audit. Find three places in your own design where one request must change two systems (database and queue, approval and action, upload and index). For each, say whether you would use "the database is the queue" or an outbox, and what makes the consumer idempotent (2.12).
Hints for the exercises
  1. Minimum boxes: user, web client, API/monolith, Postgres (+ pgvector), object storage, job worker, model providers (external), any SaaS. Trust boundaries sit between the client and API, API and providers, and retrieval content and the prompt.
  2. Argue the other side as an honest engineer would: fewer hops and lower first-event latency, no gateway to run. A fair counter-consequence is that you then expose provider keys or accept provider-shaped events in clients, and you must say how auth, cost metering and guardrails work without a server hop.
  3. For scanned PDFs, parse (OCR or layout) usually dominates, so measure per-page parse latency first, then per-extraction-call latency. Budget per stage, add a buffer for retries inside stages, and convert the total into a job SLO (for example, minutes, not seconds), with progress events per page.
  4. Violations and fixes: direct SDK call (gateway/ModelPort); f-string prompt (prompt registry); no timeout and a hand-rolled retry loop (one retry owner, deadlines); no meta (provenance block); {"result": text} with no outcome (typed outcome); no request ID, idempotency key or audit event; stores nothing (conversation and audit stores); possibly a long synchronous extraction (job shape).
  5. States: queued, running, awaiting_review, approved or rejected, notifying, succeeded, failed, cancelled. If the human wait is hours to days and review is a state in your own table, a job state plus a reminder worker is enough; reach for a durable engine when waits are multi-day with several side-effecting steps after approval.
  6. Every store method (messages, jobs, audit), every cache key, prompt and model-alias resolution, the retriever filter, memory lookups, budget counters, and the outbox or event rows.
  7. Expect 202 plus a job ID on first submit; the same ID on a repeat with the same key and body; 409 with a different body; and contract status events ending in done on the events stream.
  8. A good gap list names missing provenance, untyped errors, no idempotency, no documented rate limits, and no versioning policy.
  9. Typical answers: job creation (database is the queue), approval then action (outbox), upload then index (outbox or a status column the indexer polls). Idempotency comes from a unique key per message (job ID, approval ID) checked by the consumer.

Check yourself#

  1. What are the three unusual properties of the model that drive AI application architecture?
  2. Why does a BFF exist, and what must it not become?
  3. When should an AI request be a synchronous call vs an async job vs an event-driven pipeline?
  4. How does the workflow-vs-agent choice change your architecture, not just your prompts?
  5. What does a bounded retrieval service protect you from?
  6. Name four things a model gateway owns that nothing else should.
  7. When is durable execution worth its operational weight?
  8. List the four tenancy models and which is the dangerous default for production.
  9. Why must tenant_id appear in cache keys, not just database queries?
  10. What three things resolve through the config layer, and why does that matter at 2 a.m.?
  11. Why is "retry everything" dangerous at every boundary?
  12. What state does an AI product hold that the model does not, and where does each kind live?
  13. What belongs in a response meta block, and why?
  14. What's the difference between an outcome field and an HTTP error status?
  15. When is a monolith wrong for an AI application?

Further resources#


The ai_product package after this lesson#

The cumulative tree through 13A.5. This lesson adds ports.py, jobs.py and app.py; the earlier files are listed so you can see where they sit:

text
ai_product/
├── __init__.py
├── feature_brief.py      # 13A.1 — AI feature brief + use-case scorer
├── events.py             # 13A.2 — typed event contract + SSE encoder
├── smoother.py           # 13A.2 — chunk smoother
├── progress.py           # 13A.2 — multi-step status tracker
├── approval.py           # 13A.3 — ApprovalGate
├── review_queue.py       # 13A.3 — priority review queue
├── feedback.py           # 13A.3 — feedback events + evalkit exporter
├── failure_ui.py         # 13A.4 — signal -> UserMessage mapper
├── copy_catalog.py       # 13A.4 — copy catalogue with i18n keys
├── markdown_safety.py    # 13A.4 — rendering-safety sketch
├── a11y_lint.py          # 13A.4 — accessibility checklist linter
├── ports.py              # 13A.5 — THIS LESSON: ModelPort, RetrieverPort, ToolsPort, JobStorePort, StorePort + canonical types
├── jobs.py               # 13A.5 — THIS LESSON: in-process job runner (states, idempotency keys + request hashes, atomic claim, fake clock)
└── app.py                # 13A.5 — THIS LESSON: FastAPI app factory, ports in, HTTP/SSE out, fakes + demo worker included

app.py includes _ContractEncoder, a dict-level stand-in for events.SSEEncoder with identical event:/id:/data: framing, so it does not need to import events.py. Lessons 13A.6 to 13B.1 add metrics.py, experiment.py, unit_economics.py, then case_card.py, scope_check.py and scaffold.py; 13B.1's appendix is the consolidated map.


← 13A.4 — AI UX III: Failure States, Edge Cases and Inclusive Design | Module 13A overview | 13A.6 — Product Metrics, Experiments and Unit Economics →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close