Mental model
A foundation model is one probabilistic inference component operating cleanly inside a surrounding deterministic web and backend product—never the architecture itself. Application engineering code owns identity verification, tenant RBAC isolation, durable state schemas, side-effect execution, output sanitization, OpenTelemetry traces, cost controls, and degraded fallback UX when providers stall.
Learning outcomes
- Draw sharp ownership boundaries assigning identity, authorization, transactions, and invariants deterministically to code rather than model prompts.
- Partition system state cleanly by lifetime (
ephemeral request,active conversation,durable business ledger,evaluation holdouts). - Instrument end-to-end trace correlation alongside non-catastrophic degraded fallbacks during upstream model brownouts.
Theory
Treating an AI feature as a thin proxy passing user text straight to an LLM endpoint creates brittle applications vulnerable to cross-tenant leakage, HTML XSS injection, unhandled 429 brownouts, and untracked dollar spend. Full-stack AI systems coordinate six crisp product boundaries synchronously across every turn:
| System Layer | Deterministic Responsibilities | Probabilistic Components | Failure Mode Avoided |
|---|---|---|---|
| Frontend Client UX | Stream abort signals, progress badges, inline citation resolution, sanitizing output | None (renders validated tokens & typed widget props cleanly) | Frozen spinners, DOM XSS via raw generated markdown |
| API & Policy Gateway | JWT auth, tenant isolation, rate limits, PII redaction, budget allocation | Optional low-latency guardrail/intent classifier | Horizontal tenant tampering & wallet exhaustion |
| State & Data Store | Durable Postgres orders/history, atomic idempotency keys, audited tombstones | Embeddings / hybrid reranking over authorized slices | Mixing chat history with authoritative billing records |
| Inference & Tool Runtime | Version-pinned provider adapters, Zod argument checks, primary read verification | Model synthesis & structured tool argument proposal | Vendor lock-in & silent unverified external mutations |
| Observability & Evals | OpenTelemetry GenAI spans (trace_id), P95/cost telemetry, CI holdout gates | Calibrated offline rubric auditing on anonymized samples | Blind prompt debugging & undetected latency regressions |
Notice why provider decoupling and graceful degradation determine real uptime cleanly: wrapping model SDK specifics behind an internal application interface ensures migrating checkpoints or failing over from Vendor A (HTTP 503 spike) to Vendor B or search-only keyword mode preserves user workflows cleanly rather than dumping raw JSON stack traces straight onto UI modals.
typescriptimport { z } from "zod";const VerifiedSupportReplySchema = z.object({status: z.enum(["answered", "insufficient_evidence", "degraded_search_only"]),citedChunkIds: z.array(z.string()),answerMarkdown: z.string().min(1),});export async function handleSupportTurn(params: {traceId: string;sessionUserId: string;tenantId: string;userQuery: string;retrieveAuthorized: (t: string, q: string) => Promise<Array<{ id: string; text: string }>>;callModelAdapter: (q: string, chunks: Array<{ id: string; text: string }>) => Promise<unknown>;}) {// 1. Deterministic ACL retrieval runs BEFORE any probabilistic model invocationconst authorizedChunks = await params.retrieveAuthorized(params.tenantId, params.userQuery);const allowedIds = new Set(authorizedChunks.map((c) => c.id));try {const raw = await params.callModelAdapter(params.userQuery, authorizedChunks);const parsed = VerifiedSupportReplySchema.parse(raw);const sanitizedIds = parsed.citedChunkIds.filter((id) => allowedIds.has(id));return { ...parsed, citedChunkIds: sanitizedIds, traceId: params.traceId };} catch {// 2. Explicit degraded search fallback keeps product useful during model outagesreturn {status: "degraded_search_only" as const,citedChunkIds: authorizedChunks.slice(0, 3).map((c) => c.id),answerMarkdown: "Live AI synthesis is temporarily degraded; top verified reference excerpts are attached below.",traceId: params.traceId,};}}
Trade-offs
Enforcing clear modular interfaces across UI streaming, deterministic RBAC retrieval, provider adapters, and typed post-processing raises initial boilerplate slightly compared to dropping a single 30-line provider SDK call straight inside a server route—a lightweight setup fine strictly for internal single-user hacks. As soon as multi-tenant authorization, compliance logging, regression suites, and multi-provider reliability matter, modular in-process boundaries give teams clean testability and fast cutovers without prematurely splitting everything across slow networked microservices.
Failure modes and misconceptions
- Storing Authoritative Account Data Only in Chat Transcripts: Expecting chat window summaries cleanly to hold subscription status or shipping addresses guarantees stale overwrites and quota blowups.
- Rendering Raw Model HTML / SVG Blindly: Injecting LLM-emitted markup directly into browser DOM enables stored or reflected Cross-Site Scripting (
XSS) via indirect retrieval payloads. - Leaky Provider Exceptions Directly to UI Clients: Exposing vendor quota strings or upstream model endpoints reveals operational architecture while breaking client retry state cleanly.
- Evaluating Model Accuracy Isolated From Product Outcomes: Celebrating offline prompt pass rates while UI stream disconnects, slow retrieval, or missing cancel handlers frustrate real users.
Decision scenario
An AI billing support web portal currently wraps one raw chat provider SDK directly in an API route, stores session limits inside chat system strings, and crashes with blank screens during upstream 429 outages. Architect deterministic JWT/tenant retrieval pre-filtering, Zod response verification, OTel trace correlation, and search-only graceful fallback cleanly.
Which product responsibilities must remain strictly inside deterministic application code rather than being delegated to the foundation model?