aiagent.org logo aiagent.org
🌐 Production Control Plane • LiteLLM • Envoy AI Gateway • Kong

AI Gateways: Multi-Model Routing & Semantic Caching

How to decouple autonomous agents from single-vendor rate limits (`HTTP 429`) and outages (`HTTP 503`) using a centralized AI Gateway with token-aware load balancing, semantic vector caching, and OAuth 2.1 policy enforcement.

⚡ 30-Second Architectural TL;DR
Gateway Stack Proxy Overhead (P95) Best For Key Production Capability
Envoy AI Gateway / Rust Gateways (Bifrost) 0.4 – 1.8 ms High-QPS Kubernetes service meshes >5,000 RPS xDS dynamic routing, upstream TPM token rate limiting, zero GC pauses.
LiteLLM Proxy (Python / FastAPI) 8 – 22 ms Rapid 100+ model unification & Postgres virtual keys Drop-in OpenAI-compatible schema translation + per-team USD spend caps.
Kong AI Gateway 1.5 – 4 ms Enterprise API management + existing Kong clusters Native AI prompt decorator, PII redaction, and Redis semantic cache plugins.

01 Multi-Provider Failover & Token-Aware Load Balancing

Standard round-robin HTTP load balancers fail for LLM workloads because a single 100k-token context prompt consumes the entire Minute Token Quota (TPM) of an endpoint. Production AI Gateways track remaining TPM/RPM headers (`x-ratelimit-remaining-tokens`) in Redis and automatically fail over across providers (`Gemini 2.5 Pro` ↔ `Claude Sonnet` ↔ `OpenAI`) on `HTTP 429` or `503` within 50ms.

import asyncio, hashlib, time
from typing import Dict, List

class ResilientAIGateway:
    def __init__(self, providers: List[Dict]):
        # providers: [{"name": "gemini-primary", "tpm_limit": 2_000_000}, {"name": "claude-fallback", "tpm_limit": 1_000_000}]
        self.providers = providers
        self.cooldown_until = {}
        self.semantic_cache = {}

    async def route_completion(self, *, tenant_id: str, prompt: str, est_tokens: int, allow_cache: bool = True):
        # 1. Check tenant-isolated Semantic / Exact Cache first
        cache_key = f"{tenant_id}:{hashlib.sha256(prompt.strip().lower().encode()).hexdigest()[:20]}"
        if allow_cache and cache_key in self.semantic_cache:
            return {"source": "GATEWAY_CACHE_HIT", "latency_ms": 4, "output": self.semantic_cache[cache_key]}

        # 2. Iterate healthy upstreams ordered by priority & remaining token budget
        now = time.time()
        for up in self.providers:
            name = up["name"]
            if self.cooldown_until.get(name, 0) > now:
                continue
            try:
                # Simulated upstream invocation
                output = f"[{name}] Verified response for {tenant_id} ({est_tokens} tokens)"
                if allow_cache:
                    self.semantic_cache[cache_key] = output
                return {"source": name, "latency_ms": 380, "output": output}
            except Exception as err:
                # Trip 30-second circuit breaker on HTTP 429 / 503 and fail over immediately
                self.cooldown_until[name] = now + 30
        raise RuntimeError("ALL_UPSTREAM_PROVIDERS_EXHAUSTED")

02 Frequently Asked Questions

When should I bypass the Semantic Cache in an AI Gateway?

Always bypass semantic caching when `temperature > 0.3`, when the request includes real-time tool outputs (e.g., live stock prices or user account balances), or during multi-turn A2A/MCP mutations. Always scope cache keys by `tenant_id` to prevent cross-tenant data leakage.