API gateway security is the critical first line of defense for LLM production services. This comprehensive guide covers distributed rate limiting implementation, JWT and OAuth 2.0 authentication patterns, request validation and sanitization, circuit breaker configurations, and monitoring strategies specifically designed for high-throughput LLM inference workloads. The guide provides concrete configuration examples for popular gateways including Kong, AWS API Gateway, and Envoy, along with implementation patterns that address the unique challenges of token-based LLM billing and variable latency characteristics.
Distributed Rate Limiting Architecture
LLM APIs present unique rate limiting challenges due to variable token consumption per request and the need to enforce both request-level and token-level quotas simultaneously. Traditional fixed-window rate limiters are insufficient because a single request can consume thousands of tokens while another consumes only hundreds. Effective rate limiting requires tracking token consumption across time windows and enforcing quotas at multiple granularities.
Token-Aware Rate Limiting Implementation
Implement token-aware rate limiting by extracting token counts from LLM provider responses and maintaining sliding window counters in Redis. Use Lua scripts for atomic operations to prevent race conditions. Configure separate limits for input tokens, output tokens, and total tokens per time window. For example, a typical configuration might allow 100,000 input tokens per minute and 50,000 output tokens per minute per API key, with burst allowances of 2x the base limits. The Redis Rate Limiting Pattern provides the foundational algorithms for implementing sliding window log and sliding window counter approaches with atomic operations.
-- Redis Lua script for token-aware sliding window rate limiting
local key = KEYS[1]
local limit = tonumber(ARGV[1])
local window = tonumber(ARGV[2])
local tokens = tonumber(ARGV[3])
local now = tonumber(ARGV[4])
redis.call('ZREMRANGEBYSCORE', key, 0, now - window)
local current = redis.call('ZCARD', key)
if current + tokens > limit then
return {0, current}
end
redis.call('ZADD', key, now, now .. '-' .. math.random())
redis.call('EXPIRE', key, window / 1000)
return {1, current + tokens}
Deploy this pattern across all API gateway instances with a shared Redis cluster. Configure key namespaces by API key, user ID, and endpoint to enable granular quota enforcement. Set TTL on rate limit keys to match the longest window to prevent memory growth.
Multi-Tier Rate Limit Configuration
Establish rate limits at multiple tiers: global platform limits to protect infrastructure, per-customer limits for fair usage, per-endpoint limits for expensive operations like model fine-tuning or batch inference, and per-model limits for GPU resource allocation. Implement priority queuing for premium customers during congestion using weighted fair queuing algorithms. The Kong Rate Limiting Plugin Documentation details enterprise-grade configurations including Redis-backed clustering, custom key definitions, and response headers for client-side rate limit awareness.
JWT and OAuth 2.0 Authentication Patterns
LLM production services require robust authentication that supports both human users and automated service-to-service communication. Implement a dual authentication strategy using JWT for stateless API access and OAuth 2.0 for delegated authorization flows.
JWT Token Structure for LLM Services
Design JWT payloads with LLM-specific claims including model_access (array of permitted model IDs), token_quota (monthly token allocation), rate_limit_tier (priority level for queuing), and features (enabled capabilities like streaming, function calling, or fine-tuning). Use short-lived access tokens (15-30 minutes) with long-lived refresh tokens (30-90 days) stored securely in HTTP-only cookies or secure enclaves. Implement JWKS endpoint rotation every 24 hours with overlap periods for zero-downtime key rotation. The Auth0 JWT Best Practices guide provides comprehensive token security recommendations including algorithm selection, claim validation, and storage patterns.
OAuth 2.0 for Delegated Access
Implement OAuth 2.0 Authorization Code flow with PKCE for web and mobile applications accessing LLM APIs on behalf of users. Define scopes aligned with LLM capabilities: models:read for listing available models, inference:create for generating completions, embeddings:create for vector operations, fine-tuning:manage for training jobs, and usage:read for billing and quota information. Use consent screens that clearly explain token consumption implications. Configure token introspection endpoints for real-time validation and revocation. The OAuth 2.0 RFC 6749 and PKCE RFC 7636 specifications provide the authoritative protocol definitions.
Request Validation and Sanitization
LLM APIs are vulnerable to prompt injection, oversized payloads, and malicious input patterns. Implement multi-layer validation at the gateway level before requests reach inference services.
Payload Size and Structure Validation
Enforce maximum request body sizes appropriate for each endpoint (e.g., 32KB for chat completions, 10MB for fine-tuning dataset uploads). Validate JSON schema compliance using compiled validators for minimal latency overhead. Reject requests with unexpected fields, deeply nested structures exceeding depth limits, or arrays exceeding maximum length. Implement streaming request validation for server-sent events (SSE) endpoints to prevent resource exhaustion from incomplete streams.
Prompt Injection Detection
Deploy pattern-based detection at the gateway for known injection signatures including instruction override attempts, role manipulation, and context boundary violations. Use compiled regex patterns for common attack vectors while acknowledging that pattern matching alone is insufficient. Integrate with dedicated prompt guard services for semantic analysis of suspicious inputs. Log all blocked requests with full context for security analysis and model improvement. The OWASP LLM Security Top 10 provides the authoritative threat taxonomy for LLM-specific vulnerabilities including prompt injection (LLM01), insecure output handling (LLM02), and training data poisoning (LLM03).
Circuit Breaker and Resilience Patterns
LLM inference services exhibit variable latency and can experience cascading failures under load. Implement circuit breakers at the gateway to prevent upstream overload and provide graceful degradation.
Adaptive Circuit Breaker Configuration
Configure circuit breakers with LLM-aware thresholds: open circuit after 5 consecutive 5xx errors or 50% error rate over 30 seconds, half-open state with 3 probe requests before closing, and 60-second reset timeout. Use adaptive timeout configuration based on model-specific latency percentiles (p99 + 20% buffer). Implement bulkhead patterns to isolate different model endpoints so failures in one model don't affect others. The Netflix Hystrix Patterns and Envoy Circuit Breaker Documentation provide proven implementations for high-throughput services.
Graceful Degradation Strategies
During circuit breaker open state, return cached responses for idempotent requests, serve fallback responses from smaller/faster models, or queue requests with estimated wait times. Implement priority-based request shedding that preserves premium customer traffic during overload. Use request hedging for non-streaming endpoints by sending duplicate requests to multiple instances and returning the first successful response.
Monitoring and Observability
Comprehensive observability is essential for detecting abuse, optimizing performance, and debugging production issues in LLM deployments.
Key Metrics Collection
Collect metrics at multiple levels: gateway-level (request rate, latency percentiles, error rates by status code), authentication-level (token validation success/failure, quota consumption by tier), model-level (tokens per request, cache hit rates, queue depths), and business-level (active customers, revenue per token, cost per inference). Emit metrics in Prometheus format with consistent label cardinality. The Prometheus Metrics Best Practices guide ensures metrics are queryable and cost-effective at scale.
Distributed Tracing Implementation
Implement OpenTelemetry tracing across the entire request path from gateway through authentication, rate limiting, routing, and inference services. Include span attributes for model ID, token counts, cache hit/miss, and queue wait time. Configure sampling rates appropriate for traffic volume (1-10% for high-volume endpoints). Correlate traces with logging using trace IDs for end-to-end debugging. The OpenTelemetry Semantic Conventions provide standardized attribute names for LLM workloads.
Alerting Strategy
Configure tiered alerting: critical alerts for platform-wide error rates exceeding 1%, latency p99 exceeding 30 seconds, or authentication failure rates above 5%; warning alerts for individual model error rates, quota exhaustion for top customers, or circuit breaker state changes; informational alerts for new model deployments, configuration changes, or capacity threshold crossings. Use notification routing that escalates based on severity and time of day. Implement runbook links in all alerts for rapid incident response.
Configuration Examples
Kong Gateway Configuration
# kong.yml - LLM API Gateway Configuration
services:
- name: llm-inference
url: http://inference-service:8000
routes:
- name: chat-completions
paths: ["/v1/chat/completions"]
methods: ["POST"]
plugins:
- name: rate-limiting
config:
minute: 1000
hour: 10000
policy: redis
redis_host: redis-cluster
fault_tolerant: true
hide_client_headers: false
- name: jwt
config:
uri_param_names: ["jwt"]
header_names: ["Authorization"]
claims_to_verify: ["exp", "model_access"]
maximum_expiration: 3600
- name: request-transformer
config:
add:
headers: ["X-Request-ID:$(uuid)"]
- name: correlation-id
config:
header_name: "X-Request-ID"
generator: uuid
- name: prometheus
AWS API Gateway Configuration
{
"restApiId": "llm-production-api",
"stageName": "prod",
"methodSettings": [
{
"resourcePath": "/v1/chat/completions",
"httpMethod": "POST",
"throttlingRateLimit": 1000,
"throttlingBurstLimit": 2000,
"cachingEnabled": false,
"metricsEnabled": true,
"loggingLevel": "INFO",
"dataTraceEnabled": true
}
],
"authorizers": {
"jwtAuthorizer": {
"type": "JWT",
"identitySource": "$request.header.Authorization",
"jwtConfiguration": {
"issuer": "https://auth.yourcompany.com",
"audience": ["llm-api"],
"claims": {
"model_access": "required",
"token_quota": "required"
}
}
}
}
}
Envoy Proxy Configuration
# envoy.yaml - LLM Service Mesh Configuration
static_resources:
listeners:
- name: llm_gateway_listener
address:
socket_address:
address: 0.0.0.0
port_value: 8443
filter_chains:
- filter_chain_match:
transport_protocol: "tls"
filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: llm_gateway
route_config:
name: llm_routes
virtual_hosts:
- name: llm_service
domains: ["llm-api.yourcompany.com"]
routes:
- match:
prefix: "/v1/"
route:
cluster: llm_inference_cluster
retry_policy:
retry_on: "5xx,reset,connect-failure"
num_retries: 3
per_try_timeout: "10s"
cors:
allow_origin_string_match:
- exact: "https://app.yourcompany.com"
allow_methods: "GET,POST,OPTIONS"
allow_headers: "authorization,content-type,x-request-id"
max_age: "86400"
http_filters:
- name: envoy.filters.http.jwt_authn
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication
providers:
llm_jwt_provider:
issuer: "https://auth.yourcompany.com"
audiences: ["llm-api"]
remote_jwks:
http_uri:
uri: "https://auth.yourcompany.com/.well-known/jwks.json"
cluster: auth_jwks_cluster
timeout: "5s"
cache_duration: "300s"
claim_to_headers:
model_access: "x-model-access"
token_quota: "x-token-quota"
- name: envoy.filters.http.local_ratelimit
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.local_ratelimit.v3.LocalRateLimit
stat_prefix: llm_rate_limit
token_bucket:
max_tokens: 10000
tokens_per_fill: 1000
fill_interval: "60s"
filter_enabled:
runtime_key: "rate_limit_enabled"
default_value:
numerator: 100
denominator: 100
- name: envoy.filters.http.router
Implementation Checklist
Use this checklist to validate your gateway implementation before production deployment:
- Rate Limiting: Token-aware sliding window implemented with Redis cluster; multi-tier limits configured (global, customer, endpoint, model); priority queuing for premium tiers; burst handling with 2x allowance; response headers include
X-RateLimit-Limit,X-RateLimit-Remaining,X-RateLimit-Reset - Authentication: JWT validation with JWKS rotation; OAuth 2.0 with PKCE for delegated access; scopes aligned with LLM capabilities; token introspection endpoint; refresh token rotation with revocation
- Request Validation: Maximum payload sizes enforced; JSON schema validation compiled; prompt injection pattern detection; streaming request validation; rejected request logging with full context
- Circuit Breaking: Adaptive thresholds based on model latency percentiles; bulkhead isolation per model; graceful degradation with cached/fallback responses; request hedging for non-streaming endpoints
- Observability: Prometheus metrics with consistent labels; OpenTelemetry distributed tracing; tiered alerting with runbook links; business metrics correlated with technical metrics; log correlation via trace IDs
Conclusion
Secure API gateway implementation for LLM production services requires addressing the unique characteristics of token-based billing, variable latency, and prompt injection threats. By implementing token-aware rate limiting, robust JWT/OAuth authentication, multi-layer request validation, adaptive circuit breaking, and comprehensive observability, organizations can build resilient LLM APIs that protect both infrastructure and customers. The configuration examples provided for Kong, AWS API Gateway, and Envoy serve as starting points that should be adapted to specific infrastructure, compliance requirements, and traffic patterns.
Sources
- Redis Rate Limiting Patterns: https://redis.io/docs/latest/develop/use-cases/rate-limiting/
- Kong Rate Limiting Plugin: https://docs.konghq.com/hub/kong-inc/rate-limiting/
- Auth0 JWT Best Practices: https://auth0.com/blog/ten-things-you-should-know-about-tokens-and-cookies/
- OAuth 2.0 RFC 6749: https://datatracker.ietf.org/doc/html/rfc6749
- PKCE RFC 7636: https://datatracker.ietf.org/doc/html/rfc7636
- OWASP LLM Security Top 10: https://owasp.org/www-project-llm-security/
- Netflix Hystrix Patterns: https://github.com/Netflix/Hystrix/wiki
- Envoy Circuit Breaking: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/circuit_breaking
- Prometheus Metrics Best Practices: https://prometheus.io/docs/practices/naming/
- OpenTelemetry Semantic Conventions: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/README.md
- Related: Production LLM Deployment: 6 Essential Steps for 2026 Success