Wenn der AI Gateway ausfällt: Incident-Response-Übungen für LLM-Traffic in Produktion
Ein AI Gateway ist der Single Point of Failure für alle LLM-Aufrufe und reißt bei einem Ausfall Chat-Assistent, Summarizer und Code-Copilot mit sich. Viele Teams haben dafür keine eingespielten Notfallprozesse.

Posted on Nov 30 • Originally published at tamiz.pro
Your AI gateway is the single point of failure for every LLM call in production. When it dies, your chat assistant, summarizer, and code copilot all die with it. The question isn't whether it will happen—it's whether you'll be ready. Most teams have no drill for LLM traffic; they have a vague runbook and hope. This tutorial fixes that. We'll build a complete incident response drill: SLOs, failure injection, automated runbook execution, and postmortem measurement. By the end, you'll have a repeatable practice that turns an AI gateway outage from a five-alarm fire into a well-rehearsed drill.
Traditional API gateways have mature incident practices. LLM gateways are different. They add latency, cost, and semantic degradation to the usual failure modes. A 503 from a REST endpoint is obvious; a 200 response that contains a truncated, hallucinated, or off-topic completion is not. Your on-call engineer needs to distinguish between a hard outage and a soft degradation—and the drill must exercise both.
Here are the failure modes you should plan for:
"Who pages you?" is the core question. The drill answers it by forcing a real page, through your real alerting path, to a real on-call engineer (or a designated drill observer). If nobody gets paged, your monitoring is broken. If the page goes to the wrong team, your escalation is broken. The drill exposes these gaps before a real incident does.
Note: This tutorial assumes you have a basic understanding of Kubernetes, PromQL, and CI/CD. If you're new to SRE, check out Tamiz's Insights for foundational articles.
+----------+ +-------------+ +---------------+ | Client | ---> | AI Gateway | ---> | LLM Providers | | (app) | | (deployment)| | (OpenAI, etc.)| +----------+ +-------------+ +---------------+ | | metrics v +-------------+ | Prometheus | +-------------+ | v +-------------+ | AlertManager| ---> PagerDuty +-------------+ Drill Harness (separate deployment) | toggles fault mode via HTTP endpoint v AI Gateway middleware checks fault flag Enter fullscreen mode Exit fullscreen mode The drill harness is a small service that can inject failures into the gateway. It exposes an endpoint like /fault/on and /fault/off. The gateway's middleware checks a shared flag (e.g., a ConfigMap or a Redis key) and, when enabled, returns a configurable status code (503, 429, or a timeout) for a percentage of requests.
This keeps the injection decoupled from the gateway's core logic.
Before you can drill, you need to know what "healthy" means. Define SLOs for your LLM traffic:
Create a Prometheus recording rule for the success rate. Save as slo-rules.yaml:
apiVersion: monitoring.coreos.com/v1 kind: PrometheusRule metadata: name: llm-gateway-slo namespace: monitoring spec: groups: - name: llm-gateway-slo interval: 30s rules: - record: job:llm_gateway_success_rate:rate5m expr: | sum(rate(http_requests_total{job="ai-gateway", status=~"2.."}[5m])) / sum(rate(http_requests_total{job="ai-gateway"}[5m])) - record: job:llm_gateway_p95_latency:5m expr: | histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{job="ai-gateway"}[5m])) by (le)) Enter fullscreen mode Exit fullscreen mode Now the alert rules. Save as alert-rules.yaml:
apiVersion: monitoring.coreos.com/v1 kind: PrometheusRule metadata: name: llm-gateway-alerts namespace: monitoring spec: groups: - name: llm-gateway-alerts interval: 30s rules: - alert: LLMGatewayHighErrorRate expr: | (1 - job:llm_gateway_success_rate:rate5m) > 0.01 for: 5m labels: severity: page annotations: summary: "AI Gateway error rate above 1%" description: "Error rate is {{ $value | humanizePercentage }} over 5m. Check the gateway." - alert: LLMGatewayHighLatency expr: | job:llm_gateway_p95_latency:5m > 2.0 for: 10m labels: severity: page annotations: summary: "AI Gateway p95 latency above 2s" description: "p95 latency is {{ $value }}s over 10m. Possible upstream provider issue." Enter fullscreen mode Exit fullscreen mode Apply them:
kubectl apply -f slo-rules.yaml -f alert-rules.yaml Enter fullscreen mode Exit fullscreen mode Configure AlertManager to route severity="page" alerts to PagerDuty. The key here is that the drill will trigger these exact alerts, so you'll know the paging path works end-to-end.
We'll build a simple FastAPI service that toggles a fault flag in a shared ConfigMap. The gateway middleware reads this flag. This approach is clean, reversible, and doesn't require modifying the gateway's code—just adding a middleware wrapper.
First, the harness. Create drill-harness/main.py:
import os import yaml from fastapi import FastAPI, HTTPException from kubernetes import client, config app = FastAPI ( title = "Drill Harness" ) CONFIG_MAP_NAME = "ai-gateway-fault" NAMESPACE = os. getenv ( "NAMESPACE", "default" ) def get_configmap ( ): config. load_incluster_config ( ) v1 = client. CoreV1Api ( ) return v1. read_namespaced_config_map ( CONFIG_MAP_NAME, NAMESPACE ) def update_configmap ( data: dict ): config. load_incluster_config ( ) v1 = client. CoreV1Api ( ) cm = v1. read_namespaced_config_map ( CONFIG_MAP_NAME, NAMESPACE ) cm. data. update ( data ) v1. patch_namespaced_config_map ( CONFIG_MAP_NAME, NAMESPACE, cm ) @app. post ( "/fault/on" ) def fault_on ( status_code: int = 503, rate: float = 1.0 ): if rate <= 0 or rate > 1: raise HTTPException ( 400, "rate must be (0, 1]" ) update_configmap ( { "fault_enabled": "true", "fault_status_code": str ( status_code ), "fault_rate": str ( rate ), } ) return { "status": "fault enabled", "status_code": status_code, "rate": rate } @app. post ( "/fault/off" ) def fault_off ( ): update_configmap ( { "fault_enabled": "false" } ) return { "status": "fault disabled" } @app. get ( "/fault/status" ) def fault_status ( ): cm = get_configmap ( ) return cm. data Enter fullscreen mode Exit fullscreen mode Now the gateway middleware.
Add this to your gateway's entrypoint (e.g., a FastAPI middleware or an nginx Lua script). Here's a Python middleware for a FastAPI-based gateway:
import random from fastapi import Request, Response async def fault_injection_middleware ( request: Request, call_next ): # Read fault config from a cached ConfigMap (refresh every 10s) fault = get_cached_fault_config ( ) if fault. get ( "fault_enabled" ) == "true": rate = float ( fault. get ( "fault_rate", 1.0 ) ) if random. random ( ) < rate: status_code = int ( fault. get ( "fault_status_code", 503 ) ) return Response ( content = "Fault injected", status_code = status_code ) return await call_next ( request ) Enter fullscreen mode Exit fullscreen mode Deploy the harness:
kubectl create configmap ai-gateway-fault --namespace default \ --from-literal=fault_enabled=false kubectl apply -f - << EOF apiVersion: apps/v1 kind: Deployment metadata: name: drill-harness namespace: drill spec: replicas: 1 selector: matchLabels: app: drill-harness template: metadata: labels: app: drill-harness spec: serviceAccountName: drill-harness-sa containers: - name: harness image: your-registry/drill-harness:latest ports: - containerPort: 8000 EOF kubectl create serviceaccount drill-harness-sa -n drill kubectl create rolebinding drill-harness-rb \ --clusterrole=edit \ --serviceaccount=drill:drill-harness-sa \ --namespace=default Enter fullscreen mode Exit fullscreen mode Test it: curl -X POST http://<harness-svc>/fault/on?status_code=503&rate=0.5 then hit the gateway—you should see a 50% failure rate. Then curl -X POST http://<harness-svc>/fault/off.
A drill without a runbook is chaos. Write a concise, actionable runbook that lives in your repo (e.g., docs/runbooks/ai-gateway-outage.md ). It should cover detection, triage, mitigation, and communication. Here's a template:
# AI Gateway Outage Runbook ## Detection - Alert: LLMGatewayHighErrorRate or LLMGatewayHighLatency - Check Grafana dashboard: error rate, p95, token usage ## Initial Triage (0-5 min) 1. Confirm the alert is real: `kubectl get pods -n default | grep ai-gateway` 2. Check gateway logs: `kubectl logs -n default deploy/ai-gateway --tail=200` 3.
Check upstream provider status (e.g., OpenAI status page) ## Mitigation (5-15 min) - If gateway is down: `kubectl rollout restart deploy/ai-gateway -n default` - If provider is degraded: fail over to a secondary provider - `kubectl set env deploy/ai-gateway -n default PRIMARY_PROVIDER=anthropic` - If rate-limited: enable client-side backoff and circuit breaker ## Communication - Post to #incident channel: `@incident-bot create --severity=SEV2` - Update stakeholders every 15 min ## Recovery - Verify success rate > 99% for 5 min - Disable fault injection (if drill): `curl -X POST http://<harness>/fault/off` - Close incident Enter fullscreen mode Exit fullscreen mode The runbook must be executable. In the drill, the on-call engineer will follow these exact steps. If a step fails, you've found a gap.
Manual drills are fine for the first run, but you want them repeatable. Create a GitHub Actions workflow that runs the drill on a schedule (e.g., every Monday at 03:00 UTC) or on manual dispatch. The workflow should:
Save as.github/workflows/ai-gateway-drill.yml:
name: AI Gateway Incident Drill on: schedule: - cron: '0 3 * * 1' # Monday 03:00 UTC workflow_dispatch: jobs: drill: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Configure kubectl uses: azure/setup-kubectl@v3 with: kubeconfig: ${{ secrets.KUBECONFIG }} - name: Deploy drill harness run: | kubectl apply -f k8s/drill-harness.yaml kubectl rollout status deploy/drill-harness -n drill --timeout=60s - name: Inject failure (503 at 100% rate) run: | kubectl exec deploy/drill-harness -n drill -- \ curl -X POST http://localhost:8000/fault/on \ -d 'status_code=503' -d 'rate=1.0' - name: Wait for alert to fire run: | # Poll AlertManager for the alert for i in {1..12}; do ALERT=$(curl -s http://alertmanager:9093/api/v2/alerts \ | jq '.[] | select(.labels.alertname=="LLMGatewayHighErrorRate")') if [ -n "$ALERT" ]; then echo "Alert fired after $((i*10))s" break fi sleep 10 done test -n "$ALERT" || exit 1 - name: Verify pager was triggered (mock PagerDuty) run: | # In production, call PagerDuty API to confirm an incident was created curl -s -X POST ${{ secrets.PAGERDUTY_API_URL }} \ -H "Authorization: Token ${{ secrets.PAGERDUTY_TOKEN }}" \ -d '{"type":"incident","title":"Drill: AI Gateway outage"}' \ | jq -e '.status == "triggered"' - name: Execute runbook mitigation (simulated) run: | # This is where the on-call engineer would run the real commands. # For the drill, we just verify the commands exist and are valid. bash -n docs/runbooks/ai-gateway-outage.md echo "Runbook commands syntactically valid" - name: Clear failure run: | kubectl exec deploy/drill-harness -n drill -- \ curl -X POST http://localhost:8000/fault/off - name: Collect metrics and upload report run: | # Generate a drill report from Prometheus queries python scripts/generate_drill_report.py \ --output drill-report-$(date +%Y%m%d).md cat drill-report-$(date +%Y%m%d).md Enter fullscreen mode Exit fullscreen mode This workflow is a starting point. In a real drill, you'd want a human to acknowledge the page and execute the runbook. We can automate the injection and measurement, but the response should be human-driven—that's the point of the drill.
Now run the drill. Before you do, make sure you have a way to measure success. Define these metrics:
Create a measurement script scripts/generate_drill_report.py:
#!/usr/bin/env python3 import argparse import json import time from datetime import datetime, timezone import requests PROMETHEUS_URL = "http://prometheus:9090" def query_prometheus ( query: str ): resp = requests. get ( f "{PROMETHEUS_URL}/api/v1/query", params = { "query": query } ) resp. raise_for_status ( ) return resp. json ( ) [ "data" ] [ "result" ] def main ( ): parser = argparse. ArgumentParser ( ) parser. add_argument ( "--output", required = True ) parser. add_argument ( "--start", required = True, help = "ISO timestamp of drill start" ) parser. add_argument ( "--end", required = True, help = "ISO timestamp of drill end" ) args = parser. parse_args ( ) start = int ( datetime. fromisoformat ( args. start ). timestamp ( ) ) end = int ( datetime. fromisoformat ( args. end ). timestamp ( ) ) # Query error rate during drill window error_rate = query_prometheus ( f "(1 - job:llm_gateway_success_rate:rate5m) and on() " f "timestamp(job:llm_gateway_success_rate:rate5m) >= {start} " f "and timestamp(job:llm_gateway_success_rate:rate5m) <= {end}" ) # Query p95 latency p95 = query_prometheus ( f "job:llm_gateway_p95_latency:5m and on() " f "timestamp(job:llm_gateway_p95_latency:5m) >= {start} " f "and timestamp(job:llm_gateway_p95_latency:5m) <= {end}" ) # Compute summary report = { "drill_start": args. start, "drill_end": args. end, "max_error_rate": max ( [ float ( r [ "value" ] [ 1 ] ) for r in error_rate ], default = 0 ), "max_p95_latency": max ( [ float ( r [ "value" ] [ 1 ] ) for r in p95 ], default = 0 ), "alert_fired": bool ( error_rate ), } with open ( args. output, "w" ) as f: f. write ( f "# AI Gateway Drill Report\n\n" ) f. write ( f "- **Start:** {args.start}\n" ) f. write ( f "- **End:** {args.end}\n" ) f. write ( f "- **Max error rate:** {report['max_error_rate']:.2%}\n" ) f. write ( f "- **Max p95 latency:** {report['max_p95_latency']:.2f}s\n" ) f. write ( f "- **Alert fired:** {report['alert_fired']}\n" ) print ( json. dumps ( report, indent = 2 ) ) if __name__ == "__main__": main ( ) Enter fullscreen mode Exit fullscreen mode Run the drill manually first:
# 1. Record start time START = $( date -u +%Y-%m-%dT%H:%M:%SZ ) # 2. Inject failure curl -X POST http:// < harness-svc > /fault/on?status_code=503 & rate = 1.0 # 3. Wait for the page (your on-call engineer should get a real PagerDuty alert) sleep 60 # 4. Have the on-call engineer execute the runbook #... (simulate or real) # 5. Clear failure curl -X POST http:// < harness-svc > /fault/off # 6. Generate report python scripts/generate_drill_report.py --output drill-report.md \ --start "$START" --end "$(date -u +%Y-%m-%dT%H:%M:%SZ)" Enter fullscreen mode Exit fullscreen mode Pro tip: Record the drill in a video or screen capture. Seeing your team's reaction to a real page is invaluable for postmortem review.
After the drill, hold a postmortem within 48 hours. Answer these questions:
date,drill_id,ttd_seconds,ttm_seconds,error_budget_burn_percent,notes 2024-06-03,drill-001,120,300,0.5,First run; alert fired at 2 min 2024-06-10,drill-002,45,150,0.2,Reduced TTD by 60% after tuning alert rules Enter fullscreen mode Exit fullscreen mode Use the postmortem to improve:
The drill is not a one-off. Run it monthly, or at least quarterly, to keep the muscle memory fresh. As your LLM traffic grows, the drill will catch regressions in your monitoring and response before they become real outages.
Yes. If you're using a managed gateway (e.g., Azure OpenAI, AWS Bedrock), you can't modify its middleware. Instead, inject failures at the client side or at a proxy in front of the managed service. Deploy a lightweight reverse proxy (like Envoy or a simple nginx) that can return 503s based on a flag, and route all LLM traffic through it. The drill then targets the proxy. The key is to inject failures before the managed service, so your alerting and runbook paths are still exercised.
Start monthly. If your team is new to the runbook, run it every two weeks for the first quarter. Once TTD and TTM stabilize, you can move to quarterly. However, if you change your gateway, alerting, or provider, run a drill immediately after the change. The drill is a regression test for your incident response—it should be part of your release process for any infrastructure change.
This is a real concern. Injecting failures at the gateway level doesn't directly cost LLM tokens—it returns errors before reaching the provider. But if your drill triggers fallback logic that retries against a secondary provider, you could incur costs. To mitigate: (1) set a hard budget for the drill in your CI/CD workflow (e.g., fail the drill if token spend exceeds $50), (2) use a mock provider for the drill if possible, or (3) cap the failure injection rate to 10–20% of traffic to limit retries. Always check your provider dashboard after a drill to confirm no unexpected spend.
This tutorial is part of a series on production AI infrastructure. For more on SLOs, chaos engineering, and LLM observability, visit tamiz.pro and Tamiz's Insights.