api-gateway-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Gateway Patterns
API网关模式
A comprehensive skill for implementing production-grade API gateways using Kong and industry best practices. This skill covers advanced routing, authentication, rate limiting, load balancing, traffic management, and observability patterns for microservices architectures.
本指南全面介绍了如何使用Kong及行业最佳实践实现生产级API网关,涵盖微服务架构中的高级路由、认证、限流、负载均衡、流量管理与可观测性模式。
When to Use This Skill
适用场景
Use this skill when:
- Implementing an API gateway for microservices architectures
- Managing traffic routing, load balancing, and service discovery
- Implementing authentication and authorization at the gateway level
- Enforcing rate limiting, quotas, and traffic policies
- Adding observability, logging, and monitoring to API traffic
- Implementing request/response transformation and caching
- Managing API versioning and deprecation strategies
- Setting up circuit breakers and resilience patterns
- Configuring multi-environment API deployments
- Implementing API security policies (CORS, CSRF, WAF)
- Building developer portals and API documentation
- Managing API lifecycle from development to production
在以下场景中使用本指南:
- 为微服务架构实现API网关
- 管理流量路由、负载均衡与服务发现
- 在网关层面实现认证与授权
- 实施限流、配额与流量策略
- 为API流量添加可观测性、日志与监控
- 实现请求/响应转换与缓存
- 管理API版本控制与废弃策略
- 配置断路器与弹性模式
- 设置多环境API部署
- 实施API安全策略(CORS、CSRF、WAF)
- 构建开发者门户与API文档
- 管理从开发到生产的API生命周期
Core Concepts
核心概念
API Gateway Architecture
API网关架构
An API gateway acts as a single entry point for client applications, routing requests to appropriate backend services while providing cross-cutting concerns:
- Reverse Proxy: Routes client requests to backend services
- API Composition: Aggregates multiple service calls into single responses
- Protocol Translation: Converts between protocols (HTTP, gRPC, WebSocket)
- Cross-Cutting Concerns: Authentication, logging, rate limiting, caching
- Traffic Management: Load balancing, circuit breaking, retries
- Security: SSL termination, API key validation, OAuth2 flows
API网关作为客户端应用的单一入口点,将请求路由至合适的后端服务,同时提供横切关注点支持:
- 反向代理:将客户端请求路由至后端服务
- API组合:将多个服务调用聚合为单一响应
- 协议转换:在不同协议间转换(HTTP、gRPC、WebSocket)
- 横切关注点:认证、日志、限流、缓存
- 流量管理:负载均衡、断路、重试
- 安全:SSL终止、API密钥验证、OAuth2流程
Key Gateway Components
网关核心组件
- Services: Upstream APIs that the gateway proxies to
- Routes: Request matching rules that determine service routing
- Upstreams: Load balancer configurations for service instances
- Plugins: Extensible middleware for features (auth, logging, etc.)
- Consumers: API clients with authentication credentials
- Certificates: SSL/TLS certificates for secure communication
- SNIs: Server Name Indication for multi-domain SSL
- Services:网关代理的上游API
- Routes:决定服务路由的请求匹配规则
- Upstreams:服务实例的负载均衡配置
- Plugins:扩展功能的可插拔中间件(认证、日志等)
- Consumers:带有认证凭证的API客户端
- Certificates:用于安全通信的SSL/TLS证书
- SNIs:多域名SSL的服务器名称指示
Kong Gateway Fundamentals
Kong网关基础
Kong is a cloud-native, platform-agnostic, scalable API gateway:
Architecture:
- Control Plane: Admin API for configuration management
- Data Plane: Proxy layer handling runtime traffic
- Database: PostgreSQL or Cassandra for config storage (or DB-less mode)
- Plugin System: Lua-based extensibility for custom logic
Core Entities:
Service (upstream API)
└── Routes (request matching)
└── Plugins (features/policies)
Upstream (load balancer)
└── Targets (service instances)
Consumer (API client)
└── Credentials (auth keys/tokens)
└── Plugins (consumer-specific policies)Kong是云原生、平台无关、可扩展的API网关:
架构:
- 控制平面:用于配置管理的Admin API
- 数据平面:处理运行时流量的代理层
- 数据库:用于配置存储的PostgreSQL或Cassandra(或无DB模式)
- 插件系统:基于Lua的可扩展自定义逻辑
核心实体:
Service (上游API)
└── Routes (请求匹配规则)
└── Plugins (功能/策略)
Upstream (负载均衡器)
└── Targets (服务实例)
Consumer (API客户端)
└── Credentials (认证密钥/令牌)
└── Plugins (消费者专属策略)Routing Patterns
路由模式
Pattern 1: Path-Based Routing
模式1:基于路径的路由
Route requests based on URL paths to different backend services.
Use Case: Microservices with distinct URL prefixes (e.g., /users, /orders, /products)
Configuration:
yaml
undefined根据URL路径将请求路由至不同后端服务。
适用场景: 具有不同URL前缀的微服务(如/users、/orders、/products)
配置:
yaml
undefinedUsers Service
用户服务
service:
name: users-service
url: http://users-api:8001
routes:
- name: users-route
paths:
- /users
- /api/users strip_path: true methods:
- GET
- POST
- PUT
- DELETE
service:
name: users-service
url: http://users-api:8001
routes:
- name: users-route
paths:
- /users
- /api/users strip_path: true methods:
- GET
- POST
- PUT
- DELETE
Orders Service
订单服务
service:
name: orders-service
url: http://orders-api:8002
routes:
- name: orders-route
paths:
- /orders
- /api/orders strip_path: true
**Key Options:**
- `strip_path: true` - Removes matched path before proxying (e.g., /users/123 → /123)
- `strip_path: false` - Preserves full path (e.g., /users/123 → /users/123)
- `preserve_host: true` - Forwards original Host header to upstreamservice:
name: orders-service
url: http://orders-api:8002
routes:
- name: orders-route
paths:
- /orders
- /api/orders strip_path: true
**关键配置项:**
- `strip_path: true`:代理前移除匹配的路径(如/users/123 → /123)
- `strip_path: false`:保留完整路径(如/users/123 → /users/123)
- `preserve_host: true`:将原始Host头转发至上游服务Pattern 2: Header-Based Routing
模式2:基于Header的路由
Route based on HTTP headers for A/B testing, canary deployments, or API versioning.
Use Case: Gradual rollout of new API versions or feature flags
Configuration:
yaml
undefined根据HTTP头信息路由,用于A/B测试、金丝雀发布或API版本控制。
适用场景: 逐步推出新版本或功能标记
配置:
yaml
undefinedV1 Service (stable)
V1版本(稳定版)
service:
name: api-v1
url: http://api-v1:8001
routes:
- name: api-v1-route
paths:
- /api
headers:
X-API-Version:
- "1"
- "1.0"
- /api
headers:
X-API-Version:
service:
name: api-v1
url: http://api-v1:8001
V2 Service (beta)
V2版本(测试版)
service:
name: api-v2
url: http://api-v2:8002
routes:
- name: api-v2-route
paths:
- /api
headers:
X-API-Version:
- "2"
- "2.0"
- /api
headers:
X-API-Version:
service:
name: api-v2
url: http://api-v2:8002
Default route (no version header)
根据Header路由
routes:
- name: api-default
paths:
- /api
Routes to V1 by default
**Advanced Header Routing:**
```yamlroutes:
- name: api-v1-route
paths:
- /api
headers:
X-API-Version:
- "1"
- "1.0" service: api-v1
- /api
headers:
X-API-Version:
Mobile vs Web routing
V2路由
routes:
-
name: mobile-api headers: User-Agent: - ".Mobile." - ".Android." - ".iOS." service: mobile-optimized-api
-
name: web-api headers: User-Agent: - ".Chrome." - ".Firefox." - ".Safari." service: web-api
undefinedroutes:
- name: api-v2-route
paths:
- /api
headers:
X-API-Version:
- "2"
- "2.0" service: api-v2
- /api
headers:
X-API-Version:
Pattern 3: Method-Based Routing
默认路由(无版本Header时指向V1)
Route different HTTP methods to specialized services.
Use Case: CQRS pattern - separate read and write services
Configuration:
yaml
undefinedroutes:
- name: api-default
paths:
- /api service: api-v1
**高级Header路由:**
```yamlRead Service (queries)
移动端与Web端路由
service:
name: query-service
url: http://read-api:8001
routes:
- name: read-operations
paths:
- /api/resources methods:
- GET
- HEAD
- OPTIONS
routes:
-
name: mobile-api headers: User-Agent: - ".Mobile." - ".Android." - ".iOS." service: mobile-optimized-api
-
name: web-api headers: User-Agent: - ".Chrome." - ".Firefox." - ".Safari." service: web-api
undefinedWrite Service (commands)
模式3:基于方法的路由
service:
name: command-service
url: http://write-api:8002
routes:
- name: write-operations
paths:
- /api/resources methods:
- POST
- PUT
- PATCH
- DELETE
undefined将不同HTTP方法路由至专用服务。
适用场景: CQRS模式 - 分离读、写服务
配置:
yaml
undefinedPattern 4: Host-Based Routing
读服务(查询)
Route based on the requested hostname for multi-tenant applications.
Use Case: Different subdomains for different customers or environments
Configuration:
yaml
undefinedservice:
name: query-service
url: http://read-api:8001
routes:
- name: read-operations
paths:
- /api/resources methods:
- GET
- HEAD
- OPTIONS service: query-service
Tenant A
写服务(命令)
service:
name: tenant-a-api
url: http://tenant-a:8001
routes:
- name: tenant-a-route
hosts:
- tenant-a.api.example.com
- a.api.example.com
service:
name: command-service
url: http://write-api:8002
routes:
- name: write-operations
paths:
- /api/resources methods:
- POST
- PUT
- PATCH
- DELETE service: command-service
undefinedTenant B
模式4:基于主机的路由
service:
name: tenant-b-api
url: http://tenant-b:8002
routes:
- name: tenant-b-route
hosts:
- tenant-b.api.example.com
- b.api.example.com
根据请求的主机名路由,用于多租户应用。
适用场景: 不同子域名对应不同客户或环境
配置:
yaml
undefinedWildcard for dynamic tenants
租户A
routes:
- name: dynamic-tenant
hosts:
- "*.api.example.com" service: multi-tenant-api
undefinedservice:
name: tenant-a-api
url: http://tenant-a:8001
routes:
- name: tenant-a-route
hosts:
- tenant-a.api.example.com
- a.api.example.com service: tenant-a-api
Pattern 5: Weighted Routing (Canary Deployments)
租户B
Gradually shift traffic between service versions.
Implementation:
yaml
undefinedservice:
name: tenant-b-api
url: http://tenant-b:8002
routes:
- name: tenant-b-route
hosts:
- tenant-b.api.example.com
- b.api.example.com service: tenant-b-api
Create two upstreams with weight distribution
动态租户路由
upstream:
name: api-upstream
algorithm: round-robin
targets:
-
target: api-v1:8001 weight: 90 # 90% traffic to stable version
-
target: api-v2:8002 weight: 10 # 10% traffic to canary version
service:
name: api-service
host: api-upstream # Points to upstream
routes:
- name: api-route
paths:
- /api
**Gradual Rollout Strategy:**
1. Start: 100% v1, 0% v2
2. Phase 1: 90% v1, 10% v2 (monitor metrics)
3. Phase 2: 75% v1, 25% v2
4. Phase 3: 50% v1, 50% v2
5. Phase 4: 25% v1, 75% v2
6. Complete: 0% v1, 100% v2routes:
- name: dynamic-tenant
hosts:
- "*.api.example.com" service: multi-tenant-api
undefinedRate Limiting Patterns
模式5:加权路由(金丝雀发布)
Pattern 1: Global Rate Limiting
—
Protect your entire API from abuse with global limits.
Use Case: Prevent DDoS attacks and ensure fair usage
Configuration:
yaml
plugins:
- name: rate-limiting
config:
minute: 1000
hour: 10000
day: 100000
policy: local # or 'cluster', 'redis'
fault_tolerant: true
hide_client_headers: false
limit_by: ip # or 'consumer', 'credential', 'service'Policy Options:
- : In-memory, single node (not cluster-safe)
local - : Shared across Kong nodes via database
cluster - : High-performance distributed limiting via Redis
redis
逐步在服务版本间切换流量。
实现方式:
yaml
undefinedPattern 2: Consumer-Specific Rate Limiting
创建两个上游环境,按权重分配流量
Different limits for different API consumers (tiers).
Use Case: Freemium model with tiered pricing
Configuration:
yaml
undefinedupstream:
name: api-upstream
algorithm: round-robin
targets:
-
target: api-v1:8001 weight: 90 # 90%流量到稳定版本
-
target: api-v2:8002 weight: 10 # 10%流量到新版本
service:
name: api-service
host: api-upstream # 指向包含两个版本的上游
Free tier consumer
灰度发布策略:
consumer:
username: free-user-123
plugins:
- name: rate-limiting consumer: free-user-123 config: minute: 10 hour: 100 day: 1000
- 初始:100% v1, 0% v2
- 阶段1:90% v1, 10% v2(监控指标)
- 阶段2:75% v1, 25% v2
- 阶段3:50% v1, 50% v2
- 阶段4:25% v1, 75% v2
- 完成:0% v1, 100% v2
undefinedPremium tier consumer
限流模式
—
模式1:全局限流
consumer:
username: premium-user-456
plugins:
- name: rate-limiting consumer: premium-user-456 config: minute: 1000 hour: 10000 day: 100000
为整个API设置全局限流,防止滥用。
适用场景: 防止DDoS攻击,确保公平使用
配置:
yaml
plugins:
- name: rate-limiting
config:
minute: 1000
hour: 10000
day: 100000
policy: local # 或'cluster'、'redis'
fault_tolerant: true
hide_client_headers: false
limit_by: ip # 或'consumer'、'credential'、'service'策略选项:
- :内存存储,单节点(不支持集群)
local - :通过数据库在Kong节点间共享
cluster - :通过Redis实现高性能分布式限流
redis
Enterprise tier (unlimited)
模式2:消费者专属限流
consumer:
username: enterprise-user-789
为不同API消费者设置不同限流规则(分级)。
适用场景: 免费增值模式,分级定价
配置:
yaml
undefinedNo rate limiting plugin for enterprise
免费版消费者
undefinedconsumer:
username: free-user-123
plugins:
- name: rate-limiting consumer: free-user-123 config: minute: 10 hour: 100 day: 1000
Pattern 3: Endpoint-Specific Rate Limiting
付费版消费者
Different limits for different API endpoints.
Use Case: Protect expensive operations while allowing higher rates for cheap ones
Configuration:
yaml
undefinedconsumer:
username: premium-user-456
plugins:
- name: rate-limiting consumer: premium-user-456 config: minute: 1000 hour: 10000 day: 100000
Expensive search endpoint - strict limits
企业版(无限制)
routes:
- name: search-route
paths:
- /api/search
plugins:
- name: rate-limiting route: search-route config: minute: 10 hour: 100
consumer:
username: enterprise-user-789
Regular CRUD endpoints - moderate limits
不为该消费者添加限流插件
routes:
- name: users-route
paths:
- /api/users
plugins:
- name: rate-limiting route: users-route config: minute: 100 hour: 1000
undefinedHealth check - no limits
模式3:端点专属限流
routes:
- name: health-route
paths:
- /health
为不同API端点设置不同限流规则。
适用场景: 保护高开销操作,同时允许低开销操作的高并发
配置:
yaml
undefinedNo rate limiting plugin
高开销搜索端点 - 严格限流
undefinedroutes:
- name: search-route
paths:
- /api/search
plugins:
- name: rate-limiting route: search-route config: minute: 10 hour: 100
Pattern 4: Sliding Window Rate Limiting
常规CRUD端点 - 中等限流
More accurate rate limiting using sliding windows.
Use Case: Prevent burst attacks that exploit fixed window boundaries
Configuration:
yaml
plugins:
- name: rate-limiting-advanced # Kong Enterprise
config:
limit:
- 100 # Limit value
window_size:
- 60 # Window in seconds
window_type: sliding
retry_after_jitter_max: 1
sync_rate: 0.5
namespace: my-api
strategy: redis
redis:
host: redis
port: 6379
database: 0Sliding vs Fixed Windows:
- Fixed: 100 requests per minute resets at :00 seconds
- Sliding: 100 requests in any 60-second window
- Sliding prevents burst exploitation at window boundaries
routes:
- name: users-route
paths:
- /api/users
plugins:
- name: rate-limiting route: users-route config: minute: 100 hour: 1000
Pattern 5: Quota Management
健康检查 - 无限制
Long-term usage quotas (monthly, yearly).
Use Case: Enforce subscription limits based on plan
Configuration:
yaml
plugins:
- name: request-termination
enabled: false # Will be enabled when quota exceeded
plugins:
- name: acme # Custom quota tracking plugin
config:
quota:
month: 1000000
reset_on: first_day
consumer_groups:
- name: starter
quota: 10000
- name: professional
quota: 100000
- name: enterprise
quota: 1000000routes:
- name: health-route
paths:
- /health
Authentication Patterns
不为该路由添加限流插件
Pattern 1: API Key Authentication
—
Simple API key validation for basic security.
Use Case: Internal APIs, development environments, simple integrations
Configuration:
yaml
undefinedundefinedEnable key-auth plugin
模式4:滑动窗口限流
plugins:
- name: key-auth config: key_names: - apikey - api-key - X-API-Key hide_credentials: true anonymous: null # Require authentication run_on_preflight: false
使用滑动窗口实现更精确的限流。
适用场景: 防止利用固定窗口边界的突发攻击
配置:
yaml
plugins:
- name: rate-limiting-advanced # Kong企业版
config:
limit:
- 100 # 限流值
window_size:
- 60 # 窗口大小(秒)
window_type: sliding
retry_after_jitter_max: 1
sync_rate: 0.5
namespace: my-api
strategy: redis
redis:
host: redis
port: 6379
database: 0滑动窗口vs固定窗口:
- 固定窗口:每分钟100次请求,在整点重置
- 滑动窗口:任意60秒内最多100次请求
- 滑动窗口可防止在窗口边界的突发流量绕过限制
Create consumer with API key
模式5:配额管理
consumers:
- username: mobile-app custom_id: app-001
长期使用配额(月度、年度)。
适用场景: 根据订阅计划执行使用限制
配置:
yaml
plugins:
- name: request-termination
enabled: false # 配额超限时启用
plugins:
- name: acme # 自定义配额跟踪插件
config:
quota:
month: 1000000
reset_on: first_day
consumer_groups:
- name: starter
quota: 10000
- name: professional
quota: 100000
- name: enterprise
quota: 1000000Add key credential
认证模式
—
模式1:API密钥认证
keyauth_credentials:
- consumer: mobile-app key: sk_live_abc123def456ghi789
**Usage:**
```bash
curl -H "apikey: sk_live_abc123def456ghi789" \
https://api.example.com/usersBest Practices:
- Use cryptographically random keys (min 32 chars)
- Rotate keys periodically
- Different keys for different environments
- Never commit keys to version control
- Use HTTPS to protect keys in transit
简单的API密钥验证,提供基础安全。
适用场景: 内部API、开发环境、简单集成
配置:
yaml
undefinedPattern 2: JWT Authentication
启用key-auth插件
Token-based authentication with payload verification.
Use Case: Modern SPAs, mobile apps, microservices
Configuration:
yaml
plugins:
- name: jwt
config:
uri_param_names:
- jwt
cookie_names:
- jwt_token
header_names:
- Authorization
claims_to_verify:
- exp
- nbf
key_claim_name: iss
secret_is_base64: false
anonymous: null
run_on_preflight: false
maximum_expiration: 3600 # 1 hour maxplugins:
- name: key-auth config: key_names: - apikey - api-key - X-API-Key hide_credentials: true anonymous: null # 强制要求认证 run_on_preflight: false
Create consumer with JWT credential
创建消费者与API密钥
consumers:
- username: web-app
jwt_secrets:
- consumer: web-app key: myapp-issuer algorithm: HS256 secret: my-secret-key-change-in-production
**RS256 (Asymmetric) Configuration:**
```yaml
jwt_secrets:
- consumer: mobile-app
key: mobile-issuer
algorithm: RS256
rsa_public_key: |
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----Token Format:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJteWFwcC1pc3N1ZXIiLCJzdWIiOiJ1c2VyMTIzIiwiZXhwIjoxNjQwOTk1MjAwfQ.signatureconsumers:
- username: mobile-app custom_id: app-001
Pattern 3: OAuth 2.0 Authorization
添加密钥凭证
Full OAuth 2.0 flows for third-party integrations.
Use Case: Public APIs, third-party developer access
Supported Flows:
- Authorization Code Flow
- Client Credentials Flow
- Implicit Flow (deprecated)
- Resource Owner Password Flow
Configuration:
yaml
plugins:
- name: oauth2
config:
scopes:
- read
- write
- admin
mandatory_scope: true
token_expiration: 3600
enable_authorization_code: true
enable_client_credentials: true
enable_implicit_grant: false
enable_password_grant: false
hide_credentials: true
accept_http_if_already_terminated: false
refresh_token_ttl: 1209600 # 14 dayskeyauth_credentials:
- consumer: mobile-app key: sk_live_abc123def456ghi789
**使用方式:**
```bash
curl -H "apikey: sk_live_abc123def456ghi789" \
https://api.example.com/users最佳实践:
- 使用加密随机密钥(至少32位)
- 定期轮换密钥
- 为不同环境使用不同密钥
- 切勿将密钥提交至版本控制
- 使用HTTPS保护传输中的密钥
Create OAuth application
模式2:JWT认证
oauth2_credentials:
- consumer: third-party-app name: "Partner Integration" client_id: client_abc123 client_secret: secret_xyz789 redirect_uris:
**Authorization Code Flow:**
```bash基于令牌的认证,支持载荷验证。
适用场景: 现代SPA、移动应用、微服务
配置:
yaml
plugins:
- name: jwt
config:
uri_param_names:
- jwt
cookie_names:
- jwt_token
header_names:
- Authorization
claims_to_verify:
- exp
- nbf
key_claim_name: iss
secret_is_base64: false
anonymous: null
run_on_preflight: false
maximum_expiration: 3600 # 最长1小时1. Get authorization code
创建消费者与JWT凭证
GET /oauth2/authorize?
response_type=code&
client_id=client_abc123&
redirect_uri=https://partner.com/callback&
scope=read write
consumers:
- username: web-app
jwt_secrets:
- consumer: web-app key: myapp-issuer algorithm: HS256 secret: my-secret-key-change-in-production
**RS256(非对称)配置:**
```yaml
jwt_secrets:
- consumer: mobile-app
key: mobile-issuer
algorithm: RS256
rsa_public_key: |
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
-----END PUBLIC KEY-----令牌格式:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJteWFwcC1pc3N1ZXIiLCJzdWIiOiJ1c2VyMTIzIiwiZXhwIjoxNjQwOTk1MjAwfQ.signature2. Exchange code for token
模式3:OAuth 2.0授权
POST /oauth2/token
grant_type=authorization_code&
client_id=client_abc123&
client_secret=secret_xyz789&
code=AUTH_CODE&
redirect_uri=https://partner.com/callback
undefined适用于第三方集成的完整OAuth 2.0流程。
适用场景: 公开API、第三方开发者访问
支持的流程:
- 授权码流程
- 客户端凭证流程
- 隐式流程(已废弃)
- 资源所有者密码流程
配置:
yaml
plugins:
- name: oauth2
config:
scopes:
- read
- write
- admin
mandatory_scope: true
token_expiration: 3600
enable_authorization_code: true
enable_client_credentials: true
enable_implicit_grant: false
enable_password_grant: false
hide_credentials: true
accept_http_if_already_terminated: false
refresh_token_ttl: 1209600 # 14天Pattern 4: OpenID Connect (OIDC)
创建OAuth应用
Enterprise SSO integration with identity providers.
Use Case: Enterprise authentication with Google, Okta, Auth0, Azure AD
Configuration:
yaml
plugins:
- name: openid-connect
config:
issuer: https://accounts.google.com
client_id: your-client-id.apps.googleusercontent.com
client_secret: your-client-secret
redirect_uri:
- https://api.example.com/callback
scopes:
- openid
- email
- profile
auth_methods:
- authorization_code
login_redirect_uri: https://app.example.com/login
logout_redirect_uri: https://app.example.com/logout
ssl_verify: true
session_secret: change-this-secret-in-production
discovery: https://accounts.google.com/.well-known/openid-configurationMulti-Provider Configuration:
yaml
undefinedoauth2_credentials:
- consumer: third-party-app name: "合作伙伴集成" client_id: client_abc123 client_secret: secret_xyz789 redirect_uris:
**授权码流程:**
```bashGoogle OIDC
1. 获取授权码
plugins:
- name: openid-connect route: google-login config: issuer: https://accounts.google.com client_id: google-client-id client_secret: google-secret
GET /oauth2/authorize?
response_type=code&
client_id=client_abc123&
redirect_uri=https://partner.com/callback&
scope=read write
Azure AD OIDC
2. 用授权码交换令牌
plugins:
- name: openid-connect route: azure-login config: issuer: https://login.microsoftonline.com/tenant-id/v2.0 client_id: azure-client-id client_secret: azure-secret
POST /oauth2/token
grant_type=authorization_code&
client_id=client_abc123&
client_secret=secret_xyz789&
code=AUTH_CODE&
redirect_uri=https://partner.com/callback
undefinedOkta OIDC
模式4:OpenID Connect (OIDC)
plugins:
- name: openid-connect route: okta-login config: issuer: https://dev-123456.okta.com client_id: okta-client-id client_secret: okta-secret
undefined与身份提供商集成的企业单点登录。
适用场景: 使用Google、Okta、Auth0、Azure AD进行企业认证
配置:
yaml
plugins:
- name: openid-connect
config:
issuer: https://accounts.google.com
client_id: your-client-id.apps.googleusercontent.com
client_secret: your-client-secret
redirect_uri:
- https://api.example.com/callback
scopes:
- openid
- email
- profile
auth_methods:
- authorization_code
login_redirect_uri: https://app.example.com/login
logout_redirect_uri: https://app.example.com/logout
ssl_verify: true
session_secret: change-this-secret-in-production
discovery: https://accounts.google.com/.well-known/openid-configuration多提供商配置:
yaml
undefinedPattern 5: mTLS (Mutual TLS) Authentication
Google OIDC
Certificate-based authentication for service-to-service security.
Use Case: Microservices mutual authentication, B2B integrations
Configuration:
yaml
undefinedplugins:
- name: openid-connect route: google-login config: issuer: https://accounts.google.com client_id: google-client-id client_secret: google-secret
Enable mTLS plugin
Azure AD OIDC
plugins:
- name: mtls-auth config: ca_certificates: - ca-cert-id-1 - ca-cert-id-2 skip_consumer_lookup: false anonymous: null revocation_check_mode: SKIP # or IGNORE_CA_ERROR, STRICT
plugins:
- name: openid-connect route: azure-login config: issuer: https://login.microsoftonline.com/tenant-id/v2.0 client_id: azure-client-id client_secret: azure-secret
Upload CA certificate
Okta OIDC
ca_certificates:
- cert: | -----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAKL... -----END CERTIFICATE-----
plugins:
- name: openid-connect route: okta-login config: issuer: https://dev-123456.okta.com client_id: okta-client-id client_secret: okta-secret
undefinedCreate consumer mapped to client certificate
模式5:mTLS(双向TLS)认证
consumers:
- username: service-a custom_id: service-a-001
基于证书的服务间安全认证。
适用场景: 微服务间双向认证、B2B集成
配置:
yaml
undefinedMap certificate to consumer
启用mTLS插件
mtls_auth_credentials:
- consumer: service-a subject_name: CN=service-a,O=MyOrg
undefinedplugins:
- name: mtls-auth config: ca_certificates: - ca-cert-id-1 - ca-cert-id-2 skip_consumer_lookup: false anonymous: null revocation_check_mode: SKIP # 或IGNORE_CA_ERROR、STRICT
Load Balancing Patterns
上传CA证书
Pattern 1: Round-Robin Load Balancing
—
Distribute requests evenly across service instances.
Use Case: Stateless services with uniform capacity
Configuration:
yaml
upstreams:
- name: api-upstream
algorithm: round-robin
slots: 10000
healthchecks:
active:
type: http
http_path: /health
healthy:
interval: 5
successes: 2
unhealthy:
interval: 5
http_failures: 3
timeouts: 3
passive:
healthy:
successes: 5
unhealthy:
http_failures: 5
timeouts: 2
targets:
- upstream: api-upstream
target: api-1.internal:8001
weight: 100
- upstream: api-upstream
target: api-2.internal:8001
weight: 100
- upstream: api-upstream
target: api-3.internal:8001
weight: 100ca_certificates:
- cert: | -----BEGIN CERTIFICATE----- MIIDXTCCAkWgAwIBAgIJAKL... -----END CERTIFICATE-----
Pattern 2: Weighted Load Balancing
创建与客户端证书关联的消费者
Distribute traffic proportionally based on server capacity.
Use Case: Heterogeneous servers with different capacities
Configuration:
yaml
upstreams:
- name: api-upstream
algorithm: round-robin
targets:
# Powerful server - 50% traffic
- target: api-1.internal:8001
weight: 500
# Medium server - 30% traffic
- target: api-2.internal:8001
weight: 300
# Small server - 20% traffic
- target: api-3.internal:8001
weight: 200Weight Distribution:
- Total weight: 500 + 300 + 200 = 1000
- api-1: 500/1000 = 50% of requests
- api-2: 300/1000 = 30% of requests
- api-3: 200/1000 = 20% of requests
consumers:
- username: service-a custom_id: service-a-001
Pattern 3: Consistent Hashing
将证书映射至消费者
Route requests from same client to same backend (session affinity).
Use Case: Stateful services requiring session persistence
Configuration:
yaml
upstreams:
- name: api-upstream
algorithm: consistent-hashing
hash_on: header
hash_on_header: X-User-ID
hash_fallback: ip
hash_fallback_header: X-Forwarded-For
targets:
- target: api-1.internal:8001
- target: api-2.internal:8001
- target: api-3.internal:8001Hashing Options:
- - Random distribution
hash_on: none - - Hash by authenticated consumer
hash_on: consumer - - Hash by client IP
hash_on: ip - - Hash by specified header value
hash_on: header - - Hash by cookie value
hash_on: cookie - - Hash by request path
hash_on: path
Use Cases by Hash Type:
- User sessions: (X-User-ID)
hash_on: header - Geographic routing:
hash_on: ip - Tenant isolation: (X-Tenant-ID)
hash_on: header - Shopping carts: (session_id)
hash_on: cookie
mtls_auth_credentials:
- consumer: service-a subject_name: CN=service-a,O=MyOrg
undefinedPattern 4: Least Connections
负载均衡模式
—
模式1:轮询负载均衡
Route to server with fewest active connections.
Use Case: Long-lived connections (WebSockets, streaming)
Configuration:
yaml
upstreams:
- name: websocket-upstream
algorithm: least-connections
targets:
- target: ws-1.internal:8001
- target: ws-2.internal:8001
- target: ws-3.internal:8001When to Use:
- WebSocket servers
- Long-polling endpoints
- Streaming APIs (SSE, gRPC streaming)
- Services with variable request duration
将请求均匀分发至所有服务实例。
适用场景: 无状态服务,容量一致
配置:
yaml
upstreams:
- name: api-upstream
algorithm: round-robin
slots: 10000
healthchecks:
active:
type: http
http_path: /health
healthy:
interval: 5
successes: 2
unhealthy:
interval: 5
http_failures: 3
timeouts: 3
passive:
healthy:
successes: 5
unhealthy:
http_failures: 5
timeouts: 2
targets:
- upstream: api-upstream
target: api-1.internal:8001
weight: 100
- upstream: api-upstream
target: api-2.internal:8001
weight: 100
- upstream: api-upstream
target: api-3.internal:8001
weight: 100Pattern 5: Active Health Checks
模式2:加权负载均衡
Automatically remove unhealthy targets from rotation.
Use Case: High availability with automatic failover
Configuration:
yaml
upstreams:
- name: api-upstream
healthchecks:
active:
type: http
http_path: /health
https_verify_certificate: true
concurrency: 10
timeout: 1
headers:
X-Health-Check:
- gateway
healthy:
interval: 5 # Check every 5 seconds
http_statuses:
- 200
- 302
successes: 2 # 2 successes → healthy
unhealthy:
interval: 5
http_statuses:
- 429
- 500
- 503
http_failures: 3 # 3 failures → unhealthy
tcp_failures: 3
timeouts: 3
passive:
type: http
healthy:
http_statuses:
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 226
- 300
- 301
- 302
successes: 5
unhealthy:
http_statuses:
- 429
- 500
- 503
http_failures: 5
tcp_failures: 2
timeouts: 2根据服务器容量按比例分发流量。
适用场景: 异构服务器,容量不同
配置:
yaml
upstreams:
- name: api-upstream
algorithm: round-robin
targets:
- upstream: api-upstream
target: api-1.internal:8001
weight: 500 # 高性能服务器,承担50%流量
- upstream: api-upstream
target: api-2.internal:8001
weight: 300 # 中等性能,承担30%流量
- upstream: api-upstream
target: api-3.internal:8001
weight: 200 # 低性能,承担20%流量权重分配:
- 总权重:500+300+200=1000
- api-1: 500/1000 = 50% 请求
- api-2: 300/1000 = 30% 请求
- api-3: 200/1000 = 20% 请求
Traffic Control Patterns
模式3:一致性哈希
Pattern 1: Circuit Breaker
—
Prevent cascading failures by failing fast when downstream is unhealthy.
Use Case: Protect your system when dependencies fail
Configuration:
yaml
plugins:
- name: proxy-cache-advanced # Kong Enterprise
config:
# Serve stale cache during outages
cache_control: false
plugins:
- name: request-termination
enabled: false # Enabled programmatically on circuit open将同一客户端的请求路由至同一后端(会话亲和性)。
适用场景: 需要会话持久化的有状态服务
配置:
yaml
upstreams:
- name: api-upstream
algorithm: consistent-hashing
hash_on: header
hash_on_header: X-User-ID
hash_fallback: ip
hash_fallback_header: X-Forwarded-For
targets:
- upstream: api-upstream
target: api-1.internal:8001
- upstream: api-upstream
target: api-2.internal:8001
- upstream: api-upstream
target: api-3.internal:8001哈希选项:
- :随机分发
hash_on: none - :按认证消费者哈希
hash_on: consumer - :按客户端IP哈希
hash_on: ip - :按指定Header哈希
hash_on: header - :按Cookie哈希
hash_on: cookie - :按请求路径哈希
hash_on: path
按哈希类型的适用场景:
- 用户会话:(X-User-ID)
hash_on: header - 地理路由:
hash_on: ip - 租户隔离:(X-Tenant-ID)
hash_on: header - 购物车:(session_id)
hash_on: cookie
Custom circuit breaker (via passive health checks)
模式4:最少连接数
upstreams:
- name: api-upstream healthchecks: passive: unhealthy: http_failures: 5 # Open circuit after 5 failures timeouts: 3 healthy: successes: 3 # Close circuit after 3 successes
**Circuit States:**
1. **Closed**: Normal operation, requests flow through
2. **Open**: Failures detected, requests fail immediately
3. **Half-Open**: Test if service recovered, allow limited requests将请求路由至活跃连接数最少的服务器。
适用场景: 长连接(WebSocket、流处理)
配置:
yaml
upstreams:
- name: websocket-upstream
algorithm: least-connections
targets:
- upstream: websocket-upstream
target: ws-1.internal:8001
- upstream: websocket-upstream
target: ws-2.internal:8001
- upstream: websocket-upstream
target: ws-3.internal:8001适用场景:
- WebSocket服务器
- 长轮询端点
- 流API(SSE、gRPC流)
- 请求时长可变的服务
Pattern 2: Request Timeout
模式5:主动健康检查
Prevent slow requests from tying up resources.
Use Case: Prevent resource exhaustion from slow backends
Configuration:
yaml
services:
- name: api-service
url: http://api.internal:8001
read_timeout: 5000 # 5 seconds
write_timeout: 5000 # 5 seconds
connect_timeout: 2000 # 2 seconds
plugins:
- name: request-timeout # Additional timeout enforcement
config:
http_timeout: 5000
stream_timeout: 30000Timeout Strategy:
connect_timeout: 2s → Connection establishment
write_timeout: 5s → Writing request to upstream
read_timeout: 5s → Reading response from upstream
http_timeout: 5s → Overall HTTP transaction自动将不健康实例从轮换中移除。
适用场景: 高可用性与自动故障转移
配置:
yaml
upstreams:
- name: api-upstream
healthchecks:
active:
type: http
http_path: /health
https_verify_certificate: true
concurrency: 10
timeout: 1
headers:
X-Health-Check:
- gateway
healthy:
interval: 5 # 每5秒检查一次
http_statuses:
- 200
- 302
successes: 2 # 2次成功标记为健康
unhealthy:
interval: 5
http_statuses:
- 429
- 500
- 503
http_failures: 3 # 3次失败标记为不健康
tcp_failures: 3
timeouts: 3
passive:
type: http
healthy:
http_statuses:
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 226
- 300
- 301
- 302
successes: 5
unhealthy:
http_statuses:
- 429
- 500
- 503
http_failures: 5
tcp_failures: 2
timeouts: 2Pattern 3: Retry Logic
流量控制模式
—
模式1:断路器
Automatically retry failed requests with exponential backoff.
Use Case: Handle transient failures in distributed systems
Configuration:
yaml
services:
- name: api-service
retries: 5 # Maximum retry attempts
plugins:
- name: proxy-retry # Custom retry plugin
config:
retries: 3
retry_on:
- 500
- 502
- 503
- 504
backoff:
type: exponential
base: 2
max: 30
jitter: 0.5Retry Schedule:
Attempt 1: Immediate
Attempt 2: 2s + jitter
Attempt 3: 4s + jitter
Attempt 4: 8s + jitter
Attempt 5: 16s + jitterIdempotency Considerations:
- Retry GET, HEAD, PUT, DELETE (idempotent)
- DO NOT retry POST unless idempotency keys used
- Check for Idempotency-Key header
当下游服务不健康时快速失败,防止级联故障。
适用场景: 依赖服务故障时保护系统
配置:
yaml
plugins:
- name: proxy-cache-advanced # Kong企业版
config:
# 故障时返回缓存内容
cache_control: false
plugins:
- name: request-termination
enabled: false # 断路器打开时自动启用Pattern 4: Request Size Limiting
通过被动健康检查实现自定义断路器
Prevent large payload attacks and memory exhaustion.
Use Case: Protect against oversized request bodies
Configuration:
yaml
plugins:
- name: request-size-limiting
config:
allowed_payload_size: 10 # Megabytes
size_unit: megabytes
require_content_length: trueupstreams:
- name: api-upstream healthchecks: passive: unhealthy: http_failures: 5 # 5次失败后打开断路器 timeouts: 3 healthy: successes: 3 # 3次成功后关闭断路器
**断路器状态:**
1. **关闭**:正常运行,请求正常转发
2. **打开**:检测到故障,请求立即失败
3. **半开**:测试服务是否恢复,允许少量请求Different limits per route
模式2:请求超时
plugins:
-
name: request-size-limiting route: file-upload config: allowed_payload_size: 100 # Allow larger files
-
name: request-size-limiting route: api-endpoints config: allowed_payload_size: 1 # Strict limit for APIs
undefined防止慢请求占用资源。
适用场景: 防止慢后端导致资源耗尽
配置:
yaml
services:
- name: api-service
url: http://api.internal:8001
read_timeout: 5000 # 5秒
write_timeout: 5000 # 5秒
connect_timeout: 2000 # 2秒
plugins:
- name: request-timeout # 额外超时强制
config:
http_timeout: 5000
stream_timeout: 30000超时策略:
connect_timeout: 2s → 连接建立超时
write_timeout: 5s → 向上游写入请求超时
read_timeout: 5s → 从上游读取响应超时
http_timeout: 5s → 整个HTTP事务超时Pattern 5: Traffic Shaping (Throttling)
模式3:重试逻辑
Control request rate beyond simple rate limiting.
Use Case: Smooth traffic spikes, prevent backend overload
Configuration:
yaml
plugins:
- name: request-transformer-advanced
config:
# Add delay headers for client-side throttling
add:
headers:
- "Retry-After:60"
plugins:
- name: proxy-cache-advanced
config:
# Cache responses to reduce backend load
cache_ttl: 300
strategy: memory自动重试失败请求,支持指数退避。
适用场景: 处理分布式系统中的瞬时故障
配置:
yaml
services:
- name: api-service
retries: 5 # 最大重试次数
plugins:
- name: proxy-retry # 自定义重试插件
config:
retries: 3
retry_on:
- 500
- 502
- 503
- 504
backoff:
type: exponential
base: 2
max: 30
jitter: 0.5重试时间表:
第1次尝试:立即
第2次尝试:2秒 + 随机抖动
第3次尝试:4秒 + 随机抖动
第4次尝试:8秒 + 随机抖动
第5次尝试:16秒 + 随机抖动幂等性注意事项:
- 重试GET、HEAD、PUT、DELETE(幂等方法)
- 除非使用幂等键,否则不要重试POST
- 检查Idempotency-Key Header
Upstream connection limits
模式4:请求大小限制
upstreams:
- name: api-upstream slots: 1000 # Limit concurrent connections
undefined防止大 payload 攻击与内存耗尽。
适用场景: 防止超大请求体攻击
配置:
yaml
plugins:
- name: request-size-limiting
config:
allowed_payload_size: 10 # 兆字节
size_unit: megabytes
require_content_length: trueRequest/Response Transformation
为不同路由设置不同限制
Pattern 1: Request Header Manipulation
—
Add, modify, or remove request headers before proxying.
Use Case: Add authentication, tracing, or context headers
Configuration:
yaml
plugins:
- name: request-transformer
config:
add:
headers:
- "X-Gateway:kong"
- "X-Request-ID:$(uuid)"
- "X-Forwarded-Proto:https"
append:
headers:
- "X-Trace-Id:$(uuid)"
replace:
headers:
- "User-Agent:Kong-Gateway/3.0"
remove:
headers:
- "X-Internal-Secret"Advanced Transformations:
yaml
plugins:
- name: request-transformer-advanced
config:
add:
headers:
- "X-Consumer-Username:$(consumer_username)"
- "X-Consumer-ID:$(consumer_id)"
- "X-Authenticated-Scope:$(authenticated_credential.scope)"
- "X-Client-IP:$(remote_addr)"
rename:
headers:
- "Authorization:X-Original-Auth"plugins:
-
name: request-size-limiting route: file-upload config: allowed_payload_size: 100 # 允许更大文件
-
name: request-size-limiting route: api-endpoints config: allowed_payload_size: 1 # API严格限制
undefinedPattern 2: Response Header Manipulation
模式5:流量整形(限流)
Modify response headers before returning to client.
Use Case: Add security headers, CORS, caching directives
Configuration:
yaml
plugins:
- name: response-transformer
config:
add:
headers:
- "X-Gateway-Response-Time:$(latencies.request)"
- "X-Server-ID:$(upstream_addr)"
remove:
headers:
- "X-Powered-By"
- "Server"在简单限流之外控制请求速率。
适用场景: 平滑流量峰值,防止后端过载
配置:
yaml
plugins:
- name: request-transformer-advanced
config:
# 添加客户端限流的Retry-After Header
add:
headers:
- "Retry-After:60"
plugins:
- name: proxy-cache-advanced
config:
# 缓存响应以减少后端负载
cache_ttl: 300
strategy: memorySecurity headers
上游连接限制
plugins:
- name: response-transformer config: add: headers: - "Strict-Transport-Security:max-age=31536000; includeSubDomains" - "X-Content-Type-Options:nosniff" - "X-Frame-Options:DENY" - "X-XSS-Protection:1; mode=block" - "Content-Security-Policy:default-src 'self'"
undefinedupstreams:
- name: api-upstream slots: 1000 # 限制并发连接数
undefinedPattern 3: Request Body Transformation
请求/响应转换
—
模式1:请求Header处理
Modify request payloads before forwarding.
Use Case: Add fields, transform formats, sanitize input
Configuration:
yaml
plugins:
- name: request-transformer-advanced
config:
add:
body:
- "gateway_timestamp:$(timestamp)"
- "request_id:$(uuid)"
remove:
body:
- "internal_field"
replace:
body:
- "api_version:v2"在代理前添加、修改或移除请求Header。
适用场景: 添加认证、追踪或上下文Header
配置:
yaml
plugins:
- name: request-transformer
config:
add:
headers:
- "X-Gateway:kong"
- "X-Request-ID:$(uuid)"
- "X-Forwarded-Proto:https"
append:
headers:
- "X-Trace-Id:$(uuid)"
replace:
headers:
- "User-Agent:Kong-Gateway/3.0"
remove:
headers:
- "X-Internal-Secret"高级转换:
yaml
plugins:
- name: request-transformer-advanced
config:
add:
headers:
- "X-Consumer-Username:$(consumer_username)"
- "X-Consumer-ID:$(consumer_id)"
- "X-Authenticated-Scope:$(authenticated_credential.scope)"
- "X-Client-IP:$(remote_addr)"
rename:
headers:
- "Authorization:X-Original-Auth"Pattern 4: GraphQL to REST Translation
模式2:响应Header处理
Expose REST APIs as GraphQL endpoints.
Use Case: Modernize legacy REST APIs with GraphQL
Configuration:
yaml
plugins:
- name: graphql-proxy-cache-advanced
config:
strategy: memory在返回客户端前修改响应Header。
适用场景: 添加安全Header、CORS、缓存指令
配置:
yaml
plugins:
- name: response-transformer
config:
add:
headers:
- "X-Gateway-Response-Time:$(latencies.request)"
- "X-Server-ID:$(upstream_addr)"
remove:
headers:
- "X-Powered-By"
- "Server"Define GraphQL schema mapping
安全Header
graphql_schemas:
-
name: users-graphql schema: | type Query { user(id: ID!): User users: [User] }type User { id: ID! name: String! email: String! } resolvers: Query: user: http://users-api/users/{id} users: http://users-api/users
undefinedplugins:
- name: response-transformer config: add: headers: - "Strict-Transport-Security:max-age=31536000; includeSubDomains" - "X-Content-Type-Options:nosniff" - "X-Frame-Options:DENY" - "X-XSS-Protection:1; mode=block" - "Content-Security-Policy:default-src 'self'"
undefinedPattern 5: Protocol Translation
模式3:请求体转换
Convert between HTTP, gRPC, and WebSocket protocols.
Use Case: Expose gRPC services via HTTP/JSON
Configuration:
yaml
undefined在转发前修改请求负载。
适用场景: 添加字段、转换格式、清理输入
配置:
yaml
plugins:
- name: request-transformer-advanced
config:
add:
body:
- "gateway_timestamp:$(timestamp)"
- "request_id:$(uuid)"
remove:
body:
- "internal_field"
replace:
body:
- "api_version:v2"gRPC to HTTP/JSON
模式4:GraphQL转REST
plugins:
- name: grpc-gateway config: proto: /path/to/service.proto
services:
- name: grpc-service url: grpc://grpc.internal:9000 protocol: grpc
routes:
- name: grpc-http-route
paths:
- /v1/users protocols:
- http
- https
undefined将REST API暴露为GraphQL端点。
适用场景: 用GraphQL现代化遗留REST API
配置:
yaml
plugins:
- name: graphql-proxy-cache-advanced
config:
strategy: memoryCaching Patterns
定义GraphQL schema映射
Pattern 1: Response Caching
—
Cache upstream responses to reduce backend load.
Use Case: Cache expensive queries, reduce database load
Configuration:
yaml
plugins:
- name: proxy-cache
config:
strategy: memory # or 'redis'
content_type:
- "application/json"
- "text/html"
cache_ttl: 300 # 5 minutes
cache_control: false # Ignore client cache headers
storage_ttl: 600 # Backend storage TTL
memory:
dictionary_name: kong_cache
vary_headers:
- "Accept-Language"
- "X-User-Tier"Redis-Based Caching:
yaml
plugins:
- name: proxy-cache-advanced
config:
strategy: redis
cache_ttl: 3600
redis:
host: redis.internal
port: 6379
database: 0
password: redis-password
timeout: 2000
sentinel_master: mymaster
sentinel_addresses:
- redis-sentinel-1:26379
- redis-sentinel-2:26379graphql_schemas:
-
name: users-graphql schema: | type Query { user(id: ID!): User users: [User] }type User { id: ID! name: String! email: String! } resolvers: Query: user: http://users-api/users/{id} users: http://users-api/users
undefinedPattern 2: Conditional Caching
模式5:协议转换
Cache based on status codes, headers, or request criteria.
Use Case: Cache only successful responses, skip errors
Configuration:
yaml
plugins:
- name: proxy-cache-advanced
config:
response_code:
- 200
- 301
- 302
request_method:
- GET
- HEAD
vary_headers:
- "Accept"
- "Accept-Encoding"
vary_query_params:
- "page"
- "limit"
ignore_uri_case: true在HTTP、gRPC、WebSocket间转换协议。
适用场景: 通过HTTP/JSON暴露gRPC服务
配置:
yaml
undefinedPattern 3: Cache Invalidation
gRPC转HTTP/JSON
Purge cache on-demand or based on events.
Use Case: Update cache when data changes
Configuration:
yaml
undefinedplugins:
- name: grpc-gateway config: proto: /path/to/service.proto
services:
- name: grpc-service url: grpc://grpc.internal:9000 protocol: grpc
routes:
- name: grpc-http-route
paths:
- /v1/users protocols:
- http
- https
undefinedAdmin API cache purge
缓存模式
—
模式1:响应缓存
POST /cache/purge
缓存上游响应以减少后端负载。
适用场景: 缓存昂贵查询,减少数据库负载
配置:
yaml
plugins:
- name: proxy-cache
config:
strategy: memory # 或'redis'
content_type:
- "application/json"
- "text/html"
cache_ttl: 300 # 5分钟
cache_control: false # 忽略客户端缓存Header
storage_ttl: 600 # 后端存储TTL
memory:
dictionary_name: kong_cache
vary_headers:
- "Accept-Language"
- "X-User-Tier"基于Redis的缓存:
yaml
plugins:
- name: proxy-cache-advanced
config:
strategy: redis
cache_ttl: 3600
redis:
host: redis.internal
port: 6379
database: 0
password: redis-password
timeout: 2000
sentinel_master: mymaster
sentinel_addresses:
- redis-sentinel-1:26379
- redis-sentinel-2:26379Purge specific endpoint
模式2:条件缓存
POST /cache/purge/users
根据状态码、Header或请求条件缓存。
适用场景: 仅缓存成功响应,跳过错误
配置:
yaml
plugins:
- name: proxy-cache-advanced
config:
response_code:
- 200
- 301
- 302
request_method:
- GET
- HEAD
vary_headers:
- "Accept"
- "Accept-Encoding"
vary_query_params:
- "page"
- "limit"
ignore_uri_case: trueTTL-based expiration
模式3:缓存失效
plugins:
- name: proxy-cache config: cache_ttl: 60 # Short TTL for frequently updated data
按需或基于事件清除缓存。
适用场景: 数据变更时更新缓存
配置:
yaml
undefinedEvent-based invalidation (custom plugin)
Admin API清除缓存
plugins:
- name: custom-cache-invalidator config: invalidate_on: - POST - PUT - PATCH - DELETE propagate: true # Clear related caches
undefinedPOST /cache/purge
Pattern 4: Multi-Tier Caching
清除特定端点
Layer caching at gateway and backend.
Use Case: Maximize cache hit rate across layers
Architecture:
Client
↓
Kong Gateway Cache (L1)
↓
Backend API Cache (L2)
↓
DatabaseConfiguration:
yaml
undefinedPOST /cache/purge/users
Gateway cache (L1)
基于TTL的过期
plugins:
- name: proxy-cache config: strategy: memory cache_ttl: 60 # 1 minute
plugins:
- name: proxy-cache config: cache_ttl: 60 # 频繁更新数据使用短TTL
Backend passes Cache-Control headers
基于事件的失效(自定义插件)
Gateway respects them if cache_control: true
—
plugins:
- name: proxy-cache config: cache_control: true # Respect upstream Cache-Control vary_headers: - "Cache-Control"
undefinedplugins:
- name: custom-cache-invalidator config: invalidate_on: - POST - PUT - PATCH - DELETE propagate: true # 清除相关缓存
undefinedPattern 5: Surrogate-Key Based Invalidation
模式4:多层缓存
Tag caches for granular invalidation.
Use Case: Invalidate related resources efficiently
Configuration:
yaml
undefined在网关与后端设置多层缓存。
适用场景: 最大化跨层缓存命中率
架构:
客户端
↓
Kong网关缓存(L1)
↓
后端API缓存(L2)
↓
数据库配置:
yaml
undefinedTag responses with surrogate keys
网关缓存(L1)
plugins:
- name: response-transformer config: add: headers: - "Surrogate-Key:user-$(user_id) tenant-$(tenant_id)"
plugins:
- name: proxy-cache config: strategy: memory cache_ttl: 60 # 1分钟
Invalidate by surrogate key
后端返回Cache-Control Header
Custom plugin or Varnish integration
若cache_control: true,网关会遵循上游的Cache-Control
POST /cache/purge
Headers:
Surrogate-Key: user-123
undefinedplugins:
- name: proxy-cache config: cache_control: true # 遵循上游Cache-Control vary_headers: - "Cache-Control"
undefinedSecurity Patterns
模式5:基于代理键的失效
Pattern 1: CORS (Cross-Origin Resource Sharing)
—
Enable controlled cross-origin requests.
Use Case: Web apps calling APIs from different domains
Configuration:
yaml
plugins:
- name: cors
config:
origins:
- "https://app.example.com"
- "https://admin.example.com"
methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
headers:
- Accept
- Authorization
- Content-Type
- X-Request-ID
exposed_headers:
- X-Total-Count
- X-Page-Number
credentials: true
max_age: 3600
preflight_continue: falseWildcard CORS (Development Only):
yaml
plugins:
- name: cors
config:
origins:
- "*"
methods:
- "*"
headers:
- "*"
credentials: false # Must be false with wildcard origins为缓存打标签以实现细粒度失效。
适用场景: 高效失效相关资源
配置:
yaml
undefinedPattern 2: IP Restriction
用代理键标记响应
Allow or deny based on IP addresses.
Use Case: Restrict admin APIs to office IPs
Configuration:
yaml
undefinedplugins:
- name: response-transformer config: add: headers: - "Surrogate-Key:user-$(user_id) tenant-$(tenant_id)"
Whitelist approach
按代理键失效
—
自定义插件或Varnish集成
plugins:
- name: ip-restriction config: allow: - 10.0.0.0/8 - 192.168.1.100 - 203.0.113.0/24
POST /cache/purge
Headers:
Surrogate-Key: user-123
undefinedBlacklist approach
安全模式
—
模式1:CORS(跨域资源共享)
plugins:
- name: ip-restriction config: deny: - 1.2.3.4 - 5.6.7.0/24
**Combined with Authentication:**
```yaml启用受控的跨域请求。
适用场景: Web应用从不同域名调用API
配置:
yaml
plugins:
- name: cors
config:
origins:
- "https://app.example.com"
- "https://admin.example.com"
methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
headers:
- Accept
- Authorization
- Content-Type
- X-Request-ID
exposed_headers:
- X-Total-Count
- X-Page-Number
credentials: true
max_age: 3600
preflight_continue: false开发环境通配符CORS:
yaml
plugins:
- name: cors
config:
origins:
- "*"
methods:
- "*"
headers:
- "*"
credentials: false # 通配符origin时必须为falseAdmin route: IP + Auth
模式2:IP限制
plugins:
-
name: ip-restriction route: admin-api config: allow: - 10.0.0.0/8
-
name: key-auth route: admin-api
undefined根据IP地址允许或拒绝请求。
适用场景: 将Admin API限制为办公IP
配置:
yaml
undefinedPattern 3: Bot Detection
白名单方式
Detect and block malicious bots.
Use Case: Prevent scraping, brute force, spam
Configuration:
yaml
plugins:
- name: bot-detection
config:
allow:
- "googlebot"
- "bingbot"
- "slackbot"
deny:
- "curl"
- "wget"
- "scrapy"
blacklist_cache_size: 10000
whitelist_cache_size: 10000plugins:
- name: ip-restriction config: allow: - 10.0.0.0/8 - 192.168.1.100 - 203.0.113.0/24
Pattern 4: Request Validation
黑名单方式
Validate requests against schemas.
Use Case: Ensure API contract compliance, prevent injection
Configuration:
yaml
plugins:
- name: request-validator
config:
body_schema: |
{
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 50
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 18,
"maximum": 120
}
},
"required": ["username", "email"]
}
parameter_schema:
- name: page
in: query
required: false
schema:
type: integer
minimum: 1plugins:
- name: ip-restriction config: deny: - 1.2.3.4 - 5.6.7.0/24
**与认证结合:**
```yamlPattern 5: WAF (Web Application Firewall)
Admin路由:IP + 认证
Protect against OWASP Top 10 vulnerabilities.
Use Case: Block SQL injection, XSS, path traversal
Configuration:
yaml
plugins:
- name: waf # Kong Enterprise or ModSecurity plugin
config:
rule_sets:
- owasp_crs
anomaly_threshold: 5
paranoia_level: 1
blocked_status_code: 403plugins:
-
name: ip-restriction route: admin-api config: allow: - 10.0.0.0/8
-
name: key-auth route: admin-api
undefinedObservability Patterns
模式3:机器人检测
Pattern 1: Request Logging
—
Log all API requests for audit and debugging.
Use Case: Compliance, debugging, analytics
Configuration:
yaml
plugins:
- name: file-log
config:
path: /var/log/kong/requests.log
reopen: true检测并阻止恶意机器人。
适用场景: 防止爬取、暴力破解、垃圾信息
配置:
yaml
plugins:
- name: bot-detection
config:
allow:
- "googlebot"
- "bingbot"
- "slackbot"
deny:
- "curl"
- "wget"
- "scrapy"
blacklist_cache_size: 10000
whitelist_cache_size: 10000JSON structured logging
模式4:请求验证
plugins:
- name: http-log config: http_endpoint: http://logstash:5000 method: POST content_type: application/json timeout: 5000 keepalive: 60000 custom_fields_by_lua: request_id: "return kong.request.get_header('X-Request-ID')"
**Log to Multiple Destinations:**
```yaml根据Schema验证请求。
适用场景: 确保API契约合规,防止注入攻击
配置:
yaml
plugins:
- name: request-validator
config:
body_schema: |
{
"type": "object",
"properties": {
"username": {
"type": "string",
"minLength": 3,
"maxLength": 50
},
"email": {
"type": "string",
"format": "email"
},
"age": {
"type": "integer",
"minimum": 18,
"maximum": 120
}
},
"required": ["username", "email"]
}
parameter_schema:
- name: page
in: query
required: false
schema:
type: integer
minimum: 1Elasticsearch
模式5:WAF(Web应用防火墙)
plugins:
- name: http-log config: http_endpoint: http://elasticsearch:9200/_bulk
防护OWASP Top 10漏洞。
适用场景: 阻止SQL注入、XSS、路径遍历
配置:
yaml
plugins:
- name: waf # Kong企业版或ModSecurity插件
config:
rule_sets:
- owasp_crs
anomaly_threshold: 5
paranoia_level: 1
blocked_status_code: 403Splunk
可观测性模式
—
模式1:请求日志
plugins:
- name: http-log config: http_endpoint: https://splunk:8088/services/collector headers: Authorization: "Splunk token"
记录所有API请求用于审计与调试。
适用场景: 合规性、调试、分析
配置:
yaml
plugins:
- name: file-log
config:
path: /var/log/kong/requests.log
reopen: trueDatadog
JSON结构化日志
plugins:
- name: datadog config: host: datadog-agent port: 8125
undefinedplugins:
- name: http-log config: http_endpoint: http://logstash:5000 method: POST content_type: application/json timeout: 5000 keepalive: 60000 custom_fields_by_lua: request_id: "return kong.request.get_header('X-Request-ID')"
**多目标日志:**
```yamlPattern 2: Distributed Tracing
Elasticsearch
Track requests across microservices.
Use Case: Diagnose latency, understand request flow
Configuration:
yaml
undefinedplugins:
- name: http-log config: http_endpoint: http://elasticsearch:9200/_bulk
Zipkin
Splunk
plugins:
- name: zipkin config: http_endpoint: http://zipkin:9411/api/v2/spans sample_ratio: 0.1 # Trace 10% of requests include_credential: true traceid_byte_count: 16 header_type: preserve # or 'jaeger', 'b3', 'w3c'
plugins:
- name: http-log config: http_endpoint: https://splunk:8088/services/collector headers: Authorization: "Splunk token"
Jaeger
Datadog
plugins:
- name: opentelemetry config: endpoint: http://jaeger:14268/api/traces resource_attributes: service.name: api-gateway service.version: 1.0.0 batch_span_processor: max_queue_size: 2048 batch_timeout: 5000
**W3C Trace Context:**
```yaml
plugins:
- name: opentelemetry
config:
propagation:
default: w3c
headers:
- traceparent
- tracestateplugins:
- name: datadog config: host: datadog-agent port: 8125
undefinedPattern 3: Metrics Collection
模式2:分布式追踪
Expose Prometheus metrics for monitoring.
Use Case: Monitor gateway performance, errors, latency
Configuration:
yaml
plugins:
- name: prometheus
config:
per_consumer: true
status_code_metrics: true
latency_metrics: true
bandwidth_metrics: true
upstream_health_metrics: true跨微服务追踪请求。
适用场景: 诊断延迟,理解请求流
配置:
yaml
undefinedExpose /metrics endpoint
Zipkin
routes:
- name: metrics
paths:
- /metrics service: prometheus-service
**Available Metrics:**plugins:
- name: zipkin config: http_endpoint: http://zipkin:9411/api/v2/spans sample_ratio: 0.1 # 追踪10%的请求 include_credential: true traceid_byte_count: 16 header_type: preserve # 或'jaeger'、'b3'、'w3c'
Requests
Jaeger
kong_http_requests_total{service,route,code}
plugins:
- name: opentelemetry config: endpoint: http://jaeger:14268/api/traces resource_attributes: service.name: api-gateway service.version: 1.0.0 batch_span_processor: max_queue_size: 2048 batch_timeout: 5000
**W3C追踪上下文:**
```yaml
plugins:
- name: opentelemetry
config:
propagation:
default: w3c
headers:
- traceparent
- tracestateLatency
模式3:指标收集
kong_latency_ms{type,service,route}
kong_request_latency_ms{service,route}
kong_upstream_latency_ms{service,route}
暴露Prometheus指标用于监控。
适用场景: 监控网关性能、错误、延迟
配置:
yaml
plugins:
- name: prometheus
config:
per_consumer: true
status_code_metrics: true
latency_metrics: true
bandwidth_metrics: true
upstream_health_metrics: trueBandwidth
暴露/metrics端点
kong_bandwidth_bytes{type,service,route}
routes:
- name: metrics
paths:
- /metrics service: prometheus-service
**可用指标:**Connections
请求数
kong_datastore_reachable
kong_nginx_connections_total{state}
undefinedkong_http_requests_total{service,route,code}
Pattern 4: Health Checks
延迟
Expose health check endpoints.
Use Case: Kubernetes liveness/readiness probes
Configuration:
yaml
undefinedkong_latency_ms{type,service,route}
kong_request_latency_ms{service,route}
kong_upstream_latency_ms{service,route}
Gateway health
带宽
routes:
- name: health
paths:
- /health plugins:
- name: request-termination config: status_code: 200 message: "OK"
kong_bandwidth_bytes{type,service,route}
Detailed status
连接数
routes:
- name: status
paths:
- /status service: kong-status-service
kong_datastore_reachable
kong_nginx_connections_total{state}
undefinedUpstream health aggregation
模式4:健康检查
plugins:
- name: upstream-health-check config: healthy_threshold: 2 unhealthy_threshold: 3
undefined暴露健康检查端点。
适用场景: Kubernetes存活/就绪探针
配置:
yaml
undefinedPattern 5: Error Tracking
网关健康检查
Track and report errors to monitoring systems.
Use Case: Proactive error detection and alerting
Configuration:
yaml
undefinedroutes:
- name: health
paths:
- /health plugins:
- name: request-termination config: status_code: 200 message: "OK"
Sentry integration
详细状态
plugins:
- name: sentry config: dsn: https://key@sentry.io/project environment: production release: v1.2.3
routes:
- name: status
paths:
- /status service: kong-status-service
Custom error logging
上游健康聚合
plugins:
- name: http-log config: http_endpoint: http://error-tracker:5000 custom_fields_by_lua: error_type: | if kong.response.get_status() >= 500 then return "server_error" elseif kong.response.get_status() >= 400 then return "client_error" end
undefinedplugins:
- name: upstream-health-check config: healthy_threshold: 2 unhealthy_threshold: 3
undefinedMulti-Environment Patterns
模式5:错误追踪
Pattern 1: Environment Separation
—
Separate configurations for dev, staging, production.
Use Case: Consistent deployment across environments
Structure:
config/
├── base.yaml # Shared configuration
├── dev.yaml # Development overrides
├── staging.yaml # Staging overrides
└── production.yaml # Production overridesConfiguration:
yaml
undefined追踪并向监控系统报告错误。
适用场景: 主动错误检测与告警
配置:
yaml
undefinedbase.yaml
Sentry集成
_format_version: "3.0"
services:
- name: users-api url: http://users-service:8001
routes:
- name: users-route
service: users-api
paths:
- /users
plugins:
- name: sentry config: dsn: https://key@sentry.io/project environment: production release: v1.2.3
production.yaml
自定义错误日志
_format_version: "3.0"
services:
- name: users-api url: https://users-api-prod.internal:8001 retries: 5 read_timeout: 5000
plugins:
- name: rate-limiting service: users-api config: minute: 1000
undefinedplugins:
- name: http-log config: http_endpoint: http://error-tracker:5000 custom_fields_by_lua: error_type: | if kong.response.get_status() >= 500 then return "server_error" elseif kong.response.get_status() >= 400 then return "client_error" end
undefinedPattern 2: Blue-Green Deployments
多环境模式
—
模式1:环境隔离
Zero-downtime deployments with instant rollback.
Use Case: Safe production deployments
Configuration:
yaml
undefined为开发、 staging、生产环境分离配置。
适用场景: 跨环境一致部署
结构:
config/
├── base.yaml # 共享配置
├── dev.yaml # 开发环境覆盖
├── staging.yaml # Staging环境覆盖
└── production.yaml # 生产环境覆盖配置:
yaml
undefinedBlue environment (current production)
base.yaml
upstreams:
- name: api-blue
targets:
- target: api-blue-1:8001
- target: api-blue-2:8001
_format_version: "3.0"
services:
- name: users-api url: http://users-service:8001
routes:
- name: users-route
service: users-api
paths:
- /users
Green environment (new version)
production.yaml
upstreams:
- name: api-green
targets:
- target: api-green-1:8001
- target: api-green-2:8001
_format_version: "3.0"
services:
- name: users-api url: https://users-api-prod.internal:8001 retries: 5 read_timeout: 5000
plugins:
- name: rate-limiting service: users-api config: minute: 1000
undefinedRoute points to active environment
模式2:蓝绿部署
services:
- name: api-service host: api-blue # Switch to api-green for deployment
零停机部署,支持即时回滚。
适用场景: 安全的生产部署
配置:
yaml
undefinedRollback: Switch service.host back to api-blue
蓝色环境(当前生产)
undefinedupstreams:
- name: api-blue
targets:
- target: api-blue-1:8001
- target: api-blue-2:8001
Pattern 3: Canary Releases
绿色环境(新版本)
Gradual rollout with monitoring.
Use Case: Risk mitigation for new releases
Configuration:
yaml
undefinedupstreams:
- name: api-green
targets:
- target: api-green-1:8001
- target: api-green-2:8001
Canary routing with header
路由指向活跃环境
routes:
- name: api-canary
paths:
- /api
headers:
X-Canary:
- "true" service: api-v2
- /api
headers:
X-Canary:
routes:
- name: api-stable
paths:
- /api service: api-v1
services:
- name: api-service host: api-blue # 部署时切换为api-green
Weighted canary (10% traffic)
回滚:将service.host切回api-blue
upstreams:
- name: api-upstream
targets:
- target: api-v1:8001 weight: 90
- target: api-v2:8001 weight: 10
**Canary Progression:**Phase 1: 5% canary, monitor errors
Phase 2: 25% canary, check metrics
Phase 3: 50% canary, verify performance
Phase 4: 100% canary, deprecate old version
undefinedundefinedPattern 4: Feature Flags
模式3:金丝雀发布
Enable/disable features dynamically.
Use Case: A/B testing, gradual feature rollout
Configuration:
yaml
undefined逐步发布并监控。
适用场景: 新版本风险缓解
配置:
yaml
undefinedFeature flag via header
带权重的金丝雀路由
routes:
- name: new-feature
paths:
- /api/new-feature
headers:
X-Feature-Flag:
- "new-dashboard" service: new-feature-service
- /api/new-feature
headers:
X-Feature-Flag:
upstreams:
- name: api-upstream
targets:
- target: api-v1:8001 weight: 90 # 90%流量到稳定版
- target: api-v2:8002 weight: 10 # 10%流量到新版本
services:
- name: api-service host: api-upstream
**金丝雀发布流程:**阶段1:5%流量到新版本,监控指标
阶段2:25%流量,验证功能
阶段3:50%流量,监控性能
阶段4:75%流量,全面测试
阶段5:100%流量,完成发布
undefinedDefault route (feature disabled)
模式4:功能标记
routes:
- name: old-feature
paths:
- /api/new-feature service: old-feature-service
动态启用/禁用功能。
适用场景: A/B测试,逐步功能发布
配置:
yaml
undefinedConsumer-based feature flags
基于Header的功能标记
plugins:
- name: request-transformer consumer: beta-users config: add: headers: - "X-Feature-Flags:new-dashboard,advanced-search"
undefinedroutes:
- name: new-feature
paths:
- /api/new-feature
headers:
X-Feature-Flag:
- "new-dashboard" service: new-feature-service
- /api/new-feature
headers:
X-Feature-Flag:
Pattern 5: Multi-Region Deployment
默认路由(功能禁用)
Route to nearest region for low latency.
Use Case: Global API with regional failover
Configuration:
yaml
undefinedroutes:
- name: old-feature
paths:
- /api/new-feature service: old-feature-service
US region
基于消费者的功能标记
upstreams:
- name: api-us
targets:
- target: api-us-east:8001
- target: api-us-west:8001
plugins:
- name: request-transformer consumer: beta-users config: add: headers: - "X-Feature-Flags:new-dashboard,advanced-search"
undefinedEU region
模式5:多区域部署
upstreams:
- name: api-eu
targets:
- target: api-eu-west:8001
- target: api-eu-central:8001
将请求路由至最近区域以降低延迟。
适用场景: 全球API,区域故障转移
配置:
yaml
undefinedGeographic routing (via DNS or header)
美国区域
routes:
- name: us-traffic
hosts:
- us.api.example.com service: api-us-service
routes:
- name: eu-traffic
hosts:
- eu.api.example.com service: api-eu-service
undefinedupstreams:
- name: api-us
targets:
- target: api-us-east:8001
- target: api-us-west:8001
Best Practices
欧洲区域
Architecture Design
—
- Single Responsibility: Gateway handles cross-cutting concerns only
- Stateless Design: Keep gateway stateless for horizontal scaling
- Declarative Configuration: Use YAML/JSON for version-controlled config
- Database-Less Mode: Use DB-less for simpler deployments
- Plugin Minimalism: Only enable necessary plugins
upstreams:
- name: api-eu
targets:
- target: api-eu-west:8001
- target: api-eu-central:8001
Security Best Practices
地理路由(通过DNS或Header)
- Defense in Depth: Layer multiple security mechanisms
- Least Privilege: Minimal permissions for consumers
- Secrets Management: Never hardcode credentials
- TLS Everywhere: Encrypt all traffic (client and upstream)
- Rate Limiting: Always protect public endpoints
- Input Validation: Validate all request data
- Regular Updates: Keep Kong and plugins updated
routes:
- name: us-traffic
hosts:
- us.api.example.com service: api-us-service
routes:
- name: eu-traffic
hosts:
- eu.api.example.com service: api-eu-service
undefinedPerformance Optimization
最佳实践
—
架构设计
- Enable Caching: Cache responses aggressively
- Connection Pooling: Reuse upstream connections
- Load Balancing: Distribute load evenly
- Health Checks: Remove unhealthy targets quickly
- Timeouts: Set appropriate timeouts to prevent hangs
- Monitoring: Track latency, errors, throughput
- Resource Limits: Set memory and connection limits
- 单一职责:网关仅处理横切关注点
- 无状态设计:保持网关无状态以支持水平扩展
- 声明式配置:使用YAML/JSON进行版本控制的配置
- 无DB模式:使用无DB模式简化部署
- 插件极简:仅启用必要插件
Operational Excellence
安全最佳实践
- Logging: Structured logging for all requests
- Monitoring: Comprehensive metrics collection
- Alerting: Alert on anomalies and errors
- Documentation: Document all routes and plugins
- Testing: Test gateway config in staging
- Versioning: Version control all configurations
- Disaster Recovery: Plan for failover scenarios
- 纵深防御:多层安全机制
- 最小权限:为消费者分配最小权限
- 密钥管理:切勿硬编码凭证
- 全链路TLS:加密所有流量(客户端与上游)
- 限流:始终保护公开端点
- 输入验证:验证所有请求数据
- 定期更新:保持Kong与插件为最新版本
Plugin Strategy
性能优化
- Order Matters: Plugins execute in specific order
- Scope Appropriately: Global, service, route, or consumer
- Test Thoroughly: Test plugin combinations
- Monitor Impact: Track plugin performance overhead
- Custom Plugins: Write custom plugins for unique needs
Plugin Execution Order:
1. Authentication (key-auth, jwt, oauth2)
2. Security (ip-restriction, bot-detection)
3. Traffic Control (rate-limiting, request-size-limiting)
4. Transformation (request-transformer)
5. Logging (file-log, http-log)
6. Analytics (prometheus, datadog)- 启用缓存:积极缓存响应
- 连接池:复用上游连接
- 负载均衡:均匀分发负载
- 健康检查:快速移除不健康实例
- 超时设置:设置合理超时防止挂起
- 监控:追踪延迟、错误、吞吐量
- 资源限制:设置内存与连接限制
Configuration Management
运维卓越
- Version Control: Git for all configurations
- Environment Parity: Consistent configs across environments
- Automated Deployment: CI/CD for configuration changes
- Validation: Validate configs before applying
- Rollback Plan: Quick rollback on issues
- Change Log: Document all configuration changes
- 日志:所有请求使用结构化日志
- 监控:全面的指标收集
- 告警:异常与错误告警
- 文档:记录所有路由与插件
- 测试:在Staging环境测试网关配置
- 版本控制:所有配置纳入版本控制
- 灾难恢复:制定故障转移计划
Scaling Guidelines
插件策略
- Horizontal Scaling: Add more Kong nodes
- Database Scaling: Scale PostgreSQL separately
- Cache Offloading: Use Redis for distributed caching
- Regional Deployment: Deploy close to users
- CDN Integration: Offload static content
- Connection Limits: Set per-worker limits
- 顺序重要:插件按特定顺序执行
- 作用域恰当:全局、服务、路由或消费者级
- 充分测试:测试插件组合
- 监控影响:追踪插件性能开销
- 自定义插件:为独特需求编写自定义插件
插件执行顺序:
1. 认证(key-auth、jwt、oauth2)
2. 安全(ip-restriction、bot-detection)
3. 流量控制(rate-limiting、request-size-limiting)
4. 转换(request-transformer)
5. 日志(file-log、http-log)
6. 分析(prometheus、datadog)Common Use Cases
配置管理
Use Case 1: SaaS API Platform
—
Requirements:
- Multi-tenant isolation
- Tiered pricing (free, pro, enterprise)
- Rate limiting per tier
- Analytics per customer
- Self-service developer portal
Implementation:
yaml
undefined- 版本控制:所有配置使用Git管理
- 环境一致性:跨环境保持配置一致
- 自动化部署:CI/CD配置变更
- 验证:应用前验证配置
- 回滚计划:配置变更的快速回滚
- 变更日志:记录所有配置变更
Tenant identification
扩展指南
plugins:
- name: key-auth config: key_names: - X-API-Key
- 水平扩展:添加更多Kong节点
- 数据库扩展:独立扩展PostgreSQL
- 缓存卸载:使用Redis进行分布式缓存
- 区域部署:部署在靠近用户的区域
- CDN集成:卸载静态内容
- 连接限制:设置每工作进程的连接限制
Tier-based rate limiting
常见用例
—
用例1:SaaS API平台
consumers:
- username: free-tier-customer custom_id: customer-123
plugins:
- name: rate-limiting consumer: free-tier-customer config: minute: 60 hour: 1000
需求:
- 多租户隔离
- 分级定价(免费、专业、企业)
- 按租户限流
- 按客户分析
- 自助开发者门户
实现:
yaml
undefinedUsage analytics
租户识别
plugins:
- name: prometheus config: per_consumer: true
plugins:
- name: key-auth config: key_names: - X-API-Key
Request transformation (add tenant context)
基于租户的限流
plugins:
- name: request-transformer config: add: headers: - "X-Tenant-ID:$(consumer_custom_id)"
undefinedconsumers:
- username: free-tier-customer custom_id: customer-123
plugins:
- name: rate-limiting consumer: free-tier-customer config: minute: 60 hour: 1000
Use Case 2: Microservices Gateway
使用分析
Requirements:
- Service discovery
- Load balancing
- Circuit breaking
- Distributed tracing
- Centralized authentication
Implementation:
yaml
undefinedplugins:
- name: prometheus config: per_consumer: true
Service registry
请求转换(添加租户上下文)
services:
-
name: users-service url: http://users.internal:8001
-
name: orders-service url: http://orders.internal:8002
-
name: inventory-service url: http://inventory.internal:8003
plugins:
- name: request-transformer config: add: headers: - "X-Tenant-ID:$(consumer_custom_id)"
undefinedLoad balancing with health checks
用例2:微服务网关
upstreams:
- name: users-upstream healthchecks: active: http_path: /health healthy: interval: 5
需求:
- 服务发现
- 负载均衡
- 断路器
- 分布式追踪
- 集中认证
实现:
yaml
undefinedDistributed tracing
服务注册
plugins:
- name: zipkin config: http_endpoint: http://zipkin:9411/api/v2/spans
services:
-
name: users-service url: http://users.internal:8001
-
name: orders-service url: http://orders.internal:8002
-
name: inventory-service url: http://inventory.internal:8003
JWT authentication (single sign-on)
带健康检查的负载均衡
plugins:
- name: jwt config: claims_to_verify: - exp
undefinedupstreams:
- name: users-upstream healthchecks: active: http_path: /health healthy: interval: 5
Use Case 3: Mobile Backend
分布式追踪
Requirements:
- Versioned APIs
- GraphQL support
- Offline caching
- Push notifications
- Device-based rate limiting
Implementation:
yaml
undefinedplugins:
- name: zipkin config: http_endpoint: http://zipkin:9411/api/v2/spans
API versioning
JWT认证(单点登录)
routes:
-
name: api-v1 paths:
- /api/v1 service: mobile-api-v1
-
name: api-v2 paths:
- /api/v2 service: mobile-api-v2
plugins:
- name: jwt config: claims_to_verify: - exp
undefinedGraphQL endpoint
用例3:移动后端
plugins:
- name: graphql-proxy-cache-advanced route: graphql-route
需求:
- 版本化API
- GraphQL支持
- 离线缓存
- 推送通知
- 基于设备的限流
实现:
yaml
undefinedAggressive caching for mobile
API版本化
plugins:
- name: proxy-cache config: cache_ttl: 3600 strategy: redis
routes:
-
name: api-v1 paths:
- /api/v1 service: mobile-api-v1
-
name: api-v2 paths:
- /api/v2 service: mobile-api-v2
Device-based rate limiting
GraphQL端点
plugins:
- name: rate-limiting config: limit_by: header header_name: X-Device-ID minute: 100
undefinedplugins:
- name: graphql-proxy-cache-advanced route: graphql-route
Use Case 4: Public API
移动端激进缓存
Requirements:
- OAuth 2.0
- Developer portal
- API documentation
- Usage analytics
- Monetization
Implementation:
yaml
undefinedplugins:
- name: proxy-cache config: cache_ttl: 3600 strategy: redis
OAuth 2.0
基于设备的限流
plugins:
- name: oauth2 config: scopes: - read - write - admin enable_authorization_code: true
plugins:
- name: rate-limiting config: limit_by: header header_name: X-Device-ID minute: 100
undefinedDeveloper portal
用例4:公开API
routes:
- name: developer-docs
paths:
- /docs service: developer-portal
需求:
- OAuth 2.0
- 开发者门户
- API文档
- 使用分析
- 商业化
实现:
yaml
undefinedUsage tracking
OAuth 2.0
plugins:
- name: prometheus config: per_consumer: true
plugins:
- name: oauth2 config: scopes: - read - write - admin enable_authorization_code: true
Billing integration
开发者门户
routes:
- name: developer-docs
paths:
- /docs service: developer-portal
Use Case 5: Legacy Modernization
使用追踪
Requirements:
- REST to GraphQL
- Protocol translation
- Request/response transformation
- Gradual migration
- Backward compatibility
Implementation:
yaml
undefinedplugins:
- name: prometheus config: per_consumer: true
GraphQL facade over REST
计费集成
plugins:
- name: graphql-proxy-cache-advanced
SOAP to REST transformation
用例5:遗留系统现代化
plugins:
- name: request-transformer-advanced
config:
Transform REST to SOAP
replace: headers: - "Content-Type:text/xml"
需求:
- REST转GraphQL
- 协议转换
- 请求/响应转换
- 逐步迁移
- 向后兼容
实现:
yaml
undefinedVersion migration (route legacy to new)
REST之上的GraphQL门面
upstreams:
- name: api-upstream
targets:
- target: legacy-api:8001 weight: 20 # 20% legacy
- target: new-api:8002 weight: 80 # 80% new
undefinedplugins:
- name: graphql-proxy-cache-advanced
Quick Reference
SOAP转REST转换
Essential Commands
—
bash
undefinedplugins:
- name: request-transformer-advanced
config:
将REST转换为SOAP
replace: headers: - "Content-Type:text/xml"
Declarative configuration
版本迁移(路由遗留流量到新服务)
deck sync -s kong.yaml
upstreams:
- name: api-upstream
targets:
- target: legacy-api:8001 weight: 20 # 20%遗留流量
- target: new-api:8002 weight: 80 # 80%新流量
undefinedDatabase migrations
快速参考
—
常用命令
kong migrations bootstrap
kong migrations up
bash
undefinedStart Kong
声明式配置同步
kong start
deck sync -s kong.yaml
Reload configuration
数据库迁移
kong reload
kong migrations bootstrap
kong migrations up
Health check
启动Kong
kong start
List services
重载配置
kong reload
List routes
健康检查
List plugins
列出服务
undefinedConfiguration Templates
列出路由
Minimal Service:
yaml
services:
- name: my-service
url: http://api.internal:8001
routes:
- name: my-route
service: my-service
paths:
- /apiProduction Service:
yaml
services:
- name: production-service
url: http://api.internal:8001
protocol: http
retries: 5
connect_timeout: 5000
read_timeout: 60000
write_timeout: 60000
upstreams:
- name: production-upstream
algorithm: consistent-hashing
hash_on: header
hash_on_header: X-User-ID
healthchecks:
active:
http_path: /health
healthy:
interval: 5
successes: 2
unhealthy:
http_failures: 3
timeouts: 3
targets:
- upstream: production-upstream
target: api-1:8001
- upstream: production-upstream
target: api-2:8001
routes:
- name: production-route
service: production-service
paths:
- /api
protocols:
- https
strip_path: true
preserve_host: false
plugins:
- name: rate-limiting
route: production-route
config:
minute: 1000
policy: redis
- name: jwt
route: production-route
- name: cors
route: production-route
- name: prometheus
route: production-routeResources
列出插件
- Kong Documentation: https://docs.konghq.com/
- Kong Gateway: https://konghq.com/kong/
- Kong Plugin Hub: https://docs.konghq.com/hub/
- Kong Admin API: https://docs.konghq.com/gateway/latest/admin-api/
- decK (Declarative Config): https://docs.konghq.com/deck/
- Kong Ingress Controller: https://docs.konghq.com/kubernetes-ingress-controller/
- Kong Community: https://discuss.konghq.com/
Skill Version: 1.0.0
Last Updated: October 2025
Skill Category: API Gateway, Microservices, Traffic Management
Compatible With: Kong Gateway 3.x, Kubernetes, Docker, Cloud Platforms
undefined—
配置模板
—
最小服务配置:
yaml
services:
- name: my-service
url: http://api.internal:8001
routes:
- name: my-route
service: my-service
paths:
- /api生产级服务配置:
yaml
services:
- name: production-service
url: http://api.internal:8001
protocol: http
retries: 5
connect_timeout: 5000
read_timeout: 60000
write_timeout: 60000
upstreams:
- name: production-upstream
algorithm: consistent-hashing
hash_on: header
hash_on_header: X-User-ID
healthchecks:
active:
http_path: /health
healthy:
interval: 5
successes: 2
unhealthy:
http_failures: 3
timeouts: 3
targets:
- upstream: production-upstream
target: api-1:8001
- upstream: production-upstream
target: api-2:8001
routes:
- name: production-route
service: production-service
paths:
- /api
protocols:
- https
strip_path: true
preserve_host: false
plugins:
- name: rate-limiting
route: production-route
config:
minute: 1000
policy: redis
- name: jwt
route: production-route
- name: cors
route: production-route
- name: prometheus
route: production-route—
资源
—
- Kong文档:https://docs.konghq.com/
- Kong网关:https://konghq.com/kong/
- Kong插件中心:https://docs.konghq.com/hub/
- Kong Admin API:https://docs.konghq.com/gateway/latest/admin-api/
- decK(声明式配置):https://docs.konghq.com/deck/
- Kong Ingress Controller:https://docs.konghq.com/kubernetes-ingress-controller/
- Kong社区:https://discuss.konghq.com/
技能版本:1.0.0
最后更新:2025年10月
技能分类:API网关、微服务、流量管理
兼容版本:Kong网关3.x、Kubernetes、Docker、云平台