SXF FIELD GUIDE · LLM INFRASTRUCTURE · ENTERPRISE API OPERATIONS
LLM Gateways Explained:
Model Routing, Failover, Caching, Security & Costs
A production-first AI gateway guide: when to add a multi-provider proxy, how routing and retry policies work, what caching means for privacy, and what a real local HTTP fault-injection experiment demonstrates. Includes a vendor-neutral decision tool and reproducible files.
What is an LLM gateway and when should you use one?
An LLM gateway is a policy-controlled intermediary between an application and one or more model APIs. It can enforce tenant quotas and budgets, keep provider keys server-side, route requests, apply controlled fallback, observe token costs and optionally cache eligible content. Use one when centralized policy and multiple providers justify the complexity—not because a proxy alone can guarantee better answers or zero downtime.
Start with the workload's quality contract, model capabilities and regional privacy rules. Then define retry/failover bounds, validate outputs and count accepted tasks rather than raw HTTP 200 responses.
ENGINEERING GUIDE
What is an LLM gateway?
An LLM gateway is a central policy and routing boundary between an application and one or more large-language-model APIs. It can authenticate application callers, isolate provider credentials, enforce budgets and rate limits, choose a model route, apply controlled retries and record redacted request telemetry. A gateway does not automatically improve model quality, prevent prompt injection or guarantee uninterrupted streaming.
If you run an AI agent that uses Claude for complex reasoning, a smaller model for document classification and another model in a restricted region, the gateway can make the decision policy visible and auditable. The application still owns task-specific acceptance tests and downstream action safety. Read the AI model selection guide for quality evaluation and production deployment for durable work and rollback.
| Term | Primary responsibility | What it does not guarantee |
|---|---|---|
| LLM proxy | Relay or normalize provider API calls | Model equivalence, tenant authorization or cost control |
| LLM gateway | Proxy plus policy, audit, routing and quota controls | Guaranteed accepted answers or security by default |
| Model router | Select a model/provider for each task | Credentials, redaction or output validation by itself |
| Orchestrator / agent runtime | Coordinate multiple steps, tools and workflow state | Network-level central quotas without additional controls |
| Provider SDK | Use a particular API correctly | Cross-provider contract portability |
ENGINEERING GUIDE
Production LLM gateway architecture: app, policy, router and providers
- Authenticate: establish trusted tenant/application identity and map it to approved models and budget.
- Validate input: bound schema, payload size, sensitive-data class and tool/JSON-mode requirements.
- Apply admission policy: check RPM, TPM, in-flight request concurrency, cost cap and region requirements.
- Route: choose a pinned provider/model based on measurable capability, task policy and current health.
- Execute: send provider-compatible requests, interpret errors and account for actual attempts; nested retries must be coordinated.
- Validate output: verify expected schema, model-specific refusal semantics, tool calls and end-user acceptance.
- Observe: emit correlation IDs, usage, provider error classes, tail latency and redacted logs under explicit retention policy.
The model is not the policy authority. Tenant permissions, provider allowlists, cost ceilings, tool execution approvals and log retention belong outside the prompt.
ENGINEERING GUIDE
Do you need an LLM gateway or a thin SDK wrapper?
| Workload | Useful starting architecture | Decision trigger |
|---|---|---|
| One app, one model provider | Direct official SDK with server-side secrets and monitoring | Add a proxy if multiple teams or centrally managed quotas appear |
| Two or more providers | Gateway or common abstraction with pinned model capabilities | Failover, credential segregation, centralized usage policy |
| Enterprise multi-tenant SaaS | Identity-aware gateway plus authoritative application policy | Per-tenant budgets, rate limits, approved regions, audit trail |
| Agent tools or financial side effects | Gateway + durable workflow engine + tool authorization | Network retries cannot establish side-effect idempotency |
| High-volume batch classification | Task router with queues, cheap model path and fallback | Accepted-result unit economics and rate-limit caps |
An AI gateway introduces an extra hop and control plane. It is justified when it reduces duplicated policy code or operational risk, not merely because a demo makes it easy to list five providers. Model selection can remain in the application for small deployments.
ENGINEERING GUIDE
LLM routing strategies: reliability, quality, latency and cost
Routing can be static (task-to-model mapping), weighted (split traffic across similar deployments), capability-aware (JSON schema, context size, tools, vision, approved region) or adaptive (route health, quotas, cost and verified task outcomes). Failover is a separate choice from initial routing.
| Strategy | Useful when | What to verify |
|---|---|---|
| Static / capability-aware | Strict quality or legal requirements and reproducibility | Model ID, region and tool/JSON support are pinned |
| Weighted load distribution | Equivalent deployments exist | Independent output acceptance under both destinations |
| Latency aware | Interactive workload is latency sensitive | p95 completion, time to first token and output quality |
| Cost aware | Large numbers of low-risk classification requests | Independent acceptance and cost per accepted result |
| Health-aware failover | Transient 429/5xx disruptions | Recoverability without schema drift or unsafe double tool actions |
| Canary route | Releasing provider/model changes | Per-model regression fixtures, rollback and visibility |
A common trap is treating the phrase “OpenAI-compatible API” as proof that any two models are interchangeable. Tool-call object shapes, content types, error semantics, function calling, structured outputs, reasoning fields, streaming and safety behavior can differ. Build a model capability registry instead of blindly forwarding every flag.
{"route_policy":"support-answering-v3","allowed_regions":["eu"],"required_capabilities":["json_schema"],"max_attempts_total":2,"model_primary":"providerA:pinned-model-version","fallback":["providerB:evaluated-model-version"],"tenant_budget_usd":100,"log_prompt_content":false}ENGINEERING GUIDE
Retries, provider failover, circuit breakers and streaming boundaries
Rate limits are often measured in requests per minute and tokens per minute, and providers can enforce multiple or smaller-window constraints. A gateway should not compensate for a real 429 by blasting the same provider with immediate parallel retries. Respect provider-specific Retry-After behavior, use bounded backoff with jitter, and enforce a total request attempt/time/cost budget. OpenAI documents rate limits and backoff patterns in official guidance.
| Condition | Recommended policy concept | Failure to avoid |
|---|---|---|
| 429 rate limit | Retry-After if provided; bounded backoff; avoid hot-looping | Wasted quota, amplified failure and cost |
| 5xx transient | Limited retries or a healthy fallback if compatible | Retry storms and hidden failures |
| 4xx validation / authorization | Fail closed and surface corrective action | Sending invalid or forbidden requests to another provider |
| Deadline exceeded | Check whether the upstream request may still be running or billable | Multiple costly attempts for the same user operation |
| Malformed HTTP 200 | Reject schema/contract failure and record incident | Treating transport success as accepted task |
| Partially streamed answer | Surface interrupted stream or explicit restart; do not silently splice | Mixed-model answer presented as one continuous response |
| Downstream tool side effect | Coordinate with application-owned idempotency and confirmation | Repeated email/payment/action from a gateway retry |
A circuit breaker temporarily stops sending traffic to a failing destination and probes recovery under a defined policy. It reduces cascading failure but can also concentrate traffic on a backup that lacks quota. Consider budget caps, health checks, regional restrictions and manual fallback override. And critically: fallback can increase HTTP availability while decreasing accepted-task quality.
SXF ORIGINAL ENGINEERING LAB
Original SXF evidence: deterministic HTTP gateway fault-injection study
We created and ran a real local HTTP server with two mock upstream destinations. A Python client sent actual HTTP POST requests over the loopback interface and validated returned JSON. For each of three independent policies, we evaluated the same 80 logical tasks. The primary mock returned 50 immediately valid responses, ten rate limits that recover on the second attempt, ten persistent server errors and ten persistent rate limits. The backup returned valid responses for 15 of 20 fallback calls, and five HTTP 200 responses with an invalid schema.
| Policy | Validated completions | Success rate | Primary / backup HTTP calls | Illustrative attempted-call cost |
|---|---|---|---|---|
| No retry | 50 of 80 | 62.5% | 80 / 0 | $0.160 |
| Retry once | 60 of 80 | 75.0% | 110 / 0 | $0.220 |
| Retry then fallback | 75 of 80 | 93.75% | 110 / 20 | $0.280 |
The fallback policy rejected five malformed HTTP 200 responses instead of reporting them as successful completions. The modelled cost used $0.002 per attempted primary HTTP request and $0.003 per attempted backup request, including errors. These are invented lab coefficients transparently disclosed as assumptions—not vendor prices.
It demonstrates that explicit retry and fallback policies can recover expected-shape responses under these deterministic faults, while schema validation catches bad HTTP 200 replies. It does not measure model quality, real provider availability, TLS, tokens, real rate limits, p95 latency, paid requests, concurrency or streaming. Because the test is deterministic, no statistical or universal improvement claim follows.
Reproduce: run python sxf_gateway_http_lab.py from your terminal. No API keys, internet connection, paid model calls or third-party dependencies are required. The source checks expected results with assertions; editing the fault schedule changes the scenario and requires new conclusions.
ENGINEERING GUIDE
LLM caching: prompt-prefix reuse vs storing an answer
| Caching layer | Mechanism | Privacy and freshness impact |
|---|---|---|
| Provider prompt caching | Provider reuses eligible input prefix processing; still produces a model response | Provider-specific token accounting, content policy and cache duration |
| Gateway response caching | Replays a previously stored completion for a suitable cache key | Can leak tenant-specific content or outdated/unauthorized information |
| Semantic answer caching | Returns an earlier answer for a similar query | Semantic similarity is not authorization or factual equivalence |
| Application RAG caching | Caches permitted document IDs, retrieval or generation fragments | Source revision, ACL, embedding version and user context must be in key/validation |
OpenAI and Anthropic each document provider-side prompt caching; it is not equivalent to persisting and replaying a finished response. Cloudflare documents AI Gateway caching as a different gateway feature. Do not claim that the gateway's cache is automatically compatible with every provider's prompt-caching semantics.
Safe response cache key components include tenant/policy identity, model and version, instruction version, tool schema version, relevant retrieval corpus version and request-normalization rules. Cache bypass or tight expiration is often the right default for personal data, regulated records, live facts, tool calls and high-consequence decisions. Never turn on cross-tenant answer reuse just to improve a hit-rate dashboard.
ENGINEERING GUIDE
API key security, data privacy and zero-trust boundaries
A well-designed gateway can avoid distributing raw vendor API credentials across client apps. Its own admin API and virtual keys become sensitive control points. Apply short-lived or rotated credentials, allowlists for provider egress, tenant-scoped policies and explicit secret ownership. Never accept a tenant label or spending policy solely from an LLM prompt.
| Boundary | Control | How to verify |
|---|---|---|
| Client → gateway | Authentication, authorization, schema and payload caps | Cross-tenant negative tests |
| Gateway → provider | Managed secrets, restricted egress, approved regions | No secret logging, no unauthorized provider route |
| Prompt/content logging | Redaction, opt-in detail, retention/deletion | Sensitive prompt not present in unapproved logs |
| Per-tenant virtual keys | Separate budgets, usage accounting and revocation | Revoked key cannot access any model |
| Provider fallback | Approved residency, data use and contract | No silent cross-region transfer |
| Cache and trace store | Tenant scope, encryption, access and expiry | Other tenant cannot read cached output |
A unified gateway is also a concentrated failure and trust boundary. Deploy it with service authentication, documented restore procedures and operational visibility. Detailed agent permission and prompt injection issues belong in the AI Agent Security Guide.
ENGINEERING GUIDE
RPM, TPM, concurrency, rate-limit recovery and budget enforcement
Request rate (RPM), token throughput (TPM), concurrent in-flight calls and per-tenant spend are related but not interchangeable. A request might be cheap but produce many output tokens. Concurrency limits manage saturation while token budgets depend on provider accounting of input/output and, where available, cached tokens.
| Control | Enforce on | Measure |
|---|---|---|
| RPM | Gateway admissions over configured window | 429 decisions, allowed vs denied by tenant |
| TPM | Token reservations plus reconciled actual usage | Reserved vs actual input/output and cache units |
| Concurrent in-flight | Active requests to each destination | p95 latency, pool saturation and queuing |
| Spend budget | Total attempts, provider costs, fixed overhead | Cost per independently accepted task |
| Circuit breaker | Provider/region/model health | Time open, recovery, fallback saturation |
| Timeout budget | End-to-end request and retry chain | Missed deadlines and unknown upstream outcome |
Distributed gateways need coordinated counters and time windows or providers will see aggregate load that exceeds supposedly enforced limits. On a rate-limit event, avoid multiple retry layers stacking: SDK, gateway and application retries can multiply attempts.
DOCUMENTATION-BASED COMPARISON
LiteLLM vs Portkey vs Cloudflare AI Gateway vs Kong: what to evaluate
The following comparison summarizes publicly documented product approaches, not a vendor ranking or a claim that every feature is available on every plan. Vendor documentation and product details are live systems and should be checked before procurement. We did not benchmark these products.
| Platform | Architecture / documented position | Candidate strengths to verify | Specific buying questions |
|---|---|---|---|
| LiteLLM Proxy | Open-source proxy and router with common API patterns | Fallbacks, retries, routing, virtual keys and budgets | Deployment ownership, model parity, auth and memory/DB needs |
| Portkey AI Gateway | Gateway platform emphasizing production LLM observability and governance | Routing, provider integration, reliability policy and tracing | Hosted vs self-managed controls, quotas, data retention and terms |
| Cloudflare AI Gateway | Gateway service integrated with the Cloudflare ecosystem | Analytics/logging, caching and rate-limiting patterns | Model support, feature availability, data routing and cache semantics |
| Kong AI Gateway | API management and AI proxy policy ecosystem | AI proxy integrations, gateway plugins and traffic governance | Edition/plugins, token accounting, security and operational cost |
Do not declare a speed, price or reliability winner from these feature lists. Different service tiers, regions, connection reuse, model versions and token budgets make generic rankings invalid. Evaluate each candidate's official deployment documentation for the exact plan you intend to run.
INTERACTIVE ENTERPRISE TOOL
Interactive SXF AI Gateway Decision Matrix
Choose your application's constraints to generate an evaluation plan. No vendor is automatically recommended or scored. All computation happens in your browser; no credentials or personal prompts are requested.
Select values above to begin.
The decision matrix is an editorial checklist generator, not a hidden vendor ranking. Contract-specific feature limits and actual workload benchmarks must be confirmed independently.
ENGINEERING GUIDE
LLM gateway cost: model attempts, caching, gateway overhead and accepted outcomes
For procurement, separate provider inference spend, gateway service fees/runtime, telemetry and storage, cache infrastructure, and human/incident costs. Retrying a failed call may be billable depending on when it failed and provider terms. A cached response may skip generation but create privacy and freshness obligations. Count every attempt, not only the visible answer.
This worksheet assumes the specified fraction needs both the extra retries and one backup attempt. It excludes gateway subscription/compute, observability, token discounts and actual accepted-outcome rate. All editable prices are hypothetical, not live provider quotes.
| Cost source | Risk to model |
|---|---|
| Token/API attempts | Retries, different input/output token lengths and context migration |
| Caching | Input-prefix provider discounts vs answer reuse and invalidation |
| Gateway infrastructure | Monthly provider platform fees, runtime, logging and egress |
| Operations | Secrets, monitoring, SRE, incidents and upgrades |
| Quality | Model-substitution regressions, rejected JSON and human review |
See SXF Model Pricing, AI Agent Cost and ROI, and AI Model Cost Calculator for the adjacent inference and business cost layers.
ENGINEERING GUIDE
Observability and SLOs: measure the accepted task, not the HTTP status
| Metric | Reason | Example alert trigger |
|---|---|---|
| Accepted-outcome rate | A valid HTTP response can be wrong or violate output contract | Sustained failure against defined business SLO |
| p95/p99 end-to-end completion | Retry and fallback can hide long tails | Deadline breach or sharp anomaly |
| Provider attempts per accepted task | Shows cost and retry amplification | Growing retry ratio or exhausting budget |
| Fallback rate and contract rejection | Exposes provider health and schema parity | Mismatch growth even when 200s remain high |
| Cache hit/miss by tenant and version | Measures true reuse with privacy constraints | Unexpected cross-tenant access or stale content |
| Token usage and billable provider calls | Avoids incomplete attribution of spend | Unbudgeted cost spike or quota exhaustion |
| Regional routing decisions | Compliance and residency evidence | Disallowed provider or region attempted |
Link end-user task IDs to provider request attempts and redact sensitive prompt bodies unless approved. OpenTelemetry GenAI conventions can support trace attributes, but keep instrumentation version-aware and do not blindly collect private prompt or completion text. For full span and incident analysis read AI Agent Observability.
ENGINEERING GUIDE
A ten-step production rollout checklist
- Define a narrow business workflow and independently verified output contract.
- Inventory provider models and pin versions, tool, streaming, context and structured-output capabilities.
- Choose an owner for gateway secrets and tenant authorization.
- Set RPM/TPM/concurrency/spend and denial behavior per tenant and provider.
- Implement total retry budgets, jitter, circuit breaker, fallback compatibility tests and recovery drills.
- Decide caching per information class, with private data defaulting to no response-cache reuse.
- Publish redacted logs, attempt-level traces and cost-per-accepted-outcome dashboards.
- Replay fault cases 429/5xx/timeouts, invalid 200, partial stream and unsupported tools.
- Canary a pinned version with abort rules, rollback and a defined treatment of in-flight calls.
- Record outcomes, source documentation, owner approvals and review the configuration after provider changes.
ENGINEERING GUIDE
Ten LLM gateway mistakes that hurt reliability and cost
- Calling HTTP 200 a successful business outcome.
- Assuming OpenAI-compatible interfaces imply interchangeable model behavior.
- Stacking client, gateway and provider retries without a global attempt budget.
- Retrying a potentially irreversible tool action without idempotency and verification.
- Switching models after part of a streamed answer has already reached the user.
- Routing a sensitive tenant's traffic into a nonapproved region during fallback.
- Reusing cached answers across tenants, users or permission versions.
- Counting token price but ignoring extra attempts, reviews, observability and operations.
- Letting the model grant its own provider credentials, permissions or budgets.
- Publishing a vendor ranking based on incompatible tiers, models or unexplained test fixtures.
ENGINEERING GUIDE
Frequently asked questions about LLM and AI gateways
What is an LLM gateway?
An LLM gateway is an application-controlled intermediary for model API calls that can enforce authentication, usage policy, request routing, observability, caching and failure handling across one or more providers.
What is the difference between an AI gateway and an LLM proxy?
An LLM proxy mainly intermediates or normalizes API traffic. An AI or LLM gateway usually adds organization policy such as key isolation, budgets, rate limits, model routing, logging controls and fallback. These are industry terms, not strict product standards.
When do I need a multi-provider LLM gateway?
It becomes useful when workloads use multiple models or providers, require centrally managed credentials, per-tenant budgets, audited routing decisions or explicit resilience policies. A single-provider application may be better served by an SDK and thin policy layer.
Does LLM failover guarantee reliability?
No. Failover may restore HTTP availability while changing output schemas, model behavior, tool contracts, refusals, costs or data residency. Verify accepted user outcomes rather than counting only HTTP 200 responses.
How should an LLM gateway handle 429 errors?
Use provider-specific retry guidance and Retry-After where applicable, bounded exponential backoff with jitter, concurrency and budget limits, and safe fallbacks. Do not create retry storms or override non-idempotent tool safety.
Can you switch LLM providers during streaming?
Not transparently after content has reached the user. A partial streamed response cannot safely be continued by another model as though it were the same output. Provide a clear restart or error contract.
What is the difference between prompt caching and response caching?
Provider prompt caching reuses processing of eligible input prefixes while still producing a model response. Response caching replays a stored answer and introduces freshness, authorization and sensitive-data risks.
What is the best LLM gateway?
No product is universally best. Compare LiteLLM, Portkey, Cloudflare AI Gateway, Kong and other eligible options with the same model workload, tenant policy, capability requirements, cost and failure tests.
What does an LLM gateway cost?
Total costs combine provider inference attempts, gateway compute or fees, stored telemetry, cache operations, egress, support, incident response and human review. Calculate cost per independently accepted task.
Can an LLM gateway keep API keys secure?
It can centralize secret handling when properly deployed, but security also requires scoped identities, rotated credentials, restricted admin access, network policies and redacted logs.
EVIDENCE AND REFERENCES
Primary sources, SXF experimental method and editorial independence
Evidence rule: the comparison table reflects official documented features, not independently benchmarked vendor performance. Our original local HTTP experiment is reproducible and explicitly separates actual loopback requests from mock upstream behavior and synthetic cost coefficients. Provider limits, plans and compatibility need verification for your exact production versions.
No commercial gateway or live LLM API was tested for the original SXF lab. No speed/price/reliability winner is asserted. Product descriptions are editorial, without paid vendor placements. The published Python experiment and research protocol allow independent inspection.