The Production AI Platform Underneath a SaaS

What a SaaS company builds once, centrally, so ten product teams can ship AI features without each one reinventing keys, guardrails, and a phone bill.

This chapter replaces the old Phase 5 of the plan. It assumes you've done Phases 1–3. You can build an agent loop. You know tool use, MCP, RAG, and prompt caching. You've added a first pass of guardrails and evals.

This chapter is about what changes when that agent isn't a personal project anymore. It's one feature among dozens, built by different teams. It serves customers who pay you and who don't trust each other with their data.

The shape: a reference architecture

Picture a SaaS company with ten product teams. The support team wants an AI copilot that drafts replies. The search team wants natural-language search. The reporting team wants an agent that writes a weekly summary. Sales wants a research agent.

Say each team calls Anthropic's or OpenAI's API directly from their own service. Now you have ten different places holding API keys, ten different retry policies, and ten different logging formats. Worse, there's no company-wide answer to "how much are we spending on AI this month, and can we turn it off if one customer starts abusing it?"

The fix is the same one you already know from plain backend systems: put a shared layer in front.

Four product features, support copilot, search copilot, report writer and sales agent, all send their calls through one AI gateway. The gateway handles keys and auth, routing, fallback, per-tenant rate limits, caching, cost logging, tracing and guardrail checks. Behind it sit three shared services: model providers such as Claude and GPT, a retrieval service with vector search and an ACL filter, and a tool or MCP layer for calendars, tickets and CRM. All three report into eval and observability (traces, evals, cost dashboards) and are governed by policy and guardrails (PII redaction, injection checks, human approval).
The shape: a shared AI platform in front of every feature. Read it as: every feature is a client of the platform. None of them talks to a model, a vector store or a tool directly. Each concern (auth, cost, safety, evals) is built once, in the shared layer, instead of once per team.

Box by box:

  • Product features are the things a customer actually sees. Each one is a client of the platform, not a reimplementation of it.
  • AI gateway is the front door for every LLM call in the company. The LLM/AI gateway covers it in depth.
  • Retrieval service is a shared way to fetch context for RAG. For every chunk it returns, it has to know whether the asking user is allowed to see it (Permission-aware retrieval).
  • Tool/MCP layer is where agents reach out into the world: internal APIs, ticketing systems, calendars. You already met MCP in Phase 2. Here it needs the same tenant and permission boundaries as retrieval.
  • Eval + observability is how the company knows the platform is working, not just running (LLM observability to Evals as a lifecycle).
  • Policy/guardrails sits logically beside the gateway (often inside it, as middleware). It enforces rules that must never depend on a single team remembering to write them (Security).

None of these boxes has to be a separate physical service on day one. A startup's "AI gateway" might be a shared Python library. The architecture is the same either way. What matters is that these five responsibilities exist somewhere, on purpose, rather than being reinvented per team.

The LLM/AI gateway

AI gateway — a single service that sits between your product code and the model providers (Anthropic, OpenAI, Google, ...). Your application calls one internal API instead of calling each provider's API directly. It's the same idea as an API gateway in front of microservices, aimed at the specific failure modes of LLM calls: provider outages, per-model pricing, and per-customer cost blowups.

The jobs a gateway does

Job Why it needs to be centralized
Keys One place holds provider API keys, rotated centrally. Product code never sees a raw key.
Routing Send a request to the right model — maybe a cheap model for simple asks, a strong one for hard ones (Cost and latency engineering).
Fallback If Anthropic is down or rate-limits you, retry on a backup model/provider automatically instead of the feature erroring out.
Retries Transient errors (network blips, 5xxs) get retried with backoff, without every team writing that logic.
Rate limits Per tenant, per team, per API key — so one customer's traffic spike doesn't starve everyone else (Multi-tenancy).
Caching Identical or near-identical requests don't hit the provider twice (Cost and latency engineering).
Logging/tracing Every call is recorded once, in one format, so observability (LLM observability) has something to read.

Real gateways, so you know the landscape

Companies build this in-house or buy/self-host one of these. As of September 2026:

Tool What it is Notable
LiteLLM Open-source proxy + SDK, one OpenAI-compatible API in front of 100+ providers. Load balancing across providers/regions/keys, automatic fallback with cooldowns on 429s, per-key/per-team spend limits, response and semantic caching (Redis/S3/GCS).
Portkey Gateway with 50+ built-in guardrails, sold as "control panel for production AI." Metadata tags per request (tenant, use case) drive cost attribution; budgets and rate limits scoped per client.
Cloudflare AI Gateway Managed proxy at Cloudflare's edge. Caching from 1 minute to 1 year; fixed or sliding-window rate limiting; core analytics/caching/rate-limiting tier is free.
AWS Bedrock Guardrails Content-filtering + prompt-attack protection, model-agnostic (works even for non-Bedrock models). Governance is IAM-based, not a purpose-built AI console — no virtual keys or per-developer budgets out of the box.
Azure API Management (AI gateway capabilities) Import OpenAI-compatible or passthrough LLM endpoints as ordinary APIM APIs. Reuses APIM's existing policy engine (rate limiting, auth) for LLM traffic.

Inferred: most large SaaS companies with several AI features do not buy a single vendor gateway wholesale. Instead they use one of these (often LiteLLM, since it's open source and self-hostable) as the routing/fallback core, and layer their own auth, tenancy, and audit logging on top. Compliance and billing integrations tend to be company-specific, so that top layer usually has to be built in-house.

What calling through a gateway looks like

The point of a gateway is that your product code doesn't know which provider answered.

# product code — talks to the gateway, not to Anthropic or OpenAI directly
import httpx

resp = httpx.post(
    "https://ai-gateway.internal/v1/chat/completions",
    headers={"Authorization": "Bearer <service-token>"},
    json={
        "tenant_id": "acme-corp",          # who to bill / rate-limit
        "feature": "support-copilot",       # what to attribute cost to
        "model": "claude-sonnet-5",         # gateway may substitute a fallback
        "messages": [{"role": "user", "content": "Draft a reply to this ticket..."}],
    },
    timeout=30,
)

Everything in Multi-tenancy to Security is really an elaboration of what the gateway (or the layer right next to it) does with the tenant_id, feature, and model fields in that one request.

Multi-tenancy

Tenant — one customer (or, inside your own company, one team) whose data and usage must stay separate from every other tenant's. A multi-tenant SaaS serves many tenants from shared infrastructure. That's cheaper to run than giving each customer their own stack. But it means the platform, not the database alone, has to enforce the separation.

What needs isolating

  • Data. Tenant A's documents must never appear in Tenant B's retrieval results or prompts. This is Permission-aware retrieval's problem, scaled from "user vs. user" to "company vs. company."
  • Prompts. If you store per-tenant custom instructions or fine-tuned prompt templates, they must be looked up by tenant ID, not left in a shared config that a bug could cross-wire.
  • Caches. A cache key that doesn't include the tenant ID will happily serve Tenant A's cached answer to Tenant B. This is an easy, embarrassing bug: always put tenant_id in the cache key.

Quotas and cost attribution

Every gateway in The LLM/AI gateway's table supports budgets: a spend cap per tenant, team, or API key, over a time window (daily/weekly/monthly). The mechanism underneath a budget is usually metadata. Every request is tagged (tenant_id, feature, sometimes user_id), and cost is summed by tag after the fact. Portkey calls this pattern "metadata" tagging. The shape is the same whichever gateway you use: tag at the call, aggregate later.

This matters for a business reason beyond engineering. Say a customer is on a plan that includes "1,000 AI-assisted replies per month." You need per-tenant token counts to enforce that, and per-tenant cost to know whether that plan is even profitable.

The noisy-neighbor problem

Noisy neighbor — one tenant's heavy usage degrades service for every other tenant sharing the same infrastructure. In an AI platform this shows up like this: one customer runs a huge batch job or a runaway agent loop. That eats your whole per-minute rate limit with the model provider, and every other customer's requests start queuing or failing.

Defenses, in increasing order of isolation (and cost):

  1. Per-tenant rate limits at the gateway (The LLM/AI gateway) — the cheapest fix, and usually enough.
  2. Separate request queues per tenant tier — a free-tier queue and a paid-tier queue, so a free-tier spike can't delay paying customers.
  3. Dedicated provider capacity or a separate API key per large tenant — for enterprise customers whose contract requires it; expensive, reserved for the few tenants big enough to justify it.

Permission-aware retrieval

This is the hardest SaaS-specific problem in this whole chapter, worth its own section.

Here's the setup. Your product has RAG (you built this in Phase 2). A user asks a question. The system retrieves relevant documents from a shared vector store, and the LLM answers using them.

Inside one company, different employees can see different documents. An intern shouldn't see the board deck. A contractor shouldn't see other clients' files. The AI must only retrieve documents the asking user is already allowed to see — nothing more, no matter how relevant it is.

Index time vs. query time

ACL (access control list) — the set of users or groups allowed to see a specific piece of data.

  • Index-time enforcement: when a document is chunked and embedded, each chunk is tagged with its ACL as metadata (which user IDs or group IDs can see it). This has to be kept in sync whenever the source document's permissions change.
  • Query-time enforcement: the retrieval query itself includes a filter — "only return chunks whose ACL metadata overlaps with this user's groups" — applied as part of the nearest-neighbor search, not after it.
# query-time ACL filter, applied inside the vector search itself
results = vector_db.query(
    query_embedding=embed(user_question),
    top_k=8,
    filter={
        "tenant_id": current_user.tenant_id,             # never cross tenants
        "acl_groups": {"$in": current_user.group_ids},    # only docs this user can see
    },
)

The consensus in current enterprise-RAG guidance is that the ACL filter belongs inside the vector database's query. It should not be a second pass in application code that discards disallowed results afterward. Here's why: application logic can have a bug, or a prompt-injection attack can convince the agent to call the retrieval tool directly with different arguments. Either way, a filter-after-the-fact never runs. A filter baked into the query still applies.

The oversharing risk — Microsoft 365 Copilot's public lesson

Microsoft 365 Copilot reads everything a user can technically access across SharePoint, OneDrive, Teams, and Exchange. It then surfaces it through a plain-language prompt. This exposed a problem industry-wide: many organizations had years of accumulated permission debt. Think broad "Everyone except external users" sharing links, or inherited folder permissions nobody audited. That debt was harmless when finding a file required knowing it existed and clicking through folders. Copilot made all of it searchable by asking a question in plain English.

Concentric AI's Data Risk Report found an average of about 802,000 files at risk per organization. Roughly 16% of business-critical data was overshared this way. Copilot didn't invent or leak any secrets. It just faithfully surfaced files a user was technically permitted to open but was never intended to see. A second, related issue: Copilot's outputs don't automatically inherit the sensitivity labels of the source files. So a summary generated from a confidential document can end up unlabeled, and a human who didn't realize the source was sensitive can then share it further.

Microsoft's response has been a governance layer, not a retrieval-logic fix. It added a Copilot security dashboard for oversharing and compliance insights in the admin center. It also bundled Microsoft Purview and SharePoint Advanced Management with Copilot licenses, so admins can find and fix existing overshared content before turning Copilot loose on it.

The lesson for your own platform: permission-aware retrieval isn't only a retrieval-code problem. It also requires your source systems' permissions to already be correct. The AI will faithfully expose whatever access already exists, at a scale and searchability the old UI never had.

Building it, concretely

  1. Every document/chunk carries tenant_id and an ACL (user IDs or group IDs) as first-class metadata. Keep it in sync with the source system's real permissions (a nightly reconciliation job is common, since permission changes elsewhere won't automatically flow to your index).
  2. Every retrieval call carries the asking user's identity and group memberships, resolved server-side — never trust a client-supplied permission claim.
  3. The ACL filter runs inside the vector query, as shown above, not as a post-filter.
  4. Audit which documents were actually retrieved and shown to which user, per Security's audit logging — so an oversharing incident can be found and explained after the fact, not just prevented in theory.

Data privacy and compliance

PII redaction

PII (personally identifiable information) — data that identifies a specific person: names, emails, phone numbers, government IDs, etc. Say your feature sends customer support tickets or documents to an LLM. Those tickets likely contain PII belonging to your customer's customers — people who never agreed to have their data sent to a third-party model provider.

Microsoft Presidio is the widely used open-source option. An "Analyzer" finds PII using named-entity recognition, regex, and checksum validation (for example, a valid credit-card checksum). An "Anonymizer" then redacts it, replaces it with a placeholder, masks part of the string, or hashes it.

from presidio_analyzer import AnalyzerEngine
from presidio_anonymizer import AnonymizerEngine

text = "Call John Smith at 555-123-4567 about invoice #4021."
findings = AnalyzerEngine().analyze(text=text, language="en")
clean = AnonymizerEngine().anonymize(text=text, analyzer_results=findings).text
# clean == "Call <PERSON> at <PHONE_NUMBER> about invoice #4021."

Run this before the text reaches the LLM gateway for anything sent to a model outside a zero-data-retention agreement, and again on tool outputs coming back from systems you don't fully trust.

Zero data retention vs. "we don't train on your data"

These are two different promises, and vendors state them separately on purpose:

Promise What it actually means
No training on your data The vendor won't use your prompts/completions to improve its models. Your data may still be stored temporarily (for abuse monitoring, debugging, legal holds).
Zero data retention (ZDR) Prompts and completions are processed and then deleted — not retained beyond the API call's lifecycle — subject to exceptions for legal compliance or misuse detection.

Both Anthropic and OpenAI offer ZDR terms for eligible enterprise customers. But eligibility is not automatic. Anthropic's ZDR arrangements are approval-based and vary by product (Claude API vs. Claude Code vs. Claude.ai). A no-training clause in your contract does not by itself guarantee ZDR. The practical rule: read what your specific agreement says for the specific product surface you're using. Don't assume one clause implies the other.

Regional data residency

Data residency — a guarantee that customer data is processed and stored within a specific geographic region (e.g., the EU), usually required for regulatory reasons (GDPR-adjacent customer demands, government contracts).

As of September 2026, OpenAI offers EU data residency for ChatGPT Enterprise, ChatGPT Edu, and its API platform. Anthropic's own API routes requests globally by default. The one region you can pin to on the first-party API is the US (the inference_geo: "us" parameter, which costs 1.1x). There is no EU pin on Anthropic's own API. So the practical path for EU residency with Claude is an EU regional endpoint on AWS Bedrock or Google Vertex AI.

Here's a sharp illustration of how easy this is to get wrong. Microsoft's docs state that Anthropic models inside Microsoft Copilot (formerly Microsoft 365 Copilot) are excluded from the EU Data Boundary. They are therefore off by default for EU/EFTA and UK tenants. A customer relying on "Copilot is EU Data Boundary compliant" could easily miss that detail.

If you sell into regulated industries or the EU, data residency is a per-model-provider, per-region fact you have to track explicitly — it is not implied by your own company's hosting region.

Customer opt-outs

Give tenants (and, where relevant, individual end users) a way to turn AI features off entirely. This should mean more than "don't show me the AI button." It should mean "don't send my data to any model provider." Usually this is a tenant-level flag that the gateway checks before routing a request. When the flag is on, the gateway should fail the call (or fall back to a non-AI code path) rather than silently sending data anyway.

LLM observability

You already log token usage per turn from Phase 1. At platform scale, that single habit grows into three separate needs: tracing, cost attribution, and quality signals — each with its own tooling.

Tracing: OpenTelemetry's GenAI conventions

Trace — a record of everything that happened to serve one request. It's structured as nested spans (one span per LLM call, per tool call, per retrieval step), so you can reconstruct the whole call tree after the fact.

OpenTelemetry is the vendor-neutral standard for this across all of observability. It has a GenAI-specific extension (gen_ai.* attributes: model name, token counts, etc.). Its current status matters if you're picking it as a foundation. As of mid-2026 the GenAI semantic conventions are still marked Development, not Stable. In June 2026 they were split out of the main OpenTelemetry spec into a dedicated semantic-conventions-genai repository. As of July 2026, no gen_ai.*-prefixed attribute had graduated to Stable. Practically: you can build on it today (major coding tools already emit gen_ai.* telemetry). But expect attribute names and shapes to still change before 1.0.

Cost and tokens, sliced two ways

Track token counts and estimated cost per call, then roll them up by:

  • Feature — "the support copilot cost $4,200 last month" tells product leadership whether a feature is worth its cost.
  • Tenant — feeds the quota/attribution system from Multi-tenancy.

Tools people actually use

Tool Model Best for
Langfuse Open source, self-hostable, OpenTelemetry-native Teams that want full data control and to run it inside their own infra.
LangSmith Proprietary SaaS (self-managed option on Enterprise) Deepest integration if you're already using LangChain/LangGraph.
Arize Phoenix Free, notebook-first, built on OpenInference conventions Strongest built-in evaluation engine for offline, dataframe-driven analysis.
Datadog LLM Observability Proprietary, part of Datadog Enterprises already standardized on Datadog for infra monitoring — same dashboards, added GenAI-aware spans and evaluators.

Inferred: the "roll your own with OpenTelemetry + Grafana" option is viable for a team already running that stack for everything else. But you'll write more glue code than with a purpose-built tool. Most general infra tools (Datadog aside) don't natively understand "this span is semantically wrong" — only "this span was slow or errored."

Evals as a lifecycle

Phase 3 had you write 15–20 test cases in promptfoo and run them in one command. At platform scale, evals stop being a one-time test suite and become a recurring lifecycle with four stages. (This section is the overview. The evals engineering guide in the expert track covers each stage in depth.)

Offline, before deploy: gold-set tests run in CI on every prompt or model change. Then, online in production: live metrics and A/B tests on real traffic. From there, a sample of responses, or flagged ones, goes to a human review queue. What the reviewers find feeds back into the gold set, and the loop starts again.
Evals as a loop, not a one-time test. Read it as: the offline gold set only covers inputs someone thought to write. Production shows you the inputs nobody thought of. The human review queue turns those into new gold-set cases, so the offline tests get better every cycle.

Offline: gold sets in CI

A gold set is a curated collection of inputs with known-good expected outputs (or grading criteria). It's versioned like code, and run automatically whenever a prompt or model changes. This is exactly the promptfoo pattern from Phase 3, scaled up to the whole platform's shared test suite rather than one team's 20 cases.

LLM-as-judge

LLM-as-judge — using a second LLM call to grade the first LLM's output against a rubric, instead of (or alongside) exact-match string checks. This is necessary because most real outputs ("summarize this ticket," "draft a reply") don't have one correct string to match against. The judge model is given the rubric, the input, and the output, and it returns a score or pass/fail. That means the judge prompt itself needs its own small gold set. Otherwise you're trusting an unverified grader.

Online: production metrics and A/B tests

Offline evals only cover the inputs you thought to write. Online, you track:

  • User actions after an AI response — did they accept the drafted reply, edit it, or discard it?
  • Thumbs up/down, where you collect it.
  • A/B tests comparing a new prompt or model against the current one, on a slice of real traffic, before rolling out further (Prompt and model versioning, rollout).

Human review queues

A sampled or flagged subset of real outputs is routed to a human reviewer. Some are sampled randomly, for baseline quality tracking. Others are flagged automatically (low-confidence, guardrail near-miss, negative user reaction) for targeted review. This is also where corrected labels come from, to grow the gold set over time — the loop in the diagram above.

Regression when switching models

Promptfoo's newer red-teaming and CI tooling turns a model migration ("should we move this feature from Sonnet to a newer model?") into a measurement rather than a leap of faith. Run the existing gold set against both models, and read the diff on quality, cost, and latency together. That beats eyeballing a handful of examples. Add regression cases every time a real production bug is found — the same discipline as adding a unit test for a fixed bug in ordinary software.

Prompt and model versioning, rollout

Treat a prompt template and a model choice as a deployable artifact with a version number. It shouldn't be a string baked into application code. Apply the same discipline you already use for your own service's code.

Feature flags for prompts and models

Tools like LaunchDarkly's AI Configs apply ordinary feature-flag mechanics to prompt/model selection. You can target a specific prompt version or model to a user segment, and change it at runtime without a deploy. Then you read back quality/latency/cost metrics per flag variation to decide whether to expand or roll back.

Shadow mode and canaries

  • Shadow mode — the new prompt/model runs on real traffic alongside the current one, but its output is only logged and scored, never shown to the user. This lets you see real-world quality and cost before any customer is exposed to it.
  • Canary rollout — the new version is shown to a small percentage of real users (or one low-risk tenant) first, with the older version protecting everyone else. It's expanded only if quality/latency/cost thresholds hold.
Stage 1, shadow: 100% of traffic goes to the current prompt v3, which users see. A copy also goes to the candidate prompt v4, which is scored but never shown. When shadow looks good, stage 2, canary: 95% of traffic goes to v3 and 5% goes to v4, real users watched closely. When the canary holds for N days, stage 3: 100% of traffic goes to v4 and v3 is retired.
Shadow, then canary, then full rollout. Read it as: each stage risks a little more. In shadow, no user sees v4 at all. In canary, only a small slice does. Only after both stages hold does everyone move to v4.

Model migration as a rollout, not a switch

Combine Regression when switching models's offline regression check with a canary. Run the gold set, look at the diff, then canary on real traffic before fully cutting over. Gold sets don't cover every production input, and models can regress on cases nobody thought to write down.

Cost and latency engineering

Model routing: small model first

Not every request needs your strongest model. A common pattern: try a fast, cheap model (claude-haiku-4-5 at $1/$5 per million input/output tokens) first. If its own confidence is low, or a classifier flags the request as complex, escalate to a stronger model (claude-sonnet-5 at $2/$10 per million tokens). LiteLLM's "auto routing" feature does a version of this automatically: simple prompts go to cheaper models, hard ones go to stronger ones.

Caching: two kinds, two different risk profiles

Cache type What it matches Risk
Prompt cache (covered in Phase 1) Exact prefix of the request (system prompt, tools, stable context) Low — it's an exact match, so a cache hit is always the same input.
Semantic cache Requests whose meaning is similar, via embedding similarity above a threshold Real — a threshold that's too loose returns a wrong answer with a confident 200 OK. "How do I cancel my subscription?" and "how do I keep my subscription?" can embed close enough together to collapse at a 0.80 threshold.

Semantic caches also have no natural invalidation trigger the way an exact-key cache does. If the underlying fact changes (a price update, a policy revision), nothing tells the cache its stored answer is now stale. You need a TTL or an explicit invalidation hook tied to whatever content changed.

Rule of thumb from current practice: tune the threshold to the cost of being wrong. Use 0.95+ for anything like billing or legal answers. Go looser (around 0.80) for tone-of-voice rewrites, where a near-miss barely matters.

Batching: the Batch API

Anthropic's Message Batches API gives a 50% discount on both input and output tokens, for requests that don't need an immediate response. You submit up to 100,000 requests in one batch. Anthropic processes them on a best-effort basis (often within about an hour for small batches, with a 24-hour SLA), and you poll for results. Output quality and determinism are identical to the synchronous API. The only trade-off is latency. Good fits: nightly document processing, bulk classification, and running your offline eval gold set (Evals as a lifecycle) cheaply.

Streaming

You built this in Phase 2. At the platform level, the only addition is that the gateway needs to proxy streamed responses (server-sent events) through without buffering the whole response first. Buffering defeats the point, and it adds latency exactly where users notice it most.

Budgets and kill switches

A kill switch is a single flag, checked by the gateway, that can disable an entire feature (or route all its traffic to a canned fallback response) in seconds, without a deploy. Use it when a cost spike, an outage, or a bad rollout needs to stop right now, not after a fifteen-minute build pipeline. Pair it with the per-tenant budgets from Multi-tenancy. When a tenant's spend crosses its cap, the gateway should reject further calls (or downgrade to a cheaper model) automatically, rather than paging a human to do it manually.

Security

Prompt injection, at platform scale

You covered the basics in Phase 3. Here's a harder finding that should shape how much you rely on detection alone.

In October 2025, researchers from OpenAI, Anthropic, and Google DeepMind, together with several universities, published a study testing twelve published prompt-injection defenses. They tested against adaptive attackers: ones who could see and adapt to the defense, using techniques like gradient descent and reinforcement learning to search for a bypass. Every defense fell. Attack success rates climbed above 90%, and past 98% in several cases.

The field has drawn a clear takeaway from this: prompt injection cannot be reliably detected at the input layer. So the security boundary has to move from "catch the injection" to "limit what an injected agent can actually do."

Tool permissioning and sandboxing

Two concrete practices that follow from that shift:

  • Least-privilege tool permissions. An agent gets only the tools and scopes a specific task needs, not the permissions its role might need someday. Say a support agent's job is "read tickets, draft replies." It should not also hold a token that can delete customer accounts, even if a human with that job title could.
  • Sandboxing. Any tool that executes code or touches the filesystem/network runs inside an isolated environment. For example: containers with gVisor/Kata, a read-only root filesystem, no network unless the specific task needs it, dropped Linux capabilities, a non-root user. Treat the agent as an untrusted process, the same way you'd treat code from an untrusted user. The tool call itself is not the security boundary — the sandbox around it is.

Audit logs

Every tool call an agent makes — not just the LLM calls — should be logged with enough detail to answer "what did this agent do, on whose behalf, and why" after the fact. Log the timestamp, tenant, acting user, tool name, arguments, and result. This is what turns Building it, concretely's "audit which documents were retrieved" from a nice idea into something you can actually query during an incident.

OWASP Top 10 for LLM Applications (2025)

The current edition (updated late 2024/2025 to account for agentic systems) is the standard checklist to run your platform against:

# Risk One-line meaning
LLM01 Prompt Injection Untrusted input changes what the model does, against the app's intent.
LLM02 Sensitive Information Disclosure The model reveals data it shouldn't (secrets, PII, other tenants' data).
LLM03 Supply Chain A vulnerable/malicious third-party model, dataset, or plugin gets pulled in.
LLM04 Data and Model Poisoning Manipulated training/fine-tuning/embedding data introduces bias or backdoors.
LLM05 Improper Output Handling Model output is trusted and passed downstream unvalidated (injection, SSRF, RCE).
LLM06 Excessive Agency The system grants the model more function/permission/autonomy than the task needs.
LLM07 System Prompt Leakage The hidden system prompt (and any secrets in it) gets extracted.
LLM08 Vector and Embedding Weaknesses Weaknesses in how embeddings/vector stores are generated, stored, retrieved.
LLM09 Misinformation Confidently wrong output is trusted and acted on.
LLM10 Unbounded Consumption Uncontrolled resource use — the DoS/cost-blowup risk Budgets and kill switches defends against.

Note the reordering versus the original 2023 list. Sensitive Information Disclosure jumped from sixth to second place in the 2025 edition. That's a direct reflection of how much of this chapter (Permission-aware retrieval and 5) the industry has learned it needs.

Build it yourself: a minimal AI gateway

This is a weekend-sized project that gives you the real shape of The LLM/AI gateway, not a toy. You'll build a FastAPI service that sits in front of the Anthropic API. It does four things a bare API call doesn't: per-tenant rate limiting, model fallback, cost logging, and a trace per call.

# gateway.py — minimal AI gateway: rate limit, fallback, cost log, trace
import time, json, uuid
from collections import defaultdict
from fastapi import FastAPI, HTTPException, Header
from pydantic import BaseModel
import anthropic

app = FastAPI()
client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from env

# --- per-tenant token-bucket rate limiter (in-memory; use Redis for real multi-instance use) ---
BUCKETS = defaultdict(lambda: {"tokens": 20, "last": time.time()})
RATE = 20       # max requests
PER_SECONDS = 60

def check_rate_limit(tenant_id: str):
    b = BUCKETS[tenant_id]
    now = time.time()
    b["tokens"] = min(RATE, b["tokens"] + (now - b["last"]) * (RATE / PER_SECONDS))
    b["last"] = now
    if b["tokens"] < 1:
        raise HTTPException(status_code=429, detail="tenant rate limit exceeded")
    b["tokens"] -= 1

# --- cost table, per million tokens (see Section 9.1) ---
PRICES = {
    "claude-sonnet-5": {"in": 3.00, "out": 15.00},
    "claude-haiku-4-5": {"in": 1.00, "out": 5.00},
}

def estimate_cost(model: str, usage) -> float:
    p = PRICES[model]
    return (usage.input_tokens / 1_000_000 * p["in"]
            + usage.output_tokens / 1_000_000 * p["out"])

class ChatRequest(BaseModel):
    model: str = "claude-sonnet-5"
    fallback_model: str = "claude-haiku-4-5"
    messages: list

@app.post("/v1/chat")
def chat(req: ChatRequest, x_tenant_id: str = Header(...)):
    check_rate_limit(x_tenant_id)
    trace_id = str(uuid.uuid4())
    start = time.time()
    model_used = req.model
    try:
        resp = client.messages.create(
            model=req.model, max_tokens=1024, messages=req.messages,
        )
    except anthropic.APIStatusError:
        # fallback: primary model/provider unavailable, retry on the cheaper model
        model_used = req.fallback_model
        resp = client.messages.create(
            model=req.fallback_model, max_tokens=1024, messages=req.messages,
        )

    cost = estimate_cost(model_used, resp.usage)
    trace = {
        "trace_id": trace_id,
        "tenant_id": x_tenant_id,
        "model_requested": req.model,
        "model_used": model_used,          # differs from requested if fallback fired
        "fallback_used": model_used != req.model,
        "input_tokens": resp.usage.input_tokens,
        "output_tokens": resp.usage.output_tokens,
        "cost_usd": round(cost, 6),
        "latency_ms": round((time.time() - start) * 1000),
    }
    print(json.dumps(trace))  # replace with your logger / OTel exporter (Section 6.1)

    return {"trace_id": trace_id, "text": resp.content[0].text, "cost_usd": trace["cost_usd"]}

This is deliberately small. A real gateway would go further. It would move the rate limiter to Redis (so it works across multiple instances), add the caching and guardrail middleware from The LLM/AI gateway and 10, and export traces to Langfuse or an OTel collector instead of printing JSON.

But every one of those additions plugs into the same four places this skeleton already has:

  • a place where rate-limiting checks happen
  • a place where a fallback can fire
  • a place where cost gets computed
  • a place where a trace gets emitted

Done when

  • ☐ A request from tenant-a and tenant-b are rate-limited independently — spamming one never blocks the other.
  • ☐ Killing your primary model (e.g., pointing req.model at a model name that doesn't exist) causes a fallback to the secondary model, and the response still succeeds.
  • ☐ Every request prints a trace line with tenant_id, tokens in/out, cost_usd, and latency_ms — and you can grep your logs to answer "how much did tenant-a spend today?"
  • ☐ You can explain, without looking at the code, what happens on the wire between a rate-limit rejection and a fallback firing. They're different failure paths and shouldn't be confused.

Check yourself

Question 1

Why should the ACL filter in permission-aware retrieval run inside the vector database's query, rather than as a filter applied to results afterward in application code?

Show answer

Because a post-filter is a thin defense. If application logic has a bug, or an agent is tricked (for example, via prompt injection) into calling the retrieval tool directly with different arguments, the post-filter step never runs, and disallowed documents flow through. A filter baked into the ANN query itself is enforced at the data layer, regardless of what the application code around it does.

Question 2

What's the difference between "no training on your data" and "zero data retention," and why can't you assume one implies the other?

Show answer

"No training" means the vendor won't use your prompts/completions to improve its models, but may still store them temporarily for abuse monitoring or debugging. "Zero data retention" means the data is deleted after processing, not just excluded from training. A vendor can offer one without the other. Eligibility for ZDR is often approval-based and varies by product surface, so you have to check your specific agreement, not infer it from a general privacy claim.

Question 3

A semantic cache serves a wrong answer with a 200 OK. What went wrong, and what are the two levers you'd adjust?

Show answer

The similarity threshold was too loose. So a semantically different request (for example, "how do I cancel my subscription" vs. "how do I keep my subscription") matched a cached answer for the wrong question. Two levers fix this:

  • Raise the similarity threshold. Fewer hits get cached, but they're safer — tune it to how costly a wrong answer is for that use case.
  • Add a TTL or explicit invalidation, so a correct-at-the-time cached answer doesn't keep being served after the underlying facts changed.

Question 4

Why did the October 2025 adaptive-attack study change how the industry talks about prompt-injection defense?

Show answer

It showed that twelve published input-layer defenses all failed under adaptive attacks (attack success rates above 90%, some past 98%). That undermined the idea that prompt injection can be reliably detected. The industry's response was to shift the security boundary from detection at the input layer to limiting blast radius after the fact: least-privilege tool permissions, sandboxing, and behavior monitoring. Assume injection will sometimes succeed, and limit what it can do when it does.

Question 5

What's the difference between shadow mode and a canary rollout, and why do them in that order?

Show answer

Shadow mode runs the new prompt/model on real traffic alongside the current one, but only logs and scores its output. No real user ever sees it. A canary then shows the new version to a small slice of real users, with the majority still protected by the old version. Shadow mode catches quality/cost problems with zero user-facing risk. Only after it looks good do you accept the small real risk a canary carries, rather than exposing any real user to an untested version first.

Question 6

Your company's per-tenant budget is enforced at the gateway. A tenant reports the AI feature "just stopped working" mid-day. What's the first thing you'd check, and why is that check possible at all?

Show answer

Check whether that tenant's spend crossed its budget cap. Budgets and kill switches's kill-switch/budget pattern is designed to reject further calls (or downgrade the model) automatically once a cap is hit. This happens silently, from the tenant's point of view, unless the product surfaces the reason. This check is only possible because cost is logged and attributed per tenant (Quotas and cost attribution and 11's trace log) in the first place. Without that, you'd be debugging blind.

Sources

Next

You've now built the platform layer a real SaaS company puts under its AI features. Next up: the patterns catalog. There, these same pieces (gateways, permission-aware retrieval, evals, guardrails) get named and reused across every specific domain covered from here on: observability, security, support, dev tools, fraud.