AS·180
AI Production Architecture
Putting every part of this volume together into systems that work in production: the roadmap's reference architecture layer by layer (user and UI, API, authentication and RBAC, the AI orchestrator, retrieval, models and tools, the services behind them, evaluation, observability, and the data plane of databases, caches, object storage and audit logs), the life of a request through it, the cross-cutting concerns (security, privacy, reliability, latency, cost, compliance), a typed orchestrator skeleton in Python with interfaces for each component, two worked case studies (an enterprise support assistant and a document-processing pipeline) with capacity and cost estimates, build-vs-buy decisions, team practices, and a production-readiness checklist and design-review rubric for AI systems.
Start here: the whole system on one page
Every chapter in this volume added a part. A production AI feature puts them together around the model:
user → app → gateway (auth, rate limits, budgets, routing)
→ orchestrator (workflow / agent, state, checkpoints)
→ guardrails on input
→ retrieval (RAG index, permissions) → tools (validated, authorised, idempotent)
→ model(s) (routed by task and cost; cached)
→ guardrails on output (schema, safety, link filtering)
→ response (streamed)
all of it traced, evaluated, versioned and monitored
The model is often the smallest part of the code and the largest part of the bill.
Two levers on cost, measured
Caching answers. Many questions repeat. The lab replayed 2,000 customer questions: an exact-match cache answered 93% of them (the lab's question pool was small; real traffic has a longer tail). A semantic cache, which reuses an answer for a similar question, answered up to 98.7%, but at loose settings it served the wrong answer: "Do you deliver on Saturday?" is very similar to "…on Sunday?" (similarity 0.71), and at a threshold of 0.6, 249 customers got another question's answer. At 0.8 there were none.
Choosing the model per request. An illustrative month of 10,000 requests a day (1,500 tokens in, 300 out) at example prices:
| Design | Monthly cost |
|---|---|
| every request to a large model | $2,700 |
| + caching the shared 1,200-token prompt prefix | $1,728 |
| + routing 60% of requests to a small model | $778 |
| + a response cache answering 30% | $544 |
Five times cheaper, if quality holds, which is exactly what the evals of chapters 162 and 175 must show before each step ships.
How deep to go in AI production architecture
Volume 17 defines six mastery levels; for AI production architecture they look like this:
| Level | You can… |
|---|---|
| L1 | name the components of a production AI system and their jobs |
| L2 | assemble a working system from managed services and libraries |
| L3 | explain the trade-offs: caching, routing, guardrails, state, evaluation and observability |
| L4 | trace production problems across components and fix the right one |
| L5 | design and review AI architectures with cost, quality, safety and reliability targets |
| L6 | own AI platforms across an organisation: standards, shared services, governance |
The reference architecture
The roadmap's diagram, expanded:
Layer by layer
| Layer | Responsibilities | Chapters |
|---|---|---|
| API / UI | Endpoints (REST/gRPC), streaming (SSE/WebSockets), sessions, file upload, citations and source display, feedback capture, approval UX for agent actions, accessibility | 179, 173 |
| Auth / RBAC | Authenticate users and services; resolve tenant, roles and scopes; policy decisions (which features, tools, data sources, models); propagate identity to every downstream call | 109–110, 168, 176 |
| AI orchestrator | Assemble context; choose workflow or agent; call retrieval, models and tools; enforce budgets, guardrails and approvals; checkpoint state; produce structured results | 158, 167–171 |
| Retrieval | Query rewriting; hybrid search with ACL filters; reranking; context construction with citations | 159–162 |
| LLM / model gateway | Provider abstraction; routing by task and cost; fallbacks; rate limits and keys; prompt and response caching; cost attribution; self-hosted inference | 156–158, 165–166, 179 |
| Tools / services | Business APIs, databases (read-only where possible), code sandboxes, MCP servers; each with schemas, authorisation, timeouts, idempotency | 168, 172 |
| Evaluation | Inline: input/output guardrails (policy, PII, injection detection, schema validation, grounding checks). Offline: regression suites, red-team suites, model/prompt release gates | 162, 175, 176 |
| Observability | Traces across all steps; metrics (latency, tokens, cost, quality, errors); logs with redaction; drift; dashboards and alerts | 177 |
| Data plane | Application DB (sessions, conversations, users, configurations); vector/search indexes; caches (response, embedding, semantic); object storage (documents, generated media, artefacts); audit log (who did what, with which model and tools) | 150, 160, 170, 178 |
The life of a request
Example: an employee asks the internal assistant, "Can I expense a business-class flight to Singapore next month?"
- UI sends the message with the session id; opens an SSE stream.
- API gateway authenticates (SSO token), applies rate limits; RBAC resolves user, tenant, department, scopes (
policies:read,travel:booknot granted). - Orchestrator loads session state (recent turns, compacted summary), user memories that are relevant (home office: Hyderabad), and the configuration version (prompt v22, tools, retrieval settings, model route).
- Input guardrails: PII check, prompt-injection scan of the message, policy classification (allowed topic).
- Routing (chapter 158): a policy question with retrieval → general model; no agent needed.
- Retrieval: rewrite to a standalone query; hybrid search over the HR/finance policy index filtered by tenant and the user's ACLs; rerank; select 4 chunks with citations.
- Model call through the gateway (pinned model version, prompt cached prefix), streaming tokens back through the orchestrator to the UI.
- Output guardrails: citation validity, grounding spot check (sampled judge in the background), no disallowed content.
- Response ends with citations ("Travel Policy §3.2: business class allowed for flights over 6 hours with director approval"); UI shows sources and a feedback control.
- Observability: one trace with spans for every step, tokens and cost attributed to tenant and feature; quality signals attached.
- Persistence: conversation turn stored; audit log entry written; memory extraction runs asynchronously (nothing durable to store here).
Cross-cutting concerns
| Concern | Architectural decisions |
|---|---|
| Security | Model never the principal; least-privilege tools; taint-aware tool policies; sandboxing; egress allowlists; secrets out of prompts; security eval suite (chapter 176) |
| Privacy and compliance | Data classification of sources; tenant isolation in every store; PII redaction in logs; retention and deletion across conversations, memories, traces and indexes; provider data-processing terms; regional deployment; EU AI Act / DPDP obligations by use case |
| Reliability | Fallback models and degraded modes; timeouts and circuit breakers; idempotent tools; checkpointed workflows; multi-region for critical paths; provider outage runbooks |
| Latency | Streaming; parallel retrieval and tool calls; smaller models for sub-steps; prefix caching; precomputed embeddings; latency budgets per step |
| Cost | Routing; caching; token budgets; batch APIs offline; cost dashboards and per-tenant quotas; quantised self-hosted models where volume justifies |
| Quality | Golden sets and CI gates; online sampled evaluation; feedback loops into datasets; pinned versions with planned migrations |
| Change management | Configuration-as-code for prompts, tools, retrieval and model routes; canary releases; fast rollback (chapter 178) |
An orchestrator skeleton
Interfaces make each component replaceable (a different vector DB, model provider or guardrail) and testable with fakes:
from dataclasses import dataclass, field
from typing import Protocol, Iterator
import time, uuid
@dataclass
class Principal:
user_id: str
tenant: str
scopes: frozenset
@dataclass
class Chunk:
id: str
text: str
source: str
score: float
class Retriever(Protocol):
def search(self, query: str, principal: Principal, k: int) -> list[Chunk]: ...
class ModelGateway(Protocol):
def stream(self, route: str, system: str, messages: list[dict]) -> Iterator[str]: ...
class Guardrail(Protocol):
def check_input(self, text: str, principal: Principal) -> str | None: ... # reason if blocked
def check_output(self, text: str, chunks: list[Chunk]) -> str | None: ...
class Tracer(Protocol):
def span(self, name: str, **attrs) -> "SpanCtx": ...
@dataclass
class Config: # versioned configuration-as-code
version: str = "assistant-v22"
system_prompt: str = "Answer from the sources. Cite [S#]. Say if the sources don't cover it."
route: str = "general-model@2026-09"
k: int = 4
@dataclass
class Orchestrator:
retriever: Retriever
gateway: ModelGateway
guardrail: Guardrail
audit: list = field(default_factory=list)
config: Config = field(default_factory=Config)
def answer(self, principal: Principal, question: str) -> Iterator[dict]:
request_id = uuid.uuid4().hex[:8]; t0 = time.monotonic()
if (why := self.guardrail.check_input(question, principal)):
yield {"type": "refusal", "reason": why}; return
chunks = self.retriever.search(question, principal, self.config.k) # tenant/ACL enforced inside
sources = "\n\n".join(f"[S{i}] ({c.source}) {c.text}" for i, c in enumerate(chunks, 1))
messages = [{"role": "user", "content": f"<sources>\n{sources}\n</sources>\n\nQuestion: {question}"}]
parts = []
for delta in self.gateway.stream(self.config.route, self.config.system_prompt, messages):
parts.append(delta); yield {"type": "delta", "text": delta}
text = "".join(parts)
if (why := self.guardrail.check_output(text, chunks)):
yield {"type": "retract", "reason": why} # UI replaces the answer
yield {"type": "sources", "items": [{"id": c.id, "source": c.source} for c in chunks]}
self.audit.append({"request": request_id, "user": principal.user_id, "tenant": principal.tenant,
"config": self.config.version, "route": self.config.route,
"sources": [c.id for c in chunks], "ms": round(1000 * (time.monotonic() - t0))})
# Fakes for tests and local development
class FakeRetriever:
DOCS = {"acme": [Chunk("travel#3.2", "Business class is allowed for flights over 6 hours with director approval.",
"Travel Policy §3.2", 0.83)],
"globex": [Chunk("g#1", "Globex: economy only.", "Globex Policy", 0.9)]}
def search(self, query, principal, k): return self.DOCS.get(principal.tenant, [])[:k]
class FakeGateway:
def stream(self, route, system, messages):
yield from ["Business class is allowed ", "for flights over 6 hours ", "with director approval [S1]."]
class SimpleGuardrail:
def check_input(self, text, principal): return "empty question" if not text.strip() else None
def check_output(self, text, chunks):
import re
cited = {int(n) for n in re.findall(r"\[S(\d+)\]", text)}
return "invalid citation" if any(n < 1 or n > len(chunks) for n in cited) else None
orch = Orchestrator(FakeRetriever(), FakeGateway(), SimpleGuardrail())
events = list(orch.answer(Principal("u1", "acme", frozenset({"policies:read"})), "Can I fly business to Singapore?"))
"".join(e["text"] for e in events if e["type"] == "delta"), events[-1], orch.audit[-1]["sources"]
# streamed answer with [S1], a sources event for the UI, and an audit record listing travel#3.2
Case study 1: enterprise support assistant
Goal: answer employee and customer questions from policies, product documentation and account data; take limited actions (open tickets, request refunds within policy).
Design:
- Workflow first (chapter 169): route → retrieve → answer for questions (≈ 85% of traffic); an agent with read tools plus two write tools (create ticket, request refund ≤ ₹5,000 with confirmation) for account issues.
- Retrieval: hybrid search with contextual chunking over ~200k document chunks; ACL metadata from the document system; nightly + event-driven re-indexing.
- Models: a small fast model for routing and simple FAQs, a general model for answers, escalation to a stronger model on validation failure (cascade).
- Tools via an internal MCP server with OAuth and per-tool scopes; refund tool idempotent with keys; approvals for all writes.
- Guardrails: injection detection on retrieved emails/tickets; taint policy (external/write tools need approval once untrusted content is in context); PII redaction in logs.
- Evaluation: 400-item golden set (stratified by intent), retrieval recall@5 ≥ 0.9, faithfulness ≥ 0.95, false refusal ≤ 5%; agent task suite in a sandbox with fault injection; red-team suite in CI.
- Observability: OpenTelemetry traces with GenAI attributes; cost per resolved conversation; feedback and escalation rates.
Back-of-envelope:
daily_conversations = 40_000
turns_per_conversation = 3
requests = daily_conversations * turns_per_conversation # 120k model requests/day
mix = {"small": (0.35, 1_500, 150, 0.25, 1.25), "general": (0.60, 7_000, 350, 3.0, 15.0),
"strong": (0.05, 9_000, 600, 15.0, 75.0)} # share, input tok, output tok, $/M in, $/M out (illustrative)
cache_discount_on_input = 0.4 # ~40% of input served from prompt cache
daily_cost = sum(requests * share * ((tin * (1 - cache_discount_on_input * 0.9)) * pin + tout * pout) / 1e6
for share, tin, tout, pin, pout in mix.values())
peak_rps = requests / 86_400 * 4 # peak ≈ 4× average
round(daily_cost), round(daily_cost * 30), round(peak_rps, 1) # ≈ $2,150/day, ≈ $64.6k/month, ≈ 5.6 requests/s at peak
The numbers guide decisions: if the general model dominates cost, test whether the small model meets the bar on more intents; if latency is tight at peak, check provider rate limits and caching before adding complexity.
Case study 2: document-processing pipeline
Goal: extract structured data from 50,000 supplier invoices a month (PDFs and scans, multiple languages) into the ERP, with high accuracy and audit.
Design:
- Asynchronous pipeline (chapter 179): upload → object storage → queue → workers; status API and webhooks.
- Parsing: OCR + layout model; page images kept for the VLM (chapter 173).
- Extraction: VLM with structured outputs (chapter 167) against a versioned JSON Schema; grounding check that every extracted value appears in OCR text; arithmetic validation (line items sum to totals, tax rules).
- Confidence routing: fully validated → auto-post; validation failures → retry with error feedback → human review queue with the page image and highlighted fields.
- Learning loop: human corrections become evaluation cases and, at volume, fine-tuning data for a smaller extraction model (chapter 163), cutting cost per document.
- Controls: supplier allowlist and bank-detail change detection (fraud), idempotent ERP posting, audit trail linking each ERP entry to document, model version and reviewer.
- Metrics: field-level accuracy, straight-through processing rate, review time, cost per document, time to post.
Build vs buy
| Component | Buy / managed when… | Build / self-host when… |
|---|---|---|
| Foundation models | Frontier quality needed; variable volume; no GPU team | High steady volume on narrow tasks; data residency; latency control; fine-tuning needs |
| Vector search | Small team; moderate scale; existing database supports it (pgvector) | Very large scale, special filtering or cost constraints |
| Orchestration framework | Standard patterns; speed matters | Unusual control flow, strict reliability (durable execution), language fit |
| Evaluation / observability platforms | Want UI, annotation workflows and quick start | Strict data-control requirements; OTel-native in-house stack |
| Guardrails | Provider-integrated moderation, managed detectors | Domain-specific policies and checks (always needed in some form) |
Avoid lock-in where it's cheap to do so: an internal model gateway, OpenAI-compatible or framework-neutral interfaces, OpenTelemetry for traces, portable datasets and scorers, and configuration-as-code.
Team practices
- Product, engineering, data and domain experts together define success metrics and golden sets.
- Eval-driven development: no change without evals; failures become tests.
- Design reviews for AI features (rubric below), including security and privacy review.
- Incident response for AI-specific incidents (harmful outputs, data leaks, runaway agents, provider outages) with kill switches and runbooks.
- Documentation: system cards for internal AI features (purpose, data, models, evaluations, limitations, owners).
- Continuous learning: models and tools change quarterly; schedule re-evaluation of model choices.
Production-readiness checklist
- Problem and metrics: clear user problem, success metrics, baseline (non-AI or simpler approach) measured.
- Golden dataset and CI evals with thresholds; red-team suite; agent task suite if applicable.
- Architecture choice justified: workflow vs agent; RAG vs fine-tuning vs tools (chapter 158).
- Identity and authorisation propagated to retrieval and tools; tenant isolation tested.
- Prompt-injection defences: untrusted content labelled; taint-aware tool policies; approvals on consequential actions; egress-safe rendering.
- Structured outputs validated; failure handling with retries and escalation.
- Reliability: timeouts, retries with idempotency, fallbacks, circuit breakers, checkpointing for long workflows.
- Observability: traces with versions, tokens, cost; quality signals; dashboards; alerts; redaction.
- Cost model and budgets per tenant/feature; caching and routing in place.
- Data governance: retention, deletion, consent for memory, provider terms, residency.
- Rollout plan: shadow/canary, guardrail metrics, rollback tested.
- Human oversight: escalation paths, review queues, user feedback, clear disclosure that users are interacting with AI where required.
Design-review rubric
| Dimension | 1: weak | 3: adequate | 5: strong |
|---|---|---|---|
| Problem framing | AI for its own sake | Clear use case | Clear use case, baseline and success metrics agreed |
| Approach selection | Agent by default | Some justification | Simplest adequate design, alternatives evaluated with evidence |
| Evaluation | Vibes | Small test set | Golden set, CI gates, judge calibration, online evaluation, agent suites |
| Security | Prompt-level rules only | Some tool limits | Least privilege, taint policies, approvals, sandboxing, red-team suite |
| Data and privacy | Unclear data flows | Documented flows | Classified data, tenant isolation tests, retention/deletion, consent |
| Reliability | Single provider, no fallbacks | Retries and timeouts | Fallbacks, idempotency, checkpoints, tested degraded modes |
| Observability | Logs only | Traces | Traces + quality + cost + drift with alerts and redaction |
| Cost | Unknown | Estimated | Modelled, monitored, optimised with routing and caching |
| Operability | Manual changes | Some versioning | Configuration-as-code, canaries, rollback, runbooks, owners |
Lab: caching and cost, measured
Setup. Python and scikit-learn on the lab machine. Data, a stated substitute: a stream of 2,000 customer questions drawn from 8 intents, with 4–6 phrasings each plus random lower-casing and greetings; three pairs of intents are deliberate near-misses (Sunday/Saturday delivery, pause/cancel subscription, peanut/dairy allergies). Each intent has one correct answer. Similarity: cosine between character 3–5-gram TF-IDF vectors (a stand-in for an embedding model). Prices are illustrative, not any provider's list price; plug in your own.
Experiment 1: exact vs semantic response caching
A cache entry stores the first question seen for an answer; a later question reuses it if its similarity to the nearest entry is at least the threshold.
| Threshold | Semantic hit rate | Wrong answers among hits | Customers given a wrong answer | Cache entries |
|---|---|---|---|---|
| 0.95 | 0.967 | 0.000 | 0 | 67 |
| 0.90 | 0.968 | 0.000 | 0 | 65 |
| 0.80 | 0.980 | 0.000 | 0 | 40 |
| 0.70 | 0.983 | 0.005 | 9 | 35 |
| 0.60 | 0.985 | 0.127 | 249 | 30 |
| 0.50 | 0.987 | 0.221 | 437 | 26 |
| exact-match cache | 0.932 | 0 | 0 | — |
cosine("Do you deliver on Sunday?", "Do you deliver on Saturday?") = 0.706
- Exact matching already caught 93% because this stream repeats a small pool of phrasings; real traffic has a long tail of unique wording, so expect a much lower exact-hit rate and a bigger relative gain from semantic matching.
- Semantic matching added up to 5.5 points of hits, and below 0.8 it started answering near-miss questions with the wrong intent's answer. The errors come in exactly the pairs where one word changes the answer.
- Mitigations: choose the threshold from labelled traffic (here, 0.8); cache only answers that don't depend on user data or time; scope keys by tenant, locale and document version; invalidate on content updates; and for high-stakes answers, verify a cache hit (or skip caching).
Experiment 2: a cost model
10,000 requests a day for 30 days; each has 1,500 input tokens (of which 1,200 are a shared system prompt and policy text) and 300 output tokens. Illustrative prices: large model $3 / $15 per million input/output tokens; small model $0.25 / $1.25; cached input at 10% of the input price.
| Design | Monthly | Per 1,000 requests |
|---|---|---|
| all requests to the large model | $2,700 | $9.00 |
| + prompt caching of the shared 1,200-token prefix | $1,728 | $5.76 |
| + route 60% of requests to the small model | $778 | $2.59 |
| + response cache answering 30% of requests | $544 | $1.81 |
Output tokens cost 5× input tokens here, so after prompt caching, output dominates the large-model bill; shorter answers (and structured outputs instead of prose where possible) are a cost lever too. Each step is only a saving if quality holds: routing needs a classifier or rules plus evals per route; caching needs the error analysis in Experiment 1.
Try it yourself
- Replace the TF-IDF similarity with a neural embedding model and rerun Experiment 1. Do near-miss similarities rise or fall?
- Add a "verify" step for semantic hits (a cheap model checks that the cached answer fits the new question) and model its cost.
- Extend the cost model with retrieval (embedding queries, vector DB costs) and observability storage.
- Write the design-review document for the tiffin assistant using this chapter's rubric, with your cost model and caching thresholds.
Revision sheet: AI production architecture
Key ideas
- Reference architecture: client → gateway (auth, quotas, routing, caching) → orchestrator (workflow/agent, state) → retrieval, tools, models → guardrails → response; cross-cutting observability, evaluation, versioning, security.
- Life of a request: authenticate, budget check, input guardrails, retrieve with permissions, assemble context, call model(s), validate/structure output, output guardrails, stream, log/trace, collect feedback.
- Cost levers: model routing/cascades, prompt caching, response caching (exact and semantic), shorter outputs, batch APIs for offline work, quantised self-hosting at scale.
- Reliability: timeouts, retries with idempotency, fallbacks across models/providers, graceful degradation (e.g. "search results only" mode).
- Build vs buy: managed APIs and platforms for speed; self-host for control, data residency or unit cost at scale.
- Team practices: evals in CI, prompt/version control, incident runbooks, red-team cadence, cost reviews.
- Production readiness: quality bar met on golden sets, security review, privacy review, SLOs, dashboards and alerts, rollback plan, user feedback loop.
Numbers to remember
- Lab: semantic cache threshold 0.8 → 98.0% hits, 0 wrong; 0.6 → 249 wrong answers out of 2,000.
- Lab: Sunday/Saturday questions similarity 0.71.
- Illustrative costs: $2,700 → $544/month with prompt caching, routing and response caching.
Pitfalls
- Semantic caches without labelled-traffic thresholds or tenant scoping.
- Routing to cheaper models without per-route evals.
- No fallback when the model provider has an outage.
- Architecture with no place to enforce permissions or budgets.
- Treating the prototype's prompt as the product: no versioning, no evals, no monitoring.
Glossary
- Model routing / cascade: choosing a model per request / trying cheap models first and escalating.
- Semantic cache: reusing answers for similar requests.
- Prompt caching: provider-side reuse of processed prompt prefixes.
- Graceful degradation: reduced but safe functionality during failures.
- Guardrails: checks on inputs and outputs enforcing policy.