Zum Inhalt

Rate Limiting Guide

Overview

Rate Limiting ist ein essenzielles Feature zur Kontrolle der Anzahl von Anfragen, die ein Client an Ihre API senden kann. Es hilft, Ihre Backend-Services vor Überlastung zu schützen und stellt sicher, dass alle Clients fair auf Ressourcen zugreifen können.

GAL bietet native Rate Limiting Unterstützung für alle unterstützten Gateway-Provider: - Envoy: local_ratelimit Filter - Kong: rate-limiting Plugin - APISIX: limit-count Plugin - Traefik: rateLimit Middleware - Nginx: ngx_http_limit_req_module - HAProxy: Stick Tables - Azure APIM: rate-limit Policy XML

Quick Start

Einfaches Rate Limiting

Fügen Sie Rate Limiting zu einer Route hinzu:

services:
  - name: api_service
    type: rest
    protocol: http
    upstream:
      host: api.internal
      port: 8080
    routes:
      - path_prefix: /api/v1
        methods: [GET, POST]
        rate_limit:
          enabled: true
          requests_per_second: 100
          burst: 200

Konfigurationsoptionen

Vollständige Rate Limit Konfiguration

rate_limit:
  enabled: true                          # Standard: true
  requests_per_second: 100               # Standard: 100
  burst: 200                             # Standard: requests_per_second * 2
  key_type: ip_address                   # Standard: ip_address
  key_header: X-API-Key                  # Optional: für key_type: header
  key_claim: sub                         # Optional: für key_type: jwt_claim
  response_status: 429                   # Standard: 429
  response_message: "Rate limit exceeded" # Standard: "Rate limit exceeded"

Parameter-Beschreibung

Parameter Typ Standard Beschreibung
enabled boolean true Aktiviert oder deaktiviert Rate Limiting
requests_per_second integer 100 Maximale Anzahl von Anfragen pro Sekunde
burst integer requests_per_second * 2 Burst-Kapazität für kurzzeitige Spitzen
key_type string ip_address Identifizierungs-Methode (ip_address, header, jwt_claim)
key_header string null Header-Name wenn key_type=header
key_claim string null JWT Claim wenn key_type=jwt_claim
response_status integer 429 HTTP Status Code bei Rate Limit Überschreitung
response_message string "Rate limit exceeded" Fehlermeldung bei Rate Limit Überschreitung

Key Types

IP-basiertes Rate Limiting

Limitiert basierend auf der Client-IP-Adresse (Standard):

rate_limit:
  enabled: true
  requests_per_second: 100
  key_type: ip_address

Header-basiertes Rate Limiting

Limitiert basierend auf einem spezifischen Request-Header (z.B. API-Key):

rate_limit:
  enabled: true
  requests_per_second: 1000
  key_type: header
  key_header: X-API-Key

JWT Claim-basiertes Rate Limiting

Limitiert basierend auf einem JWT Claim (z.B. user ID):

rate_limit:
  enabled: true
  requests_per_second: 500
  key_type: jwt_claim
  key_claim: sub

Beispiele

Public vs. Private API

Unterschiedliche Limits für verschiedene Endpunkte:

services:
  - name: api_service
    type: rest
    protocol: http
    upstream:
      host: api.internal
      port: 8080
    routes:
      # Public API - niedrigeres Limit
      - path_prefix: /api/public
        methods: [GET]
        rate_limit:
          enabled: true
          requests_per_second: 10
          burst: 20
          key_type: ip_address

      # Authenticated API - höheres Limit
      - path_prefix: /api/private
        methods: [GET, POST, PUT, DELETE]
        rate_limit:
          enabled: true
          requests_per_second: 100
          burst: 200
          key_type: header
          key_header: X-API-Key

Custom Error Response

Benutzerdefinierte Fehlerantwort:

rate_limit:
  enabled: true
  requests_per_second: 50
  response_status: 503
  response_message: "Service temporarily unavailable due to high load"

Rate Limiting mit Transformationen

Kombinieren Sie Rate Limiting mit Request Transformations:

services:
  - name: user_service
    type: rest
    protocol: http
    upstream:
      host: users.internal
      port: 8080
    routes:
      - path_prefix: /api/users
        methods: [POST]
        rate_limit:
          enabled: true
          requests_per_second: 50
          burst: 100
    transformation:
      enabled: true
      defaults:
        created_by: "api"
      computed_fields:
        - field: id
          generator: uuid
          prefix: "usr_"

Provider-spezifische Implementierungen

Kong

Kong verwendet das rate-limiting Plugin:

# Generierte Kong-Konfiguration
- name: api_service_route
  paths:
    - /api/v1
  plugins:
    - name: rate-limiting
      config:
        second: 100
        policy: local
        fault_tolerant: true

Features: - ✅ Per-Route Konfiguration - ✅ Lokale oder verteilte Rate Limiting (Redis/Cluster) - ✅ Verschiedene Zeitfenster (second, minute, hour, day)

APISIX

APISIX verwendet das limit-count Plugin:

{
  "routes": [{
    "uri": "/api/v1/*",
    "plugins": {
      "limit-count": {
        "count": 100,
        "time_window": 1,
        "rejected_code": 429,
        "rejected_msg": "Rate limit exceeded",
        "key": "remote_addr",
        "policy": "local"
      }
    }
  }]
}

Features: - ✅ Per-Route Konfiguration - ✅ Flexible Key-Strategien (IP, Header, Consumer) - ✅ Redis-basierte verteilte Limits

Traefik

Traefik verwendet die rateLimit Middleware:

http:
  middlewares:
    api_service_router_0_ratelimit:
      rateLimit:
        average: 100
        burst: 200
  routers:
    api_service_router_0:
      rule: 'PathPrefix(`/api/v1`)'
      middlewares:
        - api_service_router_0_ratelimit

Features: - ✅ Per-Route Konfiguration - ✅ Token-Bucket-Algorithmus - ✅ Burst-Handling

Envoy

Envoy verwendet den local_ratelimit Filter:

http_filters:
  - name: envoy.filters.http.local_ratelimit
    typed_config:
      '@type': type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit
      stat_prefix: http_local_rate_limiter
      token_bucket:
        max_tokens: 200
        tokens_per_fill: 100
        fill_interval: 1s
      status_code: 429

Features: - ⚠️ Globale Konfiguration (gilt für alle Routes) - ✅ Token-Bucket-Algorithmus - ✅ Hochperformant (C++)

Hinweis: Die aktuelle Envoy-Implementierung verwendet eine globale Rate Limiting Konfiguration. Für per-route Konfigurationen sollte der externe Rate Limit Service verwendet werden.

Nginx

Nginx verwendet das ngx_http_limit_req_module:

# Zone definieren (in http-Block)
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=100r/s;

# Rate Limit anwenden (in location-Block)
location /api/v1 {
    limit_req zone=api_limit burst=200 nodelay;
    limit_req_status 429;

    proxy_pass http://backend;
}

Features: - ✅ Per-Location Konfiguration - ✅ Leaky-Bucket-Algorithmus - ✅ Burst-Handling mit nodelay - ✅ Sehr hohe Performance - ✅ Shared Memory Zones

Hinweis: Nginx bietet eines der performantesten Rate Limiting Systeme. Die Zone-basierte Konfiguration ermöglicht flexible Limits pro Endpoint.

HAProxy

HAProxy verwendet Stick Tables für Rate Limiting:

# Frontend mit Rate Limiting
frontend api_front
    bind *:80

    # Track requests per IP
    stick-table type ip size 100k expire 10s store http_req_rate(1s)
    http-request track-sc0 src

    # Rate Limit: 100 req/s
    acl rate_limit sc0_http_req_rate gt 100
    http-request deny deny_status 429 if rate_limit

    default_backend api_backend

Features: - ✅ Stick Table-basiert (sehr performant) - ✅ Flexible Tracking (IP, Header, Session) - ✅ Verschiedene Zeitfenster - ⚠️ Manuelle ACL-Konfiguration erforderlich

Hinweis: HAProxy's Stick Tables bieten extrem niedrige Latenz für Rate Limiting. Eignet sich besonders für High-Traffic Szenarien.

Azure APIM

Azure API Management verwendet Policy XML für Rate Limiting:

<policies>
    <inbound>
        <base />
        <rate-limit calls="6000" renewal-period="60" />
    </inbound>
</policies>

Konvertierung: GAL konvertiert requests_per_second zu calls per renewal-period: - requests_per_second: 100calls="6000" renewal-period="60" (100 req/s * 60s = 6000 calls) - requests_per_second: 10calls="600" renewal-period="60" (10 req/s * 60s = 600 calls)

Features: - ✅ Product-Level Rate Limits (globale Limits pro Subscription Tier) - ✅ Operation-Level Rate Limits (spezifische Limits pro Endpoint) - ✅ Per-Subscription Tracking (Limits pro API Key) - ✅ Automatische 429 Responses mit Retry-After Header - ⚠️ Keine Burst-Konfiguration (festes Zeitfenster)

Azure APIM-spezifische Features:

Product-Level Limits:

azure_apim:
  product_name: "Starter-Tier"
  rate_limit_calls: 6000        # 100 req/s
  rate_limit_renewal_period: 60

Multi-Tier Rate Limiting:

# Free Tier
azure_apim:
  product_name: "Free-Tier"
  rate_limit_calls: 600          # 10 req/s
  rate_limit_renewal_period: 60

# Premium Tier
azure_apim:
  product_name: "Premium-Tier"
  rate_limit_calls: 120000       # 2000 req/s
  rate_limit_renewal_period: 60

Quota Policies (zusätzlich zu Rate Limits): Azure APIM unterstützt auch Quota Policies für längere Zeitfenster (nicht in GAL implementiert):

<quota calls="10000" renewal-period="86400" /> <!-- 10k calls per day -->

Hinweis: Azure APIM eignet sich besonders für API Monetization mit unterschiedlichen Subscription Tiers.

GCP API Gateway

GCP API Gateway implementiert Rate Limiting nicht nativ auf Gateway-Ebene. Stattdessen stehen alternative Ansätze zur Verfügung.

Rate Limiting Optionen: - Mechanismus: Cloud Endpoints Quotas (falls Cloud Endpoints aktiviert) - Alternativen: Backend Rate Limiting, Apigee (Enterprise API Management) - Hinweis: Keine native Gateway-Level Rate Limits in GCP API Gateway

Alternative: Cloud Endpoints Quotas:

swagger: "2.0"
info:
  title: "API with Quotas"
  version: "1.0.0"
x-google-management:
  metrics:
    - name: "api-requests"
      valueType: INT64
      metricKind: DELTA
  quota:
    limits:
      - name: "requests-per-minute-per-user"
        metric: api-requests
        unit: "1/min/{project}"
        values:
          STANDARD: 100

Backend Rate Limiting (Empfohlen):

# Deployment mit Backend-seitigem Rate Limiting
gcloud api-gateway api-configs create config-v1 \
  --api=my-api \
  --openapi-spec=openapi.yaml \
  --project=my-project \
  --backend-auth-service-account=backend@my-project.iam.gserviceaccount.com

# Backend implementiert Rate Limiting (z.B. mit Flask-Limiter, Express Rate Limit)

GCP API Gateway Besonderheiten: - ❌ Kein natives Gateway-Level Rate Limiting - ⚠️ Cloud Endpoints Quotas (nur mit Cloud Endpoints Integration) - ✅ Backend Rate Limiting (empfohlener Ansatz) - ✅ Apigee für Enterprise-Grade Rate Limiting - ✅ Cloud Armor für DDoS Protection

Alternative: Apigee (Enterprise): Für fortgeschrittenes Rate Limiting empfiehlt Google die Verwendung von Apigee:

<!-- Apigee Quota Policy -->
<Quota name="QuotaPolicy">
  <Allow count="100" countRef="verifyapikey.VerifyAPIKey.apiproduct.developer.quota.limit"/>
  <Interval ref="verifyapikey.VerifyAPIKey.apiproduct.developer.quota.interval">1</Interval>
  <TimeUnit ref="verifyapikey.VerifyAPIKey.apiproduct.developer.quota.timeunit">minute</TimeUnit>
</Quota>

Monitoring mit Cloud Monitoring:

# Rate Metrics überwachen
gcloud monitoring time-series list \
  --filter='metric.type="serviceruntime.googleapis.com/api/request_count"' \
  --project=my-project

Hinweis: Für Production-Grade Rate Limiting mit GCP empfiehlt sich die Verwendung von: 1. Backend Rate Limiting (einfachste Lösung) 2. Cloud Armor (für DDoS Protection) 3. Apigee (für Enterprise API Management mit umfassenden Rate Limiting Features)

AWS API Gateway

AWS API Gateway implementiert Rate Limiting über Usage Plans mit API Keys, getrennt von der OpenAPI-Konfiguration.

Usage Plans (Throttling & Quotas): - Mechanismus: Usage Plans mit burstLimit und rateLimit pro API Key - Throttling: Requests per Second + Burst Capacity (Stage-Level & Method-Level) - Quotas: Daily/Weekly/Monthly Request Limits - Hinweis: Rate Limiting wird NICHT in OpenAPI konfiguriert, sondern via AWS CLI/Console

Stage-Level Throttling:

# Standard Throttling Settings für alle Methods
aws apigateway update-stage \
  --rest-api-id abc123xyz \
  --stage-name prod \
  --patch-operations \
    op=replace,path=/throttle/burstLimit,value=1000 \
    op=replace,path=/throttle/rateLimit,value=500

Method-Level Throttling:

# Spezifische Limits für einzelne Methods
aws apigateway update-stage \
  --rest-api-id abc123xyz \
  --stage-name prod \
  --patch-operations \
    op=replace,path=/*/GET/throttle/burstLimit,value=2000 \
    op=replace,path=/*/GET/throttle/rateLimit,value=1000

Usage Plans mit Quotas:

# Free Tier Usage Plan
aws apigateway create-usage-plan \
  --name "FreeTier" \
  --throttle burstLimit=100,rateLimit=10 \
  --quota limit=10000,period=MONTH

# Premium Tier Usage Plan
aws apigateway create-usage-plan \
  --name "PremiumTier" \
  --throttle burstLimit=5000,rateLimit=1000 \
  --quota limit=1000000,period=MONTH

# API Key erstellen und zu Usage Plan hinzufügen
API_KEY_ID=$(aws apigateway create-api-key \
  --name "Customer-ABC" \
  --enabled \
  --query 'id' --output text)

aws apigateway create-usage-plan-key \
  --usage-plan-id <plan-id> \
  --key-id $API_KEY_ID \
  --key-type API_KEY

Testing:

# Request mit API Key
curl -H "x-api-key: <api-key-value>" \
  https://abc123.execute-api.us-east-1.amazonaws.com/prod/api/users

# Throttling Metriken überwachen
aws cloudwatch get-metric-statistics \
  --namespace AWS/ApiGateway \
  --metric-name Count \
  --dimensions Name=ApiName,Value=MyAPI \
  --start-time 2025-10-20T00:00:00Z \
  --end-time 2025-10-20T23:59:59Z \
  --period 300 \
  --statistics Sum

# 429 Errors (Too Many Requests) überwachen
aws cloudwatch get-metric-statistics \
  --namespace AWS/ApiGateway \
  --metric-name 4XXError \
  --dimensions Name=ApiName,Value=MyAPI \
  --start-time 2025-10-20T00:00:00Z \
  --end-time 2025-10-20T23:59:59Z \
  --period 300 \
  --statistics Sum

AWS API Gateway-spezifische Features: - ✅ Usage Plans mit Throttling + Quotas - ✅ Stage-Level + Method-Level Rate Limits - ✅ Per-API-Key Rate Limiting - ✅ Daily/Weekly/Monthly Quotas - ✅ CloudWatch Integration für Monitoring - ⚠️ Keine native OpenAPI-Konfiguration (nur AWS CLI/SDK) - ⚠️ API Keys erforderlich für Per-User Rate Limiting

Limitierungen: - ⚠️ Rate Limiting nicht in OpenAPI definierbar - ⚠️ Manuelle Konfiguration via AWS CLI/Console erforderlich - ⚠️ API Keys müssen separat verwaltet werden - ❌ Kein Header-basiertes oder JWT-basiertes Rate Limiting ohne Custom Authorizer

Multi-Tier Rate Limiting Beispiel:

# 1. Free Tier (10 req/s, 100 burst, 10k/Monat)
FREE_PLAN=$(aws apigateway create-usage-plan \
  --name "Free-Tier" \
  --throttle burstLimit=100,rateLimit=10 \
  --quota limit=10000,period=MONTH,offset=0 \
  --query 'id' --output text)

# 2. Basic Tier (100 req/s, 1000 burst, 100k/Monat)
BASIC_PLAN=$(aws apigateway create-usage-plan \
  --name "Basic-Tier" \
  --throttle burstLimit=1000,rateLimit=100 \
  --quota limit=100000,period=MONTH,offset=0 \
  --query 'id' --output text)

# 3. Premium Tier (1000 req/s, 5000 burst, unlimited)
PREMIUM_PLAN=$(aws apigateway create-usage-plan \
  --name "Premium-Tier" \
  --throttle burstLimit=5000,rateLimit=1000 \
  --query 'id' --output text)

# Usage Plans zu API Stage verknüpfen
aws apigateway update-usage-plan \
  --usage-plan-id $FREE_PLAN \
  --patch-operations \
    op=add,path=/apiStages,value=abc123:prod

# Customer API Key zu Plan hinzufügen
aws apigateway create-usage-plan-key \
  --usage-plan-id $FREE_PLAN \
  --key-id $API_KEY_ID \
  --key-type API_KEY

Hinweis: AWS API Gateway's Rate Limiting erfordert API Keys und Usage Plans. Für feingranulare Kontrolle (z.B. per User ID) muss ein Lambda Authorizer mit DynamoDB verwendet werden.

Best Practices

1. Burst-Dimensionierung

Setzen Sie burst auf das 2-3-fache von requests_per_second:

rate_limit:
  requests_per_second: 100
  burst: 200  # 2x für normale Spitzen
  # burst: 300  # 3x für höhere Variabilität

2. Gestaffelte Limits

Unterschiedliche Limits für verschiedene Zugriffsebenen:

# Free Tier
rate_limit:
  requests_per_second: 10

# Paid Tier
rate_limit:
  requests_per_second: 100

# Enterprise
rate_limit:
  requests_per_second: 1000

3. Aussagekräftige Fehlermeldungen

Geben Sie hilfreiche Fehlerantworten:

rate_limit:
  enabled: true
  requests_per_second: 100
  response_status: 429
  response_message: "Rate limit of 100 requests per second exceeded. Please retry after 1 second."

4. Monitoring

Überwachen Sie Rate Limiting Metriken: - Anzahl der gerateten Anfragen - Top-IPs/Keys die gelimitiert werden - Rate Limit Auslastung (aktuell/maximum)

5. Graceful Degradation

Verwenden Sie progressive Rate Limits:

# Warn bei 80%
rate_limit:
  requests_per_second: 100
  burst: 120  # Kleiner Burst für Warnungen

# Block bei 100%
rate_limit:
  requests_per_second: 100
  burst: 200  # Größerer Burst für harte Limits

Troubleshooting

Problem: Legitime Benutzer werden geblockt

Lösung: Erhöhen Sie den burst Wert:

rate_limit:
  requests_per_second: 100
  burst: 500  # Erhöht von 200

Problem: Rate Limits greifen nicht

Lösung: Überprüfen Sie: 1. enabled: true ist gesetzt 2. Provider-Konfiguration wurde deployed 3. Provider wurde neu gestartet (bei file-based configs)

Problem: Zu viele False Positives

Lösung: Wechseln Sie von IP zu Header/JWT-basiertem Rate Limiting:

rate_limit:
  key_type: header
  key_header: X-API-Key

Testing

Manuelles Testing mit curl

# Test Rate Limiting
for i in {1..150}; do
  curl -w "\n%{http_code}\n" http://localhost:10000/api/v1/test
  sleep 0.01
done

# Mit API Key
for i in {1..150}; do
  curl -H "X-API-Key: test123" \
       -w "\n%{http_code}\n" \
       http://localhost:10000/api/v1/test
done

Load Testing mit ab (Apache Bench)

# 1000 Requests, 10 gleichzeitige Connections
ab -n 1000 -c 10 http://localhost:10000/api/v1/test

# Mit Custom Header
ab -n 1000 -c 10 -H "X-API-Key: test123" \
   http://localhost:10000/api/v1/test

Migration von v1.0.0

In GAL v1.0.0 gab es kein natives Rate Limiting. Migrieren Sie bestehende Konfigurationen:

Vorher (v1.0.0 - manuell konfiguriert):

# Manuelles Rate Limiting Plugin (Kong)
plugins:
  - name: rate_limiting
    enabled: true
    config:
      requests_per_second: 100

Nachher (v1.1.0 - nativ):

# Native Rate Limiting Konfiguration
routes:
  - path_prefix: /api/v1
    rate_limit:
      enabled: true
      requests_per_second: 100
      burst: 200

Weiterführende Ressourcen

Provider-spezifische Dokumentation

Zusammenfassung

Rate Limiting ist ein kritisches Feature für Production-APIs. GAL v1.1.0 bietet:

Einheitliche Konfiguration für alle Provider ✅ Flexible Key-Strategien (IP, Header, JWT) ✅ Burst-Handling für Traffic-Spitzen ✅ Custom Error ResponsesPer-Route Konfiguration

Beginnen Sie mit konservativen Limits und passen Sie basierend auf Monitoring-Daten an.