Originally published on tamiz.pro.
An LLM gateway becomes a security boundary the moment an agent can choose which model to call. Routing that optimizes only for price or latency can silently send sensitive prompts to an unsuitable provider, expose tool instructions to a weaker model, or repeat a jailbreak that an earlier filter rejected. A production-grade gateway must evaluate cost, capability, and resilience together, then enforce the decision as policy rather than suggestion.
This guide explains the architecture, control flow, and implementation patterns behind secure model routing for agentic systems. The examples use TypeScript with Fastify and a policy engine expressed as plain, testable code.
Table of Contents
- 1. The Gateway as a Security Enforcement Point
- 2. Core Routing Signals
- 3. Reference Architecture
- 4. Building the Routing Pipeline
- 5. Capability-Aware Model Selection
- 6. Cost-Aware Routing Without Surprising Bills
- 7. Jailbreak Resilience and Prompt Injection Defense
- 8. Provider Isolation and Data Governance
- 9. Fallbacks, Circuits, and Semantic Consistency
- 10. Observability, Evaluation, and Auditability
- 11. Production Hardening Checklist
- 12. Frequently Asked Questions
1. The Gateway as a Security Enforcement Point
In a traditional application, an application server selects a downstream API. In an agentic system, the same server may also decide which model receives a prompt, which tools are exposed, and how a provider failure is handled. That makes the gateway part router, policy enforcement point, and security control plane.
The central mistake is treating these as independent decisions:
Request -> classify -> select cheapest model -> send -> retry on error A better pipeline treats routing as a constrained optimization:
Request -> authenticate and authorize -> normalize and inspect content -> classify intent, data sensitivity, and required capabilities -> enforce provider, region, and tool policies -> rank eligible models by cost, quality, latency, and risk -> execute with bounded retries and circuit breaking -> validate output and tool calls -> record decision evidence and telemetry Three properties matter:
- Determinism: The same request and policy version should produce the same routing decision, given the same model registry and health state.
- Explainability: Every decision should be reconstructable from recorded features, candidate scores, and policy rules.
- Fail closed: If a required check cannot run, the gateway rejects or routes to a known-safe fallback. It does not skip the check.
A useful design principle is to separate the gateway into a data plane that handles live requests and a control plane that manages model metadata, policies, budgets, and health state. The data plane should remain fast and horizontally scalable. The control plane can use stronger consistency and human approval workflows.
For broader gateway patterns and infrastructure trade-offs, see Tamiz’s Insights.
2. Core Routing Signals
A router should consume structured signals rather than infer everything from the prompt. Some signals are explicit, some are computed, and some are ambient.
| Signal | Source | Example | Routing effect |
|---|---|---|---|
| Tenant and principal | Authentication token | tenant_acme | Select allowed providers and budgets |
| Data classification | DLP scanner or classifier | pii, source_code | Restrict provider and retention policy |
| Task intent | Classifier or agent metadata | code_generation | Require coding and tool-use support |
| Required capabilities | Application contract | tools, json_schema, vision | Eliminate unsupported candidates |
| Risk score | Prompt and tool policy | 0.87 | Apply stricter validation or a stronger model |
| Budget | Quota service | $0.40 remaining | Prevent expensive candidate selection |
| Latency target | Request context | p95 < 2s | Prefer eligible low-latency models |
| Provider health | Circuit breaker and telemetry | degraded | Remove or deprioritize provider |
| Model version | Policy registry | provider/model@2025-04 | Pin behavior for reproducibility |
Explicit capabilities beat inferred capabilities
Do not infer whether a model supports structured output, tool calling, or a context window from its display name. Maintain a registry with machine-readable capabilities:
export interface ModelCapabilities { tools: boolean; parallelToolCalls: boolean; jsonSchema: boolean; vision: boolean; contextWindow: number; maxOutputTokens: number; regions: string[]; } export interface ModelDefinition { id: string; provider: string; version: string; capabilities: ModelCapabilities; pricing: { inputPerMillion: number; outputPerMillion: number; }; dataHandling: { trainingOptOut: boolean; zeroRetention: boolean; allowedRegions: string[]; }; } This registry should be versioned. Provider aliases change behavior over time, so a route based on fast-model is not reproducible. Route on an immutable identifier such as provider/model/version and resolve aliases only at the edge of the registry.
Classify once, but preserve the original request
Classification adds latency and can be wrong. Preserve the original request, attach the classification result and its confidence, and allow hard constraints to override soft preferences.
A practical classification result looks like this:
export interface RequestProfile { intent: | "code_generation" | "tool_orchestration" | "summarization" | "general"; dataClasses: Array<"public" | "pii" | "secrets" | "source_code">; requiresTools: boolean; requiresStructuredOutput: boolean; jailbreakRisk: number; confidence: number; } Confidence matters. If classification confidence is low, the gateway can use a conservative default policy rather than pretending it knows the task type.
3. Reference Architecture
A resilient gateway usually contains the following components:
+--------------------------+ Clients -----> | API Gateway / Gateway | | Authentication + Quota | +------------+-------------+ | +------------v-------------+ | Request Normalizer | | DLP + Injection Scanner | +------------+-------------+ | +------------v-------------+ | Policy Decision Point | | - capability filters | | - data residency | | - risk thresholds | | - budget constraints | +------------+-------------+ | +------------v-------------+ | Model Registry + Router | | - weighted scoring | | - fallback graph | +------------+-------------+ | +------------------+------------------+ | | | +------v------+ +-------v-------+ +------v------+ | Provider A | | Provider B | | Provider C | +------+------+ +-------+-------+ +------+------+ | | | +------------------+------------------+ | +------------v-------------+ | Output Validator | | Tool Call Guard | | Response Accounting | +-------------------------+ Keep provider adapters thin
Provider adapters should translate the gateway’s internal request format into provider-specific formats. They should not contain policy decisions. A provider adapter that silently downgrades tool calls or ignores a strict JSON requirement defeats the routing layer.
Keep policy decisions separate from execution
The policy layer should return a decision object:
export interface RoutingDecision { selectedModelId: string; rejectedModelIds: Array<{ id: string; reasons: string[]; }>; policyVersion: string; requestProfile: RequestProfile; estimatedCostUsd: number; fallbackModelIds: string[]; } This makes the decision auditable and testable. It also lets the execution layer enforce the selected model instead of reimplementing routing logic.
4. Building the Routing Pipeline
The following example implements a minimal gateway with:
- API-key authentication through a trusted upstream service
- Hard capability and data-policy filters
- Jailbreak risk thresholds
- Cost-aware scoring
- A provider allowlist
- Bounded fallbacks
- Decision logging
Install dependencies
npm init -y npm install fastify @fastify/helmet zod pino npm install -D typescript tsx vitest @types/node Configure TypeScript:
{ "compilerOptions": { "target": "ES2022", "module": "NodeNext", "moduleResolution": "NodeNext", "strict": true, "outDir": "dist", "rootDir": "src", "esModuleInterop": true, "skipLibCheck": true }, "include": ["src/**/*.ts", "test/**/*.ts"] } Define the request contract
Use a strict schema so callers cannot omit security-relevant fields or inject arbitrary provider names.
// src/contracts.ts import { z } from "zod"; export const ToolDefinition = z.object({ name: z.string().min(1).max(128), description: z.string().max(4_000), parameters: z.record(z.unknown()) }); export const ChatRequest = z.object({ messages: z .array( z.object({ role: z.enum(["system", "user", "assistant", "tool"]), content: z.string().max(200_000) }) ) .min(1), tools: z.array(ToolDefinition).max(64).default([]), responseFormat: z .object({ type: z.literal("json_schema"), schema: z.record(z.unknown()) }) .optional(), maxOutputTokens: z.number().int().min(1).max(32_000).default(2_000), metadata: z .object({ tenantId: z.string().min(1), dataClasses: z .array(z.enum(["public", "pii", "secrets", "source_code"])) .default([]), requiredCapabilities: z .array(z.enum(["tools", "json_schema", "vision"])) .default([]), budgetUsd: z.number().positive().optional() }) .default({ tenantId: "unknown", dataClasses: [], requiredCapabilities: [] }) }); export type ChatRequest = z.infer<typeof ChatRequest>; Do not trust dataClasses from an untrusted caller. In production, derive it from trusted context and validate it against DLP results. The schema above demonstrates the contract; it is not a substitute for server-side classification.
Implement hard filters
Hard filters express constraints. A candidate that fails one is ineligible, regardless of its score.
// src/router.ts import type { ChatRequest } from "./contracts.js"; import type { ModelDefinition, RequestProfile } from "./model-registry.js"; export interface CandidateResult { model: ModelDefinition; score: number; reasons: string[]; } export interface FilterResult { eligible: ModelDefinition[]; rejected: CandidateResult[]; } export function hardFilter( models: ModelDefinition[], request: ChatRequest, profile: RequestProfile, allowedProviders: string[] ): FilterResult { const eligible: ModelDefinition[] = []; const rejected: CandidateResult[] = []; for (const model of models) { const reasons: string[] = []; if (!allowedProviders.includes(model.provider)) { reasons.push("provider_not_allowed"); } if (request.tools.length > 0 && !model.capabilities.tools) { reasons.push("tools_unsupported"); } if ( request.responseFormat && !model.capabilities.jsonSchema ) { reasons.push("json_schema_unsupported"); } if ( profile.dataClasses.includes("secrets") && !model.dataHandling.zeroRetention ) { reasons.push("zero_retention_required"); } if ( profile.dataClasses.includes("pii") && !model.dataHandling.trainingOptOut ) { reasons.push("training_opt_out_required"); } const estimatedTokens = estimateInputTokens(request); if (estimatedTokens > model.capabilities.contextWindow) { reasons.push("context_window_exceeded"); } if ( request.maxOutputTokens > model.capabilities.maxOutputTokens ) { reasons.push("output_limit_exceeded"); } const estimatedCost = estimateCost(model, estimatedTokens, request.maxOutputTokens); if ( request.metadata.budgetUsd !== undefined && estimatedCost > request.metadata.budgetUsd ) { reasons.push("budget_exceeded"); } if (reasons.length > 0) { rejected.push({ model, score: 0, reasons }); } else { eligible.push(model); } } return { eligible, rejected }; } export function estimateInputTokens(request: ChatRequest): number { // Replace with a tokenizer appropriate to the selected model family. // This conservative estimate is sufficient for the example. const characters = request.messages.reduce( (sum, message) => sum + message.content.length, 0 ); const toolCharacters = JSON.stringify(request.tools).length; return Math.ceil((characters + toolCharacters) / 4); } export function estimateCost( model: ModelDefinition, inputTokens: number, outputTokens: number ): number { return ( (inputTokens / 1_000_000) * model.pricing.inputPerMillion + (outputTokens / 1_000_000) * model.pricing.outputPerMillion ); } The budget check is intentionally conservative: it uses the maximum requested output. A more advanced implementation can use a probabilistic estimate and reserve the remaining budget before sending the request.
Score eligible candidates
Scoring should be explainable. A weighted score is easier to reason about than an opaque ranking model, and it can be tuned with evaluation data.
export interface RoutingWeights { cost: number; quality: number; latency: number; risk: number; } export interface ModelRuntimeStats { p95LatencyMs: number; successRate: number; qualityScore: number; riskScore: number; } export function scoreCandidates( models: ModelDefinition[], request: ChatRequest, profile: RequestProfile, stats: Map<string, ModelRuntimeStats>, weights: RoutingWeights ): CandidateResult[] { const inputTokens = estimateInputTokens(request); const candidates = models.map((model) => { const runtime = stats.get(model.id) ?? { p95LatencyMs: 5_000, successRate: 0.95, qualityScore: 0.5, riskScore: 0.5 }; const cost = estimateCost( model, inputTokens, request.maxOutputTokens ); const reasons: string[] = []; let score = 0; score += (1 - Math.min(cost / 0.10, 1)) * weights.cost; score += runtime.qualityScore * weights.quality; score += (1 - Math.min(runtime.p95LatencyMs / 10_000, 1)) * weights.latency; score += (1 - runtime.riskScore) * weights.risk; score += runtime.successRate * 0.25; if (profile.jailbreakRisk >= 0.7) { score += runtime.riskScore * 0.5; reasons.push("risk_weight_increased"); } return { model, score, reasons }; }); return candidates.sort((a, b) => b.score - a.score); } Weights are policy, not application configuration. Store them per tenant or workload, require review for production changes, and version them with the decision record.
Assemble the decision
export function chooseRoute( models: ModelDefinition[], request: ChatRequest, profile: RequestProfile, allowedProviders: string[], stats: Map<string, ModelRuntimeStats>, weights: RoutingWeights, policyVersion: string ) { const filtered = hardFilter(models, request, profile, allowedProviders); if (filtered.eligible.length === 0) { throw new Error("No model satisfies the request policy"); } const ranked = scoreC...