The Agentic Developer’s Guide to Secure LLM Gateway Routing: Cost, Capability, and Jailbreak Resilience A developer published a guide on tamiz.pro describing a secure LLM gateway architecture for agentic systems that treats model routing as a constrained optimization rather than a simple cost-based selection. The design splits the gateway into a fast data plane and a policy-managed control plane, and ranks eligible models by cost, quality, latency, and risk after enforcing provider, region, and tool policies. The guide includes TypeScript/Fastify implementation patterns and a machine-readable model capability registry covering tools, JSON schema, vision, context windows, and data-handling terms. Originally published on tamiz.pro https://tamiz.pro/insights/secure-llm-gateway-routing-cost-capability-jailbreak-resilience . 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. 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: php Request - classify - select cheapest model - send - retry on error A better pipeline treats routing as a constrained optimization: php 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: 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 https://tamiz.pro/insights . 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 | 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. 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. A resilient gateway usually contains the following components: php +--------------------------+ 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 | +-------------------------+ 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. 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. The following example implements a minimal gateway with: 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" } Use a strict schema so callers cannot omit security-relevant fields or inject arbitrary provider names. js // 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