Azure AI Gateway
Centralize LLM traffic through a controlled gateway for security, observability, policy enforcement, and cost control.
Use This Skill When
- The user needs one entry point for multiple models (Azure OpenAI, third-party LLMs, internal models)
- The user needs to enforce token budgets, rate limits, or SLA policies
- The user needs centralized auditing and compliance logging
- The user needs intelligent fallback (model outage handling)
- The user wants to avoid client-side model management complexity
Context: Gateway Maturity
Immature: Clients call models directly, no centralization
Developing: Basic gateway, simple routing, minimal logging
Managed: Multi-model routing, policy enforcement, token budgets, audit trails → Target
Optimized: Real-time cost optimization, feedback-driven routing, self-healing, ML-based model selection
Required Inputs
- Model endpoints: Azure OpenAI? Hugging Face? Internal models? Multiple versions?
- Routing criteria: Latency? Cost? Specific models for specific tasks?
- Policy requirements: Rate limits? Token budgets? Approval workflows?
- Scale: Throughput (req/sec)? Concurrent users? Peak vs. average?
- Compliance: PII redaction? Audit trail retention? Data residency?
- Cost model: Budget cap? Cost-per-department? Showback?
Decision Tree
What's the primary goal of this gateway?
├─ Cost control → Route to cheaper model if accuracy acceptable
├─ Reliability → Route to alternative model on failure/timeout
├─ Governance → Enforce policies, audit all requests
├─ Performance → Route based on latency SLA
└─ Multi-tenancy → Tenant isolation, quota per tenant
Which models will the gateway route to?
├─ Single model (single Azure OpenAI deployment) → No routing needed
├─ Multiple Azure OpenAI models → Route by task/cost/latency
├─ Multiple providers (Azure OpenAI + third-party) → Handle auth differences
└─ Canary/blue-green (new model test) → Weighted routing
What policy enforcement is needed?
├─ None (simple routing only)
├─ Token budgets (cap usage per user/org)
├─ Rate limits (req/sec, concurrent, bursts)
├─ Approval workflows (route restricted requests for review)
└─ Compliance (PII redaction, output filtering, audit)
How much data volume?
├─ < 100 req/sec → Simple load balancer
├─ 100-1000 req/sec → Async processing, queue buffering
└─ > 1000 req/sec → Distributed gateway, database-backed quotas
Workflow
Phase 1: Design Gateway Architecture
┌─ Client Application ─┐
│ (web, mobile, API) │
└──────────┬───────────┘
│ (HTTPS)
│
┌──────▼─────────────────────────────────────┐
│ AI Gateway (entry point) │
│ │
│ 1. Authenticate client (API key, JWT) │
│ 2. Check token budget (quota system) │
│ 3. Log request (audit trail) │
│ 4. Validate payload (safety checks) │
└──────┬─────────────────────────────────────┘
│
┌──────▼──────────────────┐
│ Routing & Policy Engine │
│ │
│ ├─ Route to model 1 │
│ ├─ Route to model 2 │
│ └─ Fallback to model 3 │
└──────┬──────────────────┘
│
┌──────▼──────────────────────────────────────────┐
│ Model Pools │
│ │
│ [Azure OpenAI GPT-4] → $0.03 per 1K in │
│ [Azure OpenAI GPT-3.5]→ $0.0015 per 1K in │
│ [Third-party LLaMA] → $0.01 per 1K in │
│ [Custom Model (AKS)] → On-premise │
└──────────────────────────────────────────────────┘
│
┌──────▼──────────────────────────────────┐
│ Observability │
│ │
│ ├─ Application Insights (traces) │
│ ├─ Log Analytics (audit logs) │
│ ├─ Cost Management (spend tracking) │
│ └─ Alerts (budget overrun, failures) │
└─────────────────────────────────────────┘
Phase 2: Implement Gateway (Choose Stack)
Option 1: Azure API Management + Logic Apps (low-code)
Client → [API Management] → [Logic App] → [Model endpoints]
Benefits:
- Built-in rate limiting, throttling
- Policy enforcement (transformations, auth)
- Analytics and metrics
Limitations:
- Limited model-specific logic
- Async processing harder
Option 2: Custom Service (Node.js, Python, Go)
# App Service or Container Apps
az containerapp create \
--resource-group $RG \
--name "ai-gateway" \
--image "myacr.azurecr.io/ai-gateway:latest" \
--target-port 8000 \
--environment-variables \
OPENAI_ENDPOINT="https://myai.openai.azure.com/" \
OPENAI_KEY="@keyvault(openai-key)" \
FALLBACK_MODEL="gpt-35-turbo"
Option 3: Azure Service Fabric / Kubernetes (scale-out)
Each node = independent gateway instance
Database = shared quota store (Redis, SQL)
Enables high-throughput, multi-region
Phase 3: Configure Routing Rules
Cost-optimized routing:
# Python pseudo-code
def route_to_model(prompt, required_accuracy=0.9):
# Try cheap model first
try:
response = gpt35_turbo.call(prompt, timeout=2)
if quality_score(response) >= required_accuracy:
return response
except Timeout:
pass
# Fallback to expensive but reliable model
response = gpt4.call(prompt, timeout=5)
return response
# Cost breakdown
# 1000 requests: 700 via GPT-3.5 ($1.05) + 300 via GPT-4 ($9.00) = $10.05
# vs. Direct to GPT-4: 1000 × $0.03 = $30
Latency-optimized routing:
SLA: Response < 500ms
Route 1: Model A (avg 100ms) → Use for 80% of traffic
Route 2: Model B (avg 300ms) → Use for 20% of traffic
Route 3: Model C (avg 1500ms) → Failover only if others fail
Canary / Blue-Green:
New Model (v2):
└─ 5% of traffic for 1 hour
├─ Monitor error rate, latency, cost
└─ If healthy, shift to 50%, then 100%
Old Model (v1):
└─ 95% of traffic (safe)
Phase 4: Enforce Policies
Rate limiting (prevent abuse):
Per-client:
├─ 10 requests/sec (burst)
├─ 100,000 requests/day
└─ 500 concurrent connections
Global:
├─ 100,000 requests/sec (max capacity)
└─ Backpressure: Queue & retry with exponential backoff
Token budgeting (control cost):
class TokenQuota:
def __init__(self, daily_limit=1_000_000):
self.limit = daily_limit
self.used = 0 # Track in Redis/database
def check_and_deduct(self, tokens_needed):
current = redis.get(f"quota:{user_id}")
if current + tokens_needed > self.limit:
raise QuotaExceededError(f"Budget exceeded")
redis.incr(f"quota:{user_id}", tokens_needed)
# Cost cap: $100/day per customer
# If usage exceeds budget, reject or queue for review
Approval workflows (for sensitive operations):
Request: "Summarize confidential document X"
├─ Payload > 10K tokens? → Route to human review
├─ Contains PII pattern? → Route to compliance team
└─ User has restricted tag? → Require manager approval
Approved → Route to model
Rejected → Return error with reason
Input/output filtering:
Input validation:
├─ Reject prompts with SQL injection patterns
├─ Reject attempts to override system prompt
└─ Redact email/SSN before sending to model
Output filtering:
├─ Block generation of malware/illegal content
├─ Redact PII before returning to user
└─ Flag hallucinated data if confidence low
Phase 5: Implement Observability
Log every request (for audit):
// C# - Log to Application Insights
var properties = new Dictionary<string, string>
{
{ "ClientId", clientId },
{ "Model", selectedModel },
{ "TokensIn", tokensIn.ToString() },
{ "TokensOut", tokensOut.ToString() },
{ "Cost", cost.ToString() },
{ "LatencyMs", latency.ToString() },
{ "Status", response.StatusCode.ToString() }
};
telemetryClient.TrackEvent("ai_gateway_request", properties);
Cost tracking:
# Daily cost by model
customMetrics
| where name == "ai_gateway_cost"
| extend Model = tostring(customDimensions.model)
| summarize TotalCost = sum(value) by Model, bin(timestamp, 1d)
Alerts:
- Budget exceeded: >$500/day
- Model failure: 5+ consecutive timeouts
- Latency spike: p95 > 2000ms
- Abuse pattern: 1000+ req/min from single IP
Phase 6: Deploy & Manage
Deploy gateway:
# Container Apps
az containerapp up \
--source . \
--build-env-vars "GATEWAY_VERSION=1.0" \
--environment-variables "OPENAI_ENDPOINT=..." \
--secrets "openai-key=$(az keyvault secret show --vault-name $KV --name openai-key --query value)"
Monitor SLA:
Target SLA: 99.9% uptime
├─ Availability: Measure successful responses / total requests
├─ Latency p95: < 500ms
├─ Cost per request: < $0.002
└─ Error rate: < 0.1%
Update routes (zero-downtime):
Current: 100% → Model A
Step 1: 90% → Model A, 10% → Model B (canary)
Step 2: Monitor for 1 hour
Step 3: 50% → Model A, 50% → Model B (if healthy)
Step 4: 0% → Model A, 100% → Model B (complete)
Output Contract
Gateway Architecture
- Deployment topology (App Service, Container Apps, API Mgmt)
- Model endpoints and routing rules
- Fallback and failover strategy
Policy & Control Definitions
- Rate limits (req/sec, daily cap)
- Token budgets (cost cap per user/org)
- Approval workflows for restricted operations
- Input/output filtering rules
Security & Compliance
- Authentication (API key, JWT, mTLS?)
- Authorization (RBAC roles)
- PII/sensitive data handling
- Audit trail requirements
Monitoring & Cost
- Observability dashboards (latency, errors, cost)
- Alerts for anomalies and budget overrun
- Cost breakdown by model/user/department
- SLO targets (availability, latency, cost)
Operational Runbook
- Deployment and rollback procedures
- How to add/remove models
- Incident response (model outage, quota exhausted)
Guardrails
- Never bypass policy checks: All requests through gateway, no direct model access.
- Protect API keys: Store model endpoints and secrets in Key Vault, never in code.
- Implement rate limiting: Prevent token stuffing and DDoS attacks.
- Log for compliance: Maintain audit trail for sensitive operations.
- Plan for failover: At least 2 model endpoints, automatic switchover on failure.
- Monitor cost closely: Set budget alerts; can spiral quickly with large batch jobs.
- Test routing changes: Use canary deployment before full rollout.
- Enforce timeouts: Prevent hanging requests from consuming resources indefinitely.
1---2name: azure-aigateway3description: Design an Azure AI gateway layer for centralized model routing, policy enforcement, and operational control. Use this skill when users ask about centralized AI traffic management, model governance, rate limiting, or gateway patterns.4---56# Azure AI Gateway78Centralize LLM traffic through a controlled gateway for security, observability, policy enforcement, and cost control.910## Use This Skill When1112- The user needs one entry point for multiple models (Azure OpenAI, third-party LLMs, internal models)13- The user needs to enforce token budgets, rate limits, or SLA policies14- The user needs centralized auditing and compliance logging15- The user needs intelligent fallback (model outage handling)16- The user wants to avoid client-side model management complexity1718## Context: Gateway Maturity1920**Immature**: Clients call models directly, no centralization 21**Developing**: Basic gateway, simple routing, minimal logging 22**Managed**: Multi-model routing, policy enforcement, token budgets, audit trails → **Target** 23**Optimized**: Real-time cost optimization, feedback-driven routing, self-healing, ML-based model selection2425## Required Inputs2627- **Model endpoints**: Azure OpenAI? Hugging Face? Internal models? Multiple versions?28- **Routing criteria**: Latency? Cost? Specific models for specific tasks?29- **Policy requirements**: Rate limits? Token budgets? Approval workflows?30- **Scale**: Throughput (req/sec)? Concurrent users? Peak vs. average?31- **Compliance**: PII redaction? Audit trail retention? Data residency?32- **Cost model**: Budget cap? Cost-per-department? Showback?3334## Decision Tree3536```37What's the primary goal of this gateway?38├─ Cost control → Route to cheaper model if accuracy acceptable39├─ Reliability → Route to alternative model on failure/timeout40├─ Governance → Enforce policies, audit all requests41├─ Performance → Route based on latency SLA42└─ Multi-tenancy → Tenant isolation, quota per tenant4344Which models will the gateway route to?45├─ Single model (single Azure OpenAI deployment) → No routing needed46├─ Multiple Azure OpenAI models → Route by task/cost/latency47├─ Multiple providers (Azure OpenAI + third-party) → Handle auth differences48└─ Canary/blue-green (new model test) → Weighted routing4950What policy enforcement is needed?51├─ None (simple routing only)52├─ Token budgets (cap usage per user/org)53├─ Rate limits (req/sec, concurrent, bursts)54├─ Approval workflows (route restricted requests for review)55└─ Compliance (PII redaction, output filtering, audit)5657How much data volume?58├─ < 100 req/sec → Simple load balancer59├─ 100-1000 req/sec → Async processing, queue buffering60└─ > 1000 req/sec → Distributed gateway, database-backed quotas61```6263## Workflow6465### Phase 1: Design Gateway Architecture6667```68┌─ Client Application ─┐69│ (web, mobile, API) │70└──────────┬───────────┘71 │ (HTTPS)72 │73 ┌──────▼─────────────────────────────────────┐74 │ AI Gateway (entry point) │75 │ │76 │ 1. Authenticate client (API key, JWT) │77 │ 2. Check token budget (quota system) │78 │ 3. Log request (audit trail) │79 │ 4. Validate payload (safety checks) │80 └──────┬─────────────────────────────────────┘81 │82 ┌──────▼──────────────────┐83 │ Routing & Policy Engine │84 │ │85 │ ├─ Route to model 1 │86 │ ├─ Route to model 2 │87 │ └─ Fallback to model 3 │88 └──────┬──────────────────┘89 │90 ┌──────▼──────────────────────────────────────────┐91 │ Model Pools │92 │ │93 │ [Azure OpenAI GPT-4] → $0.03 per 1K in │94 │ [Azure OpenAI GPT-3.5]→ $0.0015 per 1K in │95 │ [Third-party LLaMA] → $0.01 per 1K in │96 │ [Custom Model (AKS)] → On-premise │97 └──────────────────────────────────────────────────┘98 │99 ┌──────▼──────────────────────────────────┐100 │ Observability │101 │ │102 │ ├─ Application Insights (traces) │103 │ ├─ Log Analytics (audit logs) │104 │ ├─ Cost Management (spend tracking) │105 │ └─ Alerts (budget overrun, failures) │106 └─────────────────────────────────────────┘107```108109### Phase 2: Implement Gateway (Choose Stack)110111**Option 1: Azure API Management + Logic Apps (low-code)**112```113Client → [API Management] → [Logic App] → [Model endpoints]114115Benefits: 116- Built-in rate limiting, throttling117- Policy enforcement (transformations, auth)118- Analytics and metrics119120Limitations:121- Limited model-specific logic122- Async processing harder123```124125**Option 2: Custom Service (Node.js, Python, Go)**126```bash127# App Service or Container Apps128az containerapp create \129 --resource-group $RG \130 --name "ai-gateway" \131 --image "myacr.azurecr.io/ai-gateway:latest" \132 --target-port 8000 \133 --environment-variables \134 OPENAI_ENDPOINT="https://myai.openai.azure.com/" \135 OPENAI_KEY="@keyvault(openai-key)" \136 FALLBACK_MODEL="gpt-35-turbo"137```138139**Option 3: Azure Service Fabric / Kubernetes (scale-out)**140```141Each node = independent gateway instance142Database = shared quota store (Redis, SQL)143Enables high-throughput, multi-region144```145146### Phase 3: Configure Routing Rules1471481. **Cost-optimized routing**:149 ```python150 # Python pseudo-code151 def route_to_model(prompt, required_accuracy=0.9):152 # Try cheap model first153 try:154 response = gpt35_turbo.call(prompt, timeout=2)155 if quality_score(response) >= required_accuracy:156 return response157 except Timeout:158 pass159 160 # Fallback to expensive but reliable model161 response = gpt4.call(prompt, timeout=5)162 return response163 164 # Cost breakdown165 # 1000 requests: 700 via GPT-3.5 ($1.05) + 300 via GPT-4 ($9.00) = $10.05166 # vs. Direct to GPT-4: 1000 × $0.03 = $30167 ```1681692. **Latency-optimized routing**:170 ```171 SLA: Response < 500ms172 173 Route 1: Model A (avg 100ms) → Use for 80% of traffic174 Route 2: Model B (avg 300ms) → Use for 20% of traffic175 Route 3: Model C (avg 1500ms) → Failover only if others fail176 ```1771783. **Canary / Blue-Green**:179 ```180 New Model (v2):181 └─ 5% of traffic for 1 hour182 ├─ Monitor error rate, latency, cost183 └─ If healthy, shift to 50%, then 100%184 185 Old Model (v1):186 └─ 95% of traffic (safe)187 ```188189### Phase 4: Enforce Policies1901911. **Rate limiting** (prevent abuse):192 ```193 Per-client:194 ├─ 10 requests/sec (burst)195 ├─ 100,000 requests/day196 └─ 500 concurrent connections197 198 Global:199 ├─ 100,000 requests/sec (max capacity)200 └─ Backpressure: Queue & retry with exponential backoff201 ```2022032. **Token budgeting** (control cost):204 ```python205 class TokenQuota:206 def __init__(self, daily_limit=1_000_000):207 self.limit = daily_limit208 self.used = 0 # Track in Redis/database209 210 def check_and_deduct(self, tokens_needed):211 current = redis.get(f"quota:{user_id}")212 if current + tokens_needed > self.limit:213 raise QuotaExceededError(f"Budget exceeded")214 redis.incr(f"quota:{user_id}", tokens_needed)215 216 # Cost cap: $100/day per customer217 # If usage exceeds budget, reject or queue for review218 ```2192203. **Approval workflows** (for sensitive operations):221 ```222 Request: "Summarize confidential document X"223 ├─ Payload > 10K tokens? → Route to human review224 ├─ Contains PII pattern? → Route to compliance team225 └─ User has restricted tag? → Require manager approval226 227 Approved → Route to model228 Rejected → Return error with reason229 ```2302314. **Input/output filtering**:232 ```233 Input validation:234 ├─ Reject prompts with SQL injection patterns235 ├─ Reject attempts to override system prompt236 └─ Redact email/SSN before sending to model237 238 Output filtering:239 ├─ Block generation of malware/illegal content240 ├─ Redact PII before returning to user241 └─ Flag hallucinated data if confidence low242 ```243244### Phase 5: Implement Observability2452461. **Log every request** (for audit):247 ```csharp248 // C# - Log to Application Insights249 var properties = new Dictionary<string, string>250 {251 { "ClientId", clientId },252 { "Model", selectedModel },253 { "TokensIn", tokensIn.ToString() },254 { "TokensOut", tokensOut.ToString() },255 { "Cost", cost.ToString() },256 { "LatencyMs", latency.ToString() },257 { "Status", response.StatusCode.ToString() }258 };259 260 telemetryClient.TrackEvent("ai_gateway_request", properties);261 ```2622632. **Cost tracking**:264 ```bash265 # Daily cost by model266 customMetrics267 | where name == "ai_gateway_cost"268 | extend Model = tostring(customDimensions.model)269 | summarize TotalCost = sum(value) by Model, bin(timestamp, 1d)270 ```2712723. **Alerts**:273 - Budget exceeded: >$500/day274 - Model failure: 5+ consecutive timeouts275 - Latency spike: p95 > 2000ms276 - Abuse pattern: 1000+ req/min from single IP277278### Phase 6: Deploy & Manage2792801. **Deploy gateway**:281 ```bash282 # Container Apps283 az containerapp up \284 --source . \285 --build-env-vars "GATEWAY_VERSION=1.0" \286 --environment-variables "OPENAI_ENDPOINT=..." \287 --secrets "openai-key=$(az keyvault secret show --vault-name $KV --name openai-key --query value)"288 ```2892902. **Monitor SLA**:291 ```292 Target SLA: 99.9% uptime293 ├─ Availability: Measure successful responses / total requests294 ├─ Latency p95: < 500ms295 ├─ Cost per request: < $0.002296 └─ Error rate: < 0.1%297 ```2982993. **Update routes (zero-downtime)**:300 ```301 Current: 100% → Model A302 Step 1: 90% → Model A, 10% → Model B (canary)303 Step 2: Monitor for 1 hour304 Step 3: 50% → Model A, 50% → Model B (if healthy)305 Step 4: 0% → Model A, 100% → Model B (complete)306 ```307308## Output Contract3093101. **Gateway Architecture**311 - Deployment topology (App Service, Container Apps, API Mgmt)312 - Model endpoints and routing rules313 - Fallback and failover strategy3143152. **Policy & Control Definitions**316 - Rate limits (req/sec, daily cap)317 - Token budgets (cost cap per user/org)318 - Approval workflows for restricted operations319 - Input/output filtering rules3203213. **Security & Compliance**322 - Authentication (API key, JWT, mTLS?)323 - Authorization (RBAC roles)324 - PII/sensitive data handling325 - Audit trail requirements3263274. **Monitoring & Cost**328 - Observability dashboards (latency, errors, cost)329 - Alerts for anomalies and budget overrun330 - Cost breakdown by model/user/department331 - SLO targets (availability, latency, cost)3323335. **Operational Runbook**334 - Deployment and rollback procedures335 - How to add/remove models336 - Incident response (model outage, quota exhausted)337338## Guardrails339340- **Never bypass policy checks**: All requests through gateway, no direct model access.341- **Protect API keys**: Store model endpoints and secrets in Key Vault, never in code.342- **Implement rate limiting**: Prevent token stuffing and DDoS attacks.343- **Log for compliance**: Maintain audit trail for sensitive operations.344- **Plan for failover**: At least 2 model endpoints, automatic switchover on failure.345- **Monitor cost closely**: Set budget alerts; can spiral quickly with large batch jobs.346- **Test routing changes**: Use canary deployment before full rollout.347- **Enforce timeouts**: Prevent hanging requests from consuming resources indefinitely.