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.
calculate
Act I · Scope, Cost & Throughput Math
Token Rate Limits, Semantic Savings & Failover Envelope
Step 1 of 5
Dual-Bucket Limiter
speed
50K RPM / 40M TPM
Multi-tenant dual-bucket rate limiting: pre-flight estimated tokens reconciled against actual usage.total_tokens.
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
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
swap_horiz
< 15 ms / < 250 ms
Gateway proxy P99 overhead (< 15 ms) and circuit-breaker cross-provider failover RTO (< 250 ms).
data_object
Act II · Wire Protocols, Cache & Circuit-Breaker Contracts
Gateway HTTP/SSE Envelope & Tenant-Isolated Cache Schema
Step 2 of 5
hub
Act III · Interactive 6-Node AI Gateway Simulator & Chaos Switchboard
Semantic Cache, Model Cascade & Multi-Provider Failover Lab
PROVIDER A: CLOSED
bolt
1. Rate Limit & Semantic Cache
alt_route
2. Complexity Router & Cascade
swap_horiz
3. Circuit Breaker & SSE Failover
cos ≥ 0.94 · Cascade (8B→70B)
tune
Cosine Threshold:
0.85 (Loose)
0.94 (Strict)
0.98 (Exact)
fork_right
Routing Mode:
Cascade (8B→70B)
Frontier Only (70B)
Gateway P99
timer
12 ms
Proxy overhead < 15 ms
Semantic Hit Rate
bolt
44%
cos ≥ 0.94 + Intent Guard
Blended Cost / 1K Req
payments
$2.10
68% below Frontier-Only
Upstream Health
dns
Provider A: CLOSED
Error rate 0.1% (30s)
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
bolt
STEP 1 · SEMANTIC CACHE
Loading AI Gateway simulator...
table_chart
Live Semantic Cache & Cascade Inspector (4 Incoming Requests)
0 Cache Collisions
Incoming Prompt
Nearest Cached Prompt
Cosine Sim
Cache Verdict
Model Route
Latency & Cost
Primary Provider 429/529 Outage
OFF
Cache False-Positive Collision
OFF
Mid-Stream SSE Disconnect
OFF
crisis_alert
Trigger Provider Outage + Failover Drill
code
Act IV · Zero-Dependency Python 3.12+ Blueprints
Standard-Library Python Core & Production Stack Mapping
Auto-Synced to Simulator
layers
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
balance
Act V · Quality / Latency / Cost Tradeoffs & Production SLOs
Gateway Architecture Tradeoffs & Reliability Targets
Step 5 of 5
bolt
Tradeoff 01
Cache Safety
Semantic Cache Threshold vs. False Positives
check_circle Strict 0.94+ + Intent Guard
Blocks antonym/entity collisions (e.g. Cancel vs. Confirm flight) while still capturing 38–52% real paraphrase hits.
tune 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.
speed
Tradeoff 02
Rate Limiting
Pre-Flight Token Estimation vs. Actual Billing
check_circle Reserve + Reconcile
Reserves prompt + max_tokens pre-flight to stop bursts safely, then refunds unused tokens on stream completion via usage.total_tokens.
tune 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.
alt_route
Tradeoff 03
Cost vs. Tail Latency
Model Cascade Latency Tax vs. 68% Spend Cut
check_circle 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.
tune 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.
swap_horiz
Tradeoff 04
Affinity vs. Resilience
Sticky Prefix Affinity vs. Active-Active Failover
check_circle 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%.
tune 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.
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