PART 2 · PRODUCTION AI SYSTEMS · MODULE S5

AI Gateway, Semantic Cache & Model Routing

Absorb bursty multi-tenant token traffic with reconciled TPM/RPM rate limits, cut inference spend by 60%+ via tenant-isolated semantic caching and Small→Frontier model cascades, and survive upstream 429/529 outages without dropping SSE streams.

Act I · Scope, Cost & Throughput Math

Token Rate Limits, Semantic Savings & Failover Envelope

Step 1 of 5
Dual-Bucket Limiter
50K RPM / 40M TPM

Multi-tenant dual-bucket rate limiting: pre-flight estimated tokens reconciled against actual usage.total_tokens.

Semantic Cache Hits
38% – 52% Hit Rate

Vector semantic cache (cos ≥ 0.94) serves repeat intent in < 18 ms at $0.0002 vs $0.015/req.

Model Cascade Savings
68% Cost Reduction

Complexity router sends 72% of queries to Small 8B ($0.15/1M) and escalates 28% to Frontier 70B ($3.00/1M).

Proxy & Failover RTO
< 15 ms / < 250 ms

Gateway proxy P99 overhead (< 15 ms) and circuit-breaker cross-provider failover RTO (< 250 ms).

Act II · Wire Protocols, Cache & Circuit-Breaker Contracts

Gateway HTTP/SSE Envelope & Tenant-Isolated Cache Schema

Step 2 of 5
Gateway HTTP/SSE Envelope & Headers
Semantic Cache Key & Circuit Breaker Schema
Act III · Interactive 6-Node AI Gateway Simulator & Chaos Switchboard

Semantic Cache, Model Cascade & Multi-Provider Failover Lab

PROVIDER A: CLOSED
cos ≥ 0.94 · Cascade (8B→70B)
Cosine Threshold:
Routing Mode:
Gateway P99
12 ms
Proxy overhead < 15 ms
Semantic Hit Rate
44%
cos ≥ 0.94 + Intent Guard
Blended Cost / 1K Req
$2.10
68% below Frontier-Only
Upstream Health
Provider A: CLOSED
Error rate 0.1% (30s)
AI Gateway Topology · Rate Limit & Semantic Cache
SEMANTIC HIT
devices Client / SDK X-Tenant-ID: acme POST /completions SSE Stream Ready speed TPM/RPM Limiter Dual Token Bucket RESERVED · RECONCILE bolt Semantic Cache cos ≥ 0.94 · Isolated HIT 44% · 14ms alt_route Complexity Router Score 0.00–1.00 (<5ms) CASCADE: 72% 8B / 28% 70B Sticky Prefix Affinity ON cloud_done Provider A · Primary us-east-1 · 8B / 70B CLOSED · HEALTHY Err Rate: 0.1% (30s) swap_horiz Provider B · Failover eu-west-1 · Warm Pool STANDBY · READY RTO < 250ms · SSE Resume
STEP 1 · SEMANTIC CACHE

Loading AI Gateway simulator...

Live Semantic Cache & Cascade Inspector (4 Incoming Requests) 0 Cache Collisions
Incoming Prompt Nearest Cached Prompt Cosine Sim Cache Verdict Model Route Latency & Cost
Chaos Switchboard
0 Active
Live Gateway Event Console
Act IV · Zero-Dependency Python 3.12+ Blueprints

Standard-Library Python Core & Production Stack Mapping

Auto-Synced to Simulator
Production Stack Mapping Strip 6 AI Gateway Primitives
Pattern / Primitive Production Systems Why It Matters
AI Proxy & Token Rate Limiting Envoy AI Gateway, Kong AI, LiteLLM, Portkey Enforces per-tenant TPM/RPM quotas & reconciles post-stream token usage
Vector Semantic Cache Redis Stack (HNSW), Qdrant, GPTCache Serves repeat intent in <18ms within isolated tenant + system-prompt partitions
Model Routing & Cascades RouteLLM, Martian, Not Diamond Scores prompt complexity in <5ms to route 72% of traffic to cheap 8B models
Fast Token Counting tiktoken, HuggingFace Tokenizers (Rust) Estimates pre-flight prompt + max_tokens in microseconds before upstream dispatch
Multi-Region Failover & Pools AWS Bedrock Cross-Region, Azure APIM, Cloudflare AI Gateway Trips circuit breakers on 429/529 spikes and drains traffic in <250ms RTO
Cost & Token Telemetry OpenTelemetry GenAI SIG, Langfuse, Helicone Attributes exact token cost, cache savings, and escalation rates per tenant
Act V · Quality / Latency / Cost Tradeoffs & Production SLOs

Gateway Architecture Tradeoffs & Reliability Targets

Step 5 of 5
Tradeoff 01 Cache Safety

Semantic Cache Threshold vs. False Positives

Strict 0.94+ + Intent Guard

Blocks antonym/entity collisions (e.g. Cancel vs. Confirm flight) while still capturing 38–52% real paraphrase hits.

Loose 0.85 Threshold

Boosts raw hit rate past 60%, but silently returns wrong answers when embeddings cluster opposite verbs close together.

Verdict Enforce cos ≥ 0.94 paired with lightweight entity/verb polarity checks and strict tenant + system-prompt partition keys.
Tradeoff 02 Rate Limiting

Pre-Flight Token Estimation vs. Actual Billing

Reserve + Reconcile

Reserves prompt + max_tokens pre-flight to stop bursts safely, then refunds unused tokens on stream completion via usage.total_tokens.

Post-Hoc Only

Zero estimation overhead, but a sudden burst of 500 concurrent 16K prompts can blow past upstream TPM quotas before any stream finishes.

Verdict Always use two-phase Reserve & Reconcile so worst-case bursts are bounded without permanently penalizing short responses.
Tradeoff 03 Cost vs. Tail Latency

Model Cascade Latency Tax vs. 68% Spend Cut

Pre-Route (<5ms) + Cascade

A fast <5ms complexity classifier routes hard prompts straight to Frontier 70B while letting easy 72% run on 8B at 20x lower cost.

Blind Try-8B-First

Every failed 8B draft that escalates to 70B pays an extra ~300ms tail-latency tax and burns wasted draft tokens.

Verdict Combine a <5ms pre-router for obvious complex prompts with confidence escalation for borderline queries.
Tradeoff 04 Affinity vs. Resilience

Sticky Prefix Affinity vs. Active-Active Failover

Sticky + Breaker Failover

Pins a tenant to Provider A to maximize KV prefix cache hits (50% input discount), breaking affinity only when 429/529 error rate crosses 15%.

Round-Robin Active-Active

Spreads load evenly across providers, but destroys upstream KV prefix caching and causes jittery TTFT across regions.

Verdict Default to Sticky Prefix Affinity on healthy pools; let the Circuit Breaker fail over cleanly to Provider B in <250ms during outages.
Production Observability SLOs
AI Gateway Targets
Gateway Overhead < 15 ms P99 Limiter + cache + router
Provider Failover < 250 ms RTO Circuit breaker + SSE resume
Blended Spend Cut ≥ 55% Semantic cache + 8B cascade
Cross-Tenant Leaks 0.00% Scoped partition + prompt hash