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.

Evergreen technical guideFour gateway approaches80-task experimentFree source + checklist
DIRECT ANSWER

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.

AI gateway vs LLM proxy vs router vs agent orchestration
TermPrimary responsibilityWhat it does not guarantee
LLM proxyRelay or normalize provider API callsModel equivalence, tenant authorization or cost control
LLM gatewayProxy plus policy, audit, routing and quota controlsGuaranteed accepted answers or security by default
Model routerSelect a model/provider for each taskCredentials, redaction or output validation by itself
Orchestrator / agent runtimeCoordinate multiple steps, tools and workflow stateNetwork-level central quotas without additional controls
Provider SDKUse a particular API correctlyCross-provider contract portability

ENGINEERING GUIDE

Production LLM gateway architecture: app, policy, router and providers

Original SXF application policy model router primary fallback and redacted telemetry components
Original SXF reference architecture illustrating the separation of identities, routing and provider credentials.
  1. Authenticate: establish trusted tenant/application identity and map it to approved models and budget.
  2. Validate input: bound schema, payload size, sensitive-data class and tool/JSON-mode requirements.
  3. Apply admission policy: check RPM, TPM, in-flight request concurrency, cost cap and region requirements.
  4. Route: choose a pinned provider/model based on measurable capability, task policy and current health.
  5. Execute: send provider-compatible requests, interpret errors and account for actual attempts; nested retries must be coordinated.
  6. Validate output: verify expected schema, model-specific refusal semantics, tool calls and end-user acceptance.
  7. Observe: emit correlation IDs, usage, provider error classes, tail latency and redacted logs under explicit retention policy.
Key architecture principle

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?

When to use an LLM gateway: decision by workload
WorkloadUseful starting architectureDecision trigger
One app, one model providerDirect official SDK with server-side secrets and monitoringAdd a proxy if multiple teams or centrally managed quotas appear
Two or more providersGateway or common abstraction with pinned model capabilitiesFailover, credential segregation, centralized usage policy
Enterprise multi-tenant SaaSIdentity-aware gateway plus authoritative application policyPer-tenant budgets, rate limits, approved regions, audit trail
Agent tools or financial side effectsGateway + durable workflow engine + tool authorizationNetwork retries cannot establish side-effect idempotency
High-volume batch classificationTask router with queues, cheap model path and fallbackAccepted-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.

LLM routing policies and measurable safety checks
StrategyUseful whenWhat to verify
Static / capability-awareStrict quality or legal requirements and reproducibilityModel ID, region and tool/JSON support are pinned
Weighted load distributionEquivalent deployments existIndependent output acceptance under both destinations
Latency awareInteractive workload is latency sensitivep95 completion, time to first token and output quality
Cost awareLarge numbers of low-risk classification requestsIndependent acceptance and cost per accepted result
Health-aware failoverTransient 429/5xx disruptionsRecoverability without schema drift or unsafe double tool actions
Canary routeReleasing provider/model changesPer-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.

JSON · TECHNICAL EXAMPLE
{"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.

LLM failover policy by error and state
ConditionRecommended policy conceptFailure to avoid
429 rate limitRetry-After if provided; bounded backoff; avoid hot-loopingWasted quota, amplified failure and cost
5xx transientLimited retries or a healthy fallback if compatibleRetry storms and hidden failures
4xx validation / authorizationFail closed and surface corrective actionSending invalid or forbidden requests to another provider
Deadline exceededCheck whether the upstream request may still be running or billableMultiple costly attempts for the same user operation
Malformed HTTP 200Reject schema/contract failure and record incidentTreating transport success as accepted task
Partially streamed answerSurface interrupted stream or explicit restart; do not silently spliceMixed-model answer presented as one continuous response
Downstream tool side effectCoordinate with application-owned idempotency and confirmationRepeated 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

Original SXF Python localhost HTTP experiment with 80 tasks and retry and fallback results
An executed local HTTP test, not a benchmark of LiteLLM, Portkey, Cloudflare, Kong or any model provider.

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.

SXF executed 80-task local HTTP fault injection: three gateway policies
PolicyValidated completionsSuccess ratePrimary / backup HTTP callsIllustrative attempted-call cost
No retry50 of 8062.5%80 / 0$0.160
Retry once60 of 8075.0%110 / 0$0.220
Retry then fallback75 of 8093.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.

What this study does and does not show

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

Prompt caching vs response caching vs semantic caching
Caching layerMechanismPrivacy and freshness impact
Provider prompt cachingProvider reuses eligible input prefix processing; still produces a model responseProvider-specific token accounting, content policy and cache duration
Gateway response cachingReplays a previously stored completion for a suitable cache keyCan leak tenant-specific content or outdated/unauthorized information
Semantic answer cachingReturns an earlier answer for a similar querySemantic similarity is not authorization or factual equivalence
Application RAG cachingCaches permitted document IDs, retrieval or generation fragmentsSource 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.

Enterprise LLM gateway security controls
BoundaryControlHow to verify
Client → gatewayAuthentication, authorization, schema and payload capsCross-tenant negative tests
Gateway → providerManaged secrets, restricted egress, approved regionsNo secret logging, no unauthorized provider route
Prompt/content loggingRedaction, opt-in detail, retention/deletionSensitive prompt not present in unapproved logs
Per-tenant virtual keysSeparate budgets, usage accounting and revocationRevoked key cannot access any model
Provider fallbackApproved residency, data use and contractNo silent cross-region transfer
Cache and trace storeTenant scope, encryption, access and expiryOther 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.

Gateway rate limit and spending-control design
ControlEnforce onMeasure
RPMGateway admissions over configured window429 decisions, allowed vs denied by tenant
TPMToken reservations plus reconciled actual usageReserved vs actual input/output and cache units
Concurrent in-flightActive requests to each destinationp95 latency, pool saturation and queuing
Spend budgetTotal attempts, provider costs, fixed overheadCost per independently accepted task
Circuit breakerProvider/region/model healthTime open, recovery, fallback saturation
Timeout budgetEnd-to-end request and retry chainMissed 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.

LLM gateway comparison — evidence-led procurement criteria
PlatformArchitecture / documented positionCandidate strengths to verifySpecific buying questions
LiteLLM ProxyOpen-source proxy and router with common API patternsFallbacks, retries, routing, virtual keys and budgetsDeployment ownership, model parity, auth and memory/DB needs
Portkey AI GatewayGateway platform emphasizing production LLM observability and governanceRouting, provider integration, reliability policy and tracingHosted vs self-managed controls, quotas, data retention and terms
Cloudflare AI GatewayGateway service integrated with the Cloudflare ecosystemAnalytics/logging, caching and rate-limiting patternsModel support, feature availability, data routing and cache semantics
Kong AI GatewayAPI management and AI proxy policy ecosystemAI proxy integrations, gateway plugins and traffic governanceEdition/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.

Your evaluation plan

Select values above to begin.

Selection integrity

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.

Modeled provider attempt cost—
Modeled cost per input task—

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.

Enterprise LLM gateway total cost of ownership
Cost sourceRisk to model
Token/API attemptsRetries, different input/output token lengths and context migration
CachingInput-prefix provider discounts vs answer reuse and invalidation
Gateway infrastructureMonthly provider platform fees, runtime, logging and egress
OperationsSecrets, monitoring, SRE, incidents and upgrades
QualityModel-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

LLM gateway monitoring and reliability scorecard
MetricReasonExample alert trigger
Accepted-outcome rateA valid HTTP response can be wrong or violate output contractSustained failure against defined business SLO
p95/p99 end-to-end completionRetry and fallback can hide long tailsDeadline breach or sharp anomaly
Provider attempts per accepted taskShows cost and retry amplificationGrowing retry ratio or exhausting budget
Fallback rate and contract rejectionExposes provider health and schema parityMismatch growth even when 200s remain high
Cache hit/miss by tenant and versionMeasures true reuse with privacy constraintsUnexpected cross-tenant access or stale content
Token usage and billable provider callsAvoids incomplete attribution of spendUnbudgeted cost spike or quota exhaustion
Regional routing decisionsCompliance and residency evidenceDisallowed 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

  1. Define a narrow business workflow and independently verified output contract.
  2. Inventory provider models and pin versions, tool, streaming, context and structured-output capabilities.
  3. Choose an owner for gateway secrets and tenant authorization.
  4. Set RPM/TPM/concurrency/spend and denial behavior per tenant and provider.
  5. Implement total retry budgets, jitter, circuit breaker, fallback compatibility tests and recovery drills.
  6. Decide caching per information class, with private data defaulting to no response-cache reuse.
  7. Publish redacted logs, attempt-level traces and cost-per-accepted-outcome dashboards.
  8. Replay fault cases 429/5xx/timeouts, invalid 200, partial stream and unsupported tools.
  9. Canary a pinned version with abort rules, rollback and a defined treatment of in-flight calls.
  10. Record outcomes, source documentation, owner approvals and review the configuration after provider changes.

ENGINEERING GUIDE

Ten LLM gateway mistakes that hurt reliability and cost

  1. Calling HTTP 200 a successful business outcome.
  2. Assuming OpenAI-compatible interfaces imply interchangeable model behavior.
  3. Stacking client, gateway and provider retries without a global attempt budget.
  4. Retrying a potentially irreversible tool action without idempotency and verification.
  5. Switching models after part of a streamed answer has already reached the user.
  6. Routing a sensitive tenant's traffic into a nonapproved region during fallback.
  7. Reusing cached answers across tenants, users or permission versions.
  8. Counting token price but ignoring extra attempts, reviews, observability and operations.
  9. Letting the model grant its own provider credentials, permissions or budgets.
  10. 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.

Editorial disclosure

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.