Skip to main content

Inference Gateway & LLM Gateway Routing Strategy

Published 2025-02-05Updated 2026-07-0451 min read

This document covers design principles for 2-Tier gateway architecture and routing strategies (Cascade / Semantic Router / Hybrid). For actual deployment procedures including Helm installation, HTTPRoute manifests, and OTel integration, refer to Inference Gateway Deployment Guide.

Overview​

In large-scale AI model serving environments, infrastructure traffic management and LLM provider abstraction must be separated. A single gateway leads to exponential complexity and makes optimizing each layer difficult.

2-Tier Gateway Architecture:

  • L1 (Ingress Gateway): kgateway β€” Kubernetes Gateway API standard, traffic routing, mTLS, rate limiting
  • L2-A (Inference Gateway): Bifrost/LiteLLM β€” Provider integration, cascade routing, semantic caching
  • L2-B (Data Plane): agentgateway β€” MCP/A2A protocols, stateful session management

Each tier is managed independently, separating infrastructure and AI workloads.


2-Tier Gateway Architecture​

Gateway layer definitions are unified in a dedicated document

The platform-wide gateway-layer terminology and role definitions are consolidated in Tiered Gateway Architecture. This document focuses on the routing strategy of Tier 2-A (LLM API Gateway). For in-cluster inference pod routing (Tier 2 β‘  Inference Extension), see the Gateway API Inference Extension section below.

Gateway Layer Separation​

LLM inference platforms must clearly distinguish 3 different Gateway roles. (For the full layer definitions, see Tiered Gateway Architecture)

Gateway TypeRoleImplementationLocation
Ingress GatewayExternal traffic ingress, TLS termination, path-based routingkgateway (NLB integration)Tier 1
LLM API GatewayModel selection, intelligent routing, request cascading (external/internal model abstraction)Bifrost / LiteLLMTier 2-A
Agent Data PlaneMCP/A2A protocols, stateful sessions, tool routingagentgatewayTier 2-B

Terminology note: Here, Tier 2-A "LLM API Gateway" is a provider proxy (Bifrost/LiteLLM) that abstracts the model API. It serves a different purpose from the Gateway API Inference Extension (Tier 2 β‘ , later in this document) that routes to in-cluster inference pods.

Core Principles:

  • Ingress Gateway (kgateway): Handles network-level traffic control only. Does not include model selection logic
  • LLM API Gateway (Bifrost/LiteLLM): Analyzes request complexity β†’ Automatically selects appropriate model β†’ Cost optimization
  • Agent Data Plane (agentgateway): Handles AI-specific protocols (MCP/A2A), maintains stateful sessions

Overall Architecture​

Responsibility Separation by Tier​

TierComponentResponsibilityProtocol
Tier 1 (Ingress Gateway)kgateway (Envoy-based)Traffic routing, mTLS, rate limiting, network policiesHTTP/HTTPS, gRPC
Tier 2-A (LLM API Gateway)Bifrost / LiteLLMIntelligent model selection, cost tracking, request cascading, semantic cachingOpenAI-compatible API
Tier 2-B (Agent Data Plane)agentgatewayMCP/A2A session management, self-hosted inference routing, Tool Poisoning preventionHTTP, JSON-RPC, MCP, A2A

Traffic Flow​

External LLM: Client β†’ kgateway β†’ Bifrost/LiteLLM (Cascade + Cache) β†’ OpenAI β†’ Response + Cost tracking Self-hosted vLLM: Client β†’ kgateway β†’ agentgateway β†’ vLLM β†’ Response


kgateway (L1 Inference Gateway)​

Gateway API-based Routing​

kgateway implements the Kubernetes Gateway API standard, enabling vendor-neutral configuration.

ComponentRoleDescription
GatewayClassGateway implementation definitionDesignate Kgateway controller
GatewayEntry point definitionConfigure listeners, TLS, addresses
HTTPRouteRouting rulesPath, header-based routing
BackendModel servicevLLM, TGI and other inference servers

Gateway API v1.2.0+ provides HTTPRoute improvements, GRPCRoute stabilization, and BackendTLSPolicy, fully supported by kgateway v2.0+.

Dynamic Routing Concepts​

Routing TypeCriteriaUse Case
Header-basedx-model-id, x-providerBackend selection by model/provider
Path-based/v1/chat/completions, /v1/embeddingsService separation by API type
Weight-basedbackendRef weightCanary deployment, A/B testing
Composite conditionsHeaders + Path + TierPremium/standard customer backends

Canary deployments start with 5-10% traffic and gradually increase, with immediate rollback via weight=0 on issues.

Load Balancing Strategies​

StrategyDescriptionSuitable Scenario
Round RobinSequential distribution (default)Uniform model instances
RandomRandom distributionLarge backend pools
Consistent HashSame key β†’ Same backendKV Cache reuse, session affinity

Consistent Hash is particularly useful for LLM inference. Routing requests from the same user to the same vLLM instance increases prefix cache hit rates, significantly improving TTFT (Time to First Token).

Topology-Aware Routing (Kubernetes 1.33+)​

Kubernetes 1.33+ topology-aware routing prioritizes same-AZ Pod communication to reduce cross-AZ data transfer costs.

πŸš€ Topology-Aware Routing Effects
MetricBeforeTopology-AwareImprovement
Cross-AZ TrafficHighMinimized
50% data transfer cost savings
LatencyHigh (cross-AZ)Low (same AZ)
30-40% P99 latency improvement
Network BandwidthLimitedOptimized
20-30% throughput increase

Failure Handling Concepts​

MechanismDescriptionLLM Inference Considerations
TimeoutMaximum processing time per requestLLM long response generation takes tens of seconds. Adequate timeout needed (120s+)
RetryAuto-retry on 5xx, timeout, connection failureMax 3 retries. Infinite retries cause system overload
Circuit BreakerTemporarily block backend on consecutive failuresSet maxEjectionPercent to 50% or below to ensure at least half backends available

For streaming responses, backendRequest timeout is for first byte, request is for total time. POST retries require idempotency guarantees (caution with tool calls).


LLM Gateway Solution Comparison​

Major Solution Comparison Table​

SolutionLanguageKey FeaturesCascade RoutingLicenseBest For
BifrostGo/Rust50x faster, CEL Rules conditional routing, failoverCEL Rules + external classifierApache 2.0High performance, low cost, self-hosted
LiteLLMPython100+ providers, native complexity-based routingrouting_strategy: complexity-basedMITPython ecosystem, rapid prototyping
vLLM Semantic RouterPythonvLLM-only, lightweight embedding-based routingEmbedding similarity-basedApache 2.0vLLM standalone environment
PortkeyTypeScriptSOC2 certified, semantic caching, Virtual KeysSupportedProprietary + OSSEnterprise, compliance
Kong AI GatewayLua/CMCP support, leverages existing Kong infraPluginApache 2.0 / EnterpriseExisting Kong users
HeliconeRustGateway + Observability integrated, high performanceSupportedApache 2.0High performance + observability needed
OpenRouterSaaS (hosted)Unified API for 400+ modelsΒ·60+ providers, provider fallback, OpenAI-compatibleProvider routing supportedSaaS (commercial)Fast multi-provider integration, prototyping
Self-hosted vs SaaS

In the table above, BifrostΒ·LiteLLMΒ·HeliconeΒ·vLLM Semantic Router are self-hosted (deployed in-cluster), whereas OpenRouter is hosted SaaS. SaaS provides instant access to 400+ models and delegates provider fallback/billing, which is advantageous for fast integration and prototyping. However, since prompts are sent to an external service, review the governance considerations for environments with data sovereignty or regulatory requirements.

Bifrost vs LiteLLM​

Bifrost: Go/Rust implementation with 50x faster throughput than Python, 1/10 memory usage. CEL Rules enable conditional routing (header-based cascade, failover). Helm Chart deployment, OpenAI-compatible API. Proxy latency < 100us. Intelligent cascade via app-side complexity score calculation β†’ x-complexity-score header β†’ CEL rule branching pattern or Go Plugin.

LiteLLM: 100+ provider support, native complexity-based routing (activate with 1-line routing_strategy: complexity-based config), one-line Langfuse integration (success_callback: ["langfuse"]), direct LangChain/LlamaIndex integration. However, Python-based with lower throughput, higher memory usage.

Selection Criteria​

Use CaseRecommended SolutionReason
Intelligent cascade (convenience priority)LiteLLMNative complexity-based routing, 1-line config
Intelligent cascade (performance priority)BifrostCEL Rules + external classifier, 50x faster
vLLM standalone environmentvLLM Semantic RoutervLLM native, lightweight routing
High performance, low cost self-hostedBifrost50x faster processing, low memory
Python ecosystem (LangChain)LiteLLMNative integration, 100+ providers
Enterprise compliancePortkeySOC2/HIPAA/GDPR, Semantic Cache
High performance + observability integratedHeliconeRust-based All-in-one
ScenarioRecommended StackReason
Startup/PoCkgateway + LiteLLMLow cost, 10-min deployment, complexity routing 1-line
Self-hosted focused (performance)kgateway + Bifrost (CEL cascade) + agentgatewayHigh performance, external+self-hosted pool 2-Tier
Enterprise multi-providerkgateway + Portkey + LangfuseCompliance, 250+ providers
Hybrid (external+self-hosted)kgateway + Bifrost/LiteLLM + agentgatewayExternal via Bifrost/LiteLLM, self-hosted via agentgateway
Global deploymentCloudflare AI Gateway + kgatewayEdge caching, DDoS protection

Request Cascading: Intelligent Model Routing​

Request Cascading is an intelligent optimization technique that automatically analyzes request complexity and routes to the appropriate model. The three patterns (weight-based, fallback-based, intelligent routing), implementation approach comparison (LLM Classifier, LiteLLM, vLLM Semantic Router), RouteLLM research reference, and cost savings are covered in detail in Request Cascading β€” Intelligent Model Routing.

For threshold/keyword tuning and misroute detection operations, see Cascade Routing Tuning.


Gateway API Inference Extension​

Kubernetes Gateway API enables managing LLM inference as Kubernetes-native resources through Inference Extension.

Core CRDs (Custom Resource Definitions)​

CRDRoleExample
InferenceModelDefine per-model serving policies (criticality, routing rules)criticality: high β†’ dedicated GPU allocation
InferencePoolModel serving Pod group (vLLM replicas)replicas: 3 β†’ 3 vLLM instances
LLMRouteRules for routing requests to InferenceModelx-model-id: glm-5 β†’ GLM-5 Pool

For detailed YAML manifests, refer to Inference Gateway Deployment Guide.

Gateway API Inference Extension Integration​

Gateway API Inference Extension integrates with kgateway + llm-d EPP to provide Kubernetes-native inference routing:

Current Status: Actively developed as CNCF project. Expected to provide alpha in Kubernetes 1.34+; production use not currently recommended. For production deployment, refer to Reference Architecture guides.


Semantic Caching​

Semantic Caching detects semantically similar prompts and reuses previous responses, simultaneously reducing LLM API costs and latency. At the Gateway level (Bifrost/LiteLLM/Portkey), HIT/MISS is determined by embedding similarity, so it can be combined independently with KV Cache (vLLM) Β· Prompt Cache (provider-managed).

Recommended default threshold: 0.85 β€” allows same meaning, different expression

Design principles (3-tier cache comparison, similarity threshold tradeoffs, tool comparison table, cache key design, observabilityΒ·production checklist) are covered in detail in separate documentation.


agentgateway Data Plane​

Overview​

agentgateway is an AI workload-dedicated data plane for kgateway. Traditional Envoy is optimized for stateless HTTP/gRPC, but AI agents have special requirements like stateful JSON-RPC sessions, MCP protocols, and Tool Poisoning prevention.

Envoy vs agentgateway Comparison​

ItemEnvoy Data Planeagentgateway
Session ManagementStateless, HTTP cookie-basedStateful JSON-RPC sessions, in-memory session store
ProtocolsHTTP/1.1, HTTP/2, gRPCMCP (Model Context Protocol), A2A (Agent-to-Agent)
SecuritymTLS, RBACTool Poisoning prevention, per-session Authorization
RoutingPath/header-basedSession ID-based, tool call validation
ObservabilityHTTP metrics, Access LogLLM token tracking, tool call chains, cost

Core Features​

1. Stateful JSON-RPC Session Management: X-MCP-Session-ID header-based session tracking, Sticky Session routing, automatic inactive session cleanup (default 30 minutes)

2. Native MCP/A2A Protocol Support: /mcp/v1 (MCP protocol), /a2a/v1 (A2A agent communication) path support

3. Tool Poisoning Prevention: Allowed tool list, dangerous tool blocking (exec_shell, read_credentials), response size limits, integrity verification (SHA-256)

4. Per-session Authorization: JWT token verification, role-based tool access, session hijacking prevention

agentgateway Project Status

agentgateway is an AI-dedicated data plane separated from the kgateway project in late 2025, currently under active development. Features are continuously added to keep pace with rapid evolution of MCP and A2A protocols.


Monitoring & Observability​

Core Metrics​

Core metrics to monitor in AI inference gateways:

πŸ“Š Kgateway Prometheus Metrics
MetricDescriptionUsage
kgateway_requests_total
Total request countTraffic monitoring
kgateway_request_duration_seconds
Request processing timeLatency analysis
kgateway_upstream_rq_xx
Backend response codesError tracking
kgateway_upstream_cx_active
Active connectionsCapacity planning
kgateway_retry_count
Retry countStability analysis
Metric CategoryKey ItemMeaning
LatencyTTFT (Time to First Token)Time until first token generation. User-perceived responsiveness
ThroughputTPS (Tokens Per Second)Tokens generated per second. Model serving efficiency
Error Rate5xx / Total RequestsBackend failure ratio. Immediate action if > 5%
Cache Hit RateCache Hit / Total RequestsSemantic Cache efficiency. 30%+ recommended
CostToken usage by model Γ— unit priceReal-time cost tracking

Langfuse OTel Integration​

Send OTel traces from Bifrost/LiteLLM to Langfuse to track prompts/completions, token usage, cost analysis, and tool call chains. Bifrost activates via otel plugin, LiteLLM via success_callback: ["langfuse"] config. For detailed configuration, refer to Monitoring Stack Setup.

AlertConditionSeverity
High error rate5xx > 5% (5 min)Critical
High latencyP99 > 30s (5 min)Warning
Circuit breaker activatedcircuit_breaker_open == 1Critical
Cache hit rate dropCache hit < 30%Warning
Budget approachingBudget > 80%Warning

Production Deployment Guides​

For actual code examples and YAML manifests, refer to Reference Architecture section:

Cost and Observability​


References​

Official Documentation​

LLM Providers​

Research Papers & Patterns​