api-gateway-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API 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

网关核心组件

  1. Services: Upstream APIs that the gateway proxies to
  2. Routes: Request matching rules that determine service routing
  3. Upstreams: Load balancer configurations for service instances
  4. Plugins: Extensible middleware for features (auth, logging, etc.)
  5. Consumers: API clients with authentication credentials
  6. Certificates: SSL/TLS certificates for secure communication
  7. SNIs: Server Name Indication for multi-domain SSL
  1. Services:网关代理的上游API
  2. Routes:决定服务路由的请求匹配规则
  3. Upstreams:服务实例的负载均衡配置
  4. Plugins:扩展功能的可插拔中间件(认证、日志等)
  5. Consumers:带有认证凭证的API客户端
  6. Certificates:用于安全通信的SSL/TLS证书
  7. 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
undefined

Users 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 upstream
service: 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
undefined

V1 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"
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"
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:**
```yaml
routes:
  • name: api-v1-route paths:
    • /api headers: X-API-Version:
      • "1"
      • "1.0" service: api-v1

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
undefined
routes:
  • name: api-v2-route paths:
    • /api headers: X-API-Version:
      • "2"
      • "2.0" service: api-v2

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
undefined
routes:
  • name: api-default paths:
    • /api service: api-v1

**高级Header路由:**
```yaml

Read 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
undefined

Write 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
undefined

Pattern 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
undefined
service: 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
undefined

Tenant 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
undefined

Wildcard for dynamic tenants

租户A

routes:
  • name: dynamic-tenant hosts:
    • "*.api.example.com" service: multi-tenant-api
undefined
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: tenant-a-api

Pattern 5: Weighted Routing (Canary Deployments)

租户B

Gradually shift traffic between service versions.
Implementation:
yaml
undefined
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 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% v2
routes:
  • name: dynamic-tenant hosts:
    • "*.api.example.com" service: multi-tenant-api
undefined

Rate 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:
  • local
    : In-memory, single node (not cluster-safe)
  • cluster
    : Shared across Kong nodes via database
  • redis
    : High-performance distributed limiting via Redis
逐步在服务版本间切换流量。
实现方式:
yaml
undefined

Pattern 2: Consumer-Specific Rate Limiting

创建两个上游环境,按权重分配流量

Different limits for different API consumers (tiers).
Use Case: Freemium model with tiered pricing
Configuration:
yaml
undefined
upstream: 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
  1. 初始:100% v1, 0% v2
  2. 阶段1:90% v1, 10% v2(监控指标)
  3. 阶段2:75% v1, 25% v2
  4. 阶段3:50% v1, 50% v2
  5. 阶段4:25% v1, 75% v2
  6. 完成:0% v1, 100% v2
undefined

Premium 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
    :内存存储,单节点(不支持集群)
  • cluster
    :通过数据库在Kong节点间共享
  • redis
    :通过Redis实现高性能分布式限流

Enterprise tier (unlimited)

模式2:消费者专属限流

consumer: username: enterprise-user-789
为不同API消费者设置不同限流规则(分级)。
适用场景: 免费增值模式,分级定价
配置:
yaml
undefined

No rate limiting plugin for enterprise

免费版消费者

undefined
consumer: 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
undefined
consumer: 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
undefined

Health check - no limits

模式3:端点专属限流

routes:
  • name: health-route paths:
    • /health
为不同API端点设置不同限流规则。
适用场景: 保护高开销操作,同时允许低开销操作的高并发
配置:
yaml
undefined

No rate limiting plugin

高开销搜索端点 - 严格限流

undefined
routes:
  • 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: 0
Sliding 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: 1000000
routes:
  • 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
undefined
undefined

Enable 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: 1000000

Add 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/users
Best 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
undefined

Pattern 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 max
plugins:
  • 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.signature
consumers:
  • 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 days
keyauth_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.signature

2. 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-configuration
Multi-Provider Configuration:
yaml
undefined
oauth2_credentials:
  • consumer: third-party-app name: "合作伙伴集成" client_id: client_abc123 client_secret: secret_xyz789 redirect_uris:

**授权码流程:**
```bash

Google 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:
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

Okta 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
undefined

Pattern 5: mTLS (Mutual TLS) Authentication

Google OIDC

Certificate-based authentication for service-to-service security.
Use Case: Microservices mutual authentication, B2B integrations
Configuration:
yaml
undefined
plugins:
  • 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:

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
undefined

Create consumer mapped to client certificate

模式5:mTLS(双向TLS)认证

consumers:
  • username: service-a custom_id: service-a-001
基于证书的服务间安全认证。
适用场景: 微服务间双向认证、B2B集成
配置:
yaml
undefined

Map certificate to consumer

启用mTLS插件

mtls_auth_credentials:
  • consumer: service-a subject_name: CN=service-a,O=MyOrg
undefined
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 # 或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: 100
ca_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: 200
Weight 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:8001
Hashing Options:
  • hash_on: none
    - Random distribution
  • hash_on: consumer
    - Hash by authenticated consumer
  • hash_on: ip
    - Hash by client IP
  • hash_on: header
    - Hash by specified header value
  • hash_on: cookie
    - Hash by cookie value
  • hash_on: path
    - Hash by request path
Use Cases by Hash Type:
  • User sessions:
    hash_on: header
    (X-User-ID)
  • Geographic routing:
    hash_on: ip
  • Tenant isolation:
    hash_on: header
    (X-Tenant-ID)
  • Shopping carts:
    hash_on: cookie
    (session_id)
mtls_auth_credentials:
  • consumer: service-a subject_name: CN=service-a,O=MyOrg
undefined

Pattern 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:8001
When 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: 100

Pattern 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
    :按认证消费者哈希
  • hash_on: ip
    :按客户端IP哈希
  • hash_on: header
    :按指定Header哈希
  • hash_on: cookie
    :按Cookie哈希
  • hash_on: path
    :按请求路径哈希
按哈希类型的适用场景:
  • 用户会话:
    hash_on: header
    (X-User-ID)
  • 地理路由:
    hash_on: ip
  • 租户隔离:
    hash_on: header
    (X-Tenant-ID)
  • 购物车:
    hash_on: cookie
    (session_id)

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: 30000
Timeout 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: 2

Pattern 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.5
Retry Schedule:
Attempt 1: Immediate
Attempt 2: 2s + jitter
Attempt 3: 4s + jitter
Attempt 4: 8s + jitter
Attempt 5: 16s + jitter
Idempotency 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: true
upstreams:
  • 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: true

Request/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严格限制
undefined

Pattern 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: memory

Security 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'"
undefined
upstreams:
  • name: api-upstream slots: 1000 # 限制并发连接数
undefined

Pattern 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:
undefined
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'"
undefined

Pattern 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: memory

Caching 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:26379
graphql_schemas:
undefined

Pattern 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
undefined

Pattern 3: Cache Invalidation

gRPC转HTTP/JSON

Purge cache on-demand or based on events.
Use Case: Update cache when data changes
Configuration:
yaml
undefined
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

Admin 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:26379

Purge 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: true

TTL-based expiration

模式3:缓存失效

plugins:
  • name: proxy-cache config: cache_ttl: 60 # Short TTL for frequently updated data
按需或基于事件清除缓存。
适用场景: 数据变更时更新缓存
配置:
yaml
undefined

Event-based invalidation (custom plugin)

Admin API清除缓存

plugins:
  • name: custom-cache-invalidator config: invalidate_on: - POST - PUT - PATCH - DELETE propagate: true # Clear related caches
undefined
POST /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)
Database
Configuration:
yaml
undefined
POST /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"
undefined
plugins:
  • name: custom-cache-invalidator config: invalidate_on: - POST - PUT - PATCH - DELETE propagate: true # 清除相关缓存
undefined

Pattern 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
undefined

Tag 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
undefined
plugins:
  • name: proxy-cache config: cache_control: true # 遵循上游Cache-Control vary_headers: - "Cache-Control"
undefined

Security 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: false
Wildcard CORS (Development Only):
yaml
plugins:
  - name: cors
    config:
      origins:
        - "*"
      methods:
        - "*"
      headers:
        - "*"
      credentials: false  # Must be false with wildcard origins
为缓存打标签以实现细粒度失效。
适用场景: 高效失效相关资源
配置:
yaml
undefined

Pattern 2: IP Restriction

用代理键标记响应

Allow or deny based on IP addresses.
Use Case: Restrict admin APIs to office IPs
Configuration:
yaml
undefined
plugins:
  • 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
undefined

Blacklist 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时必须为false

Admin 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
undefined

Pattern 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: 10000
plugins:
  • 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: 1
plugins:
  • name: ip-restriction config: deny: - 1.2.3.4 - 5.6.7.0/24

**与认证结合:**
```yaml

Pattern 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: 403
plugins:
  • name: ip-restriction route: admin-api config: allow: - 10.0.0.0/8
  • name: key-auth route: admin-api
undefined

Observability 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: 10000

JSON 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: 1

Elasticsearch

模式5:WAF(Web应用防火墙)

plugins:
防护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: 403

Splunk

可观测性模式

模式1:请求日志

plugins:
记录所有API请求用于审计与调试。
适用场景: 合规性、调试、分析
配置:
yaml
plugins:
  - name: file-log
    config:
      path: /var/log/kong/requests.log
      reopen: true

Datadog

JSON结构化日志

plugins:
  • name: datadog config: host: datadog-agent port: 8125
undefined
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')"

**多目标日志:**
```yaml

Pattern 2: Distributed Tracing

Elasticsearch

Track requests across microservices.
Use Case: Diagnose latency, understand request flow
Configuration:
yaml
undefined
plugins:

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:

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
        - tracestate
plugins:
  • name: datadog config: host: datadog-agent port: 8125
undefined

Pattern 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
undefined

Expose /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
        - tracestate

Latency

模式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: true

Bandwidth

暴露/metrics端点

kong_bandwidth_bytes{type,service,route}
routes:
  • name: metrics paths:
    • /metrics service: prometheus-service

**可用指标:**

Connections

请求数

kong_datastore_reachable kong_nginx_connections_total{state}
undefined
kong_http_requests_total{service,route,code}

Pattern 4: Health Checks

延迟

Expose health check endpoints.
Use Case: Kubernetes liveness/readiness probes
Configuration:
yaml
undefined
kong_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}
undefined

Upstream health aggregation

模式4:健康检查

plugins:
  • name: upstream-health-check config: healthy_threshold: 2 unhealthy_threshold: 3
undefined
暴露健康检查端点。
适用场景: Kubernetes存活/就绪探针
配置:
yaml
undefined

Pattern 5: Error Tracking

网关健康检查

Track and report errors to monitoring systems.
Use Case: Proactive error detection and alerting
Configuration:
yaml
undefined
routes:
  • name: health paths:
    • /health plugins:
    • name: request-termination config: status_code: 200 message: "OK"

Sentry integration

详细状态

plugins:
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
undefined
plugins:
  • name: upstream-health-check config: healthy_threshold: 2 unhealthy_threshold: 3
undefined

Multi-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 overrides
Configuration:
yaml
undefined
追踪并向监控系统报告错误。
适用场景: 主动错误检测与告警
配置:
yaml
undefined

base.yaml

Sentry集成

_format_version: "3.0"
services:
routes:
  • name: users-route service: users-api paths:
    • /users
plugins:

production.yaml

自定义错误日志

_format_version: "3.0"
services:
plugins:
  • name: rate-limiting service: users-api config: minute: 1000
undefined
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
undefined

Pattern 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
undefined

Blue 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:
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:
plugins:
  • name: rate-limiting service: users-api config: minute: 1000
undefined

Route points to active environment

模式2:蓝绿部署

services:
  • name: api-service host: api-blue # Switch to api-green for deployment
零停机部署,支持即时回滚。
适用场景: 安全的生产部署
配置:
yaml
undefined

Rollback: Switch service.host back to api-blue

蓝色环境(当前生产)

undefined
upstreams:
  • 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
undefined
upstreams:
  • 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
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
undefined
undefined

Pattern 4: Feature Flags

模式3:金丝雀发布

Enable/disable features dynamically.
Use Case: A/B testing, gradual feature rollout
Configuration:
yaml
undefined
逐步发布并监控。
适用场景: 新版本风险缓解
配置:
yaml
undefined

Feature flag via header

带权重的金丝雀路由

routes:
  • name: new-feature paths:
    • /api/new-feature headers: X-Feature-Flag:
      • "new-dashboard" service: new-feature-service
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%流量,完成发布
undefined

Default route (feature disabled)

模式4:功能标记

routes:
  • name: old-feature paths:
    • /api/new-feature service: old-feature-service
动态启用/禁用功能。
适用场景: A/B测试,逐步功能发布
配置:
yaml
undefined

Consumer-based feature flags

基于Header的功能标记

plugins:
  • name: request-transformer consumer: beta-users config: add: headers: - "X-Feature-Flags:new-dashboard,advanced-search"
undefined
routes:
  • name: new-feature paths:
    • /api/new-feature headers: X-Feature-Flag:
      • "new-dashboard" service: new-feature-service

Pattern 5: Multi-Region Deployment

默认路由(功能禁用)

Route to nearest region for low latency.
Use Case: Global API with regional failover
Configuration:
yaml
undefined
routes:
  • 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"
undefined

EU region

模式5:多区域部署

upstreams:
  • name: api-eu targets:
    • target: api-eu-west:8001
    • target: api-eu-central:8001
将请求路由至最近区域以降低延迟。
适用场景: 全球API,区域故障转移
配置:
yaml
undefined

Geographic 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
undefined
upstreams:
  • name: api-us targets:
    • target: api-us-east:8001
    • target: api-us-west:8001

Best Practices

欧洲区域

Architecture Design

  1. Single Responsibility: Gateway handles cross-cutting concerns only
  2. Stateless Design: Keep gateway stateless for horizontal scaling
  3. Declarative Configuration: Use YAML/JSON for version-controlled config
  4. Database-Less Mode: Use DB-less for simpler deployments
  5. 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)

  1. Defense in Depth: Layer multiple security mechanisms
  2. Least Privilege: Minimal permissions for consumers
  3. Secrets Management: Never hardcode credentials
  4. TLS Everywhere: Encrypt all traffic (client and upstream)
  5. Rate Limiting: Always protect public endpoints
  6. Input Validation: Validate all request data
  7. 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
undefined

Performance Optimization

最佳实践

架构设计

  1. Enable Caching: Cache responses aggressively
  2. Connection Pooling: Reuse upstream connections
  3. Load Balancing: Distribute load evenly
  4. Health Checks: Remove unhealthy targets quickly
  5. Timeouts: Set appropriate timeouts to prevent hangs
  6. Monitoring: Track latency, errors, throughput
  7. Resource Limits: Set memory and connection limits
  1. 单一职责:网关仅处理横切关注点
  2. 无状态设计:保持网关无状态以支持水平扩展
  3. 声明式配置:使用YAML/JSON进行版本控制的配置
  4. 无DB模式:使用无DB模式简化部署
  5. 插件极简:仅启用必要插件

Operational Excellence

安全最佳实践

  1. Logging: Structured logging for all requests
  2. Monitoring: Comprehensive metrics collection
  3. Alerting: Alert on anomalies and errors
  4. Documentation: Document all routes and plugins
  5. Testing: Test gateway config in staging
  6. Versioning: Version control all configurations
  7. Disaster Recovery: Plan for failover scenarios
  1. 纵深防御:多层安全机制
  2. 最小权限:为消费者分配最小权限
  3. 密钥管理:切勿硬编码凭证
  4. 全链路TLS:加密所有流量(客户端与上游)
  5. 限流:始终保护公开端点
  6. 输入验证:验证所有请求数据
  7. 定期更新:保持Kong与插件为最新版本

Plugin Strategy

性能优化

  1. Order Matters: Plugins execute in specific order
  2. Scope Appropriately: Global, service, route, or consumer
  3. Test Thoroughly: Test plugin combinations
  4. Monitor Impact: Track plugin performance overhead
  5. 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)
  1. 启用缓存:积极缓存响应
  2. 连接池:复用上游连接
  3. 负载均衡:均匀分发负载
  4. 健康检查:快速移除不健康实例
  5. 超时设置:设置合理超时防止挂起
  6. 监控:追踪延迟、错误、吞吐量
  7. 资源限制:设置内存与连接限制

Configuration Management

运维卓越

  1. Version Control: Git for all configurations
  2. Environment Parity: Consistent configs across environments
  3. Automated Deployment: CI/CD for configuration changes
  4. Validation: Validate configs before applying
  5. Rollback Plan: Quick rollback on issues
  6. Change Log: Document all configuration changes
  1. 日志:所有请求使用结构化日志
  2. 监控:全面的指标收集
  3. 告警:异常与错误告警
  4. 文档:记录所有路由与插件
  5. 测试:在Staging环境测试网关配置
  6. 版本控制:所有配置纳入版本控制
  7. 灾难恢复:制定故障转移计划

Scaling Guidelines

插件策略

  1. Horizontal Scaling: Add more Kong nodes
  2. Database Scaling: Scale PostgreSQL separately
  3. Cache Offloading: Use Redis for distributed caching
  4. Regional Deployment: Deploy close to users
  5. CDN Integration: Offload static content
  6. Connection Limits: Set per-worker limits
  1. 顺序重要:插件按特定顺序执行
  2. 作用域恰当:全局、服务、路由或消费者级
  3. 充分测试:测试插件组合
  4. 监控影响:追踪插件性能开销
  5. 自定义插件:为独特需求编写自定义插件
插件执行顺序:
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
  1. 版本控制:所有配置使用Git管理
  2. 环境一致性:跨环境保持配置一致
  3. 自动化部署:CI/CD配置变更
  4. 验证:应用前验证配置
  5. 回滚计划:配置变更的快速回滚
  6. 变更日志:记录所有配置变更

Tenant identification

扩展指南

plugins:
  • name: key-auth config: key_names: - X-API-Key
  1. 水平扩展:添加更多Kong节点
  2. 数据库扩展:独立扩展PostgreSQL
  3. 缓存卸载:使用Redis进行分布式缓存
  4. 区域部署:部署在靠近用户的区域
  5. CDN集成:卸载静态内容
  6. 连接限制:设置每工作进程的连接限制

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
undefined

Usage 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)"
undefined
consumers:
  • 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
undefined
plugins:
  • name: prometheus config: per_consumer: true

Service registry

请求转换(添加租户上下文)

services:
plugins:
  • name: request-transformer config: add: headers: - "X-Tenant-ID:$(consumer_custom_id)"
undefined

Load balancing with health checks

用例2:微服务网关

upstreams:
  • name: users-upstream healthchecks: active: http_path: /health healthy: interval: 5
需求:
  • 服务发现
  • 负载均衡
  • 断路器
  • 分布式追踪
  • 集中认证
实现:
yaml
undefined

Distributed tracing

服务注册

plugins:
services:

JWT authentication (single sign-on)

带健康检查的负载均衡

plugins:
  • name: jwt config: claims_to_verify: - exp
undefined
upstreams:
  • 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
undefined
plugins:

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
undefined

GraphQL endpoint

用例3:移动后端

plugins:
  • name: graphql-proxy-cache-advanced route: graphql-route
需求:
  • 版本化API
  • GraphQL支持
  • 离线缓存
  • 推送通知
  • 基于设备的限流
实现:
yaml
undefined

Aggressive 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
undefined
plugins:
  • 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
undefined
plugins:
  • 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
undefined

Developer portal

用例4:公开API

routes:
  • name: developer-docs paths:
    • /docs service: developer-portal
需求:
  • OAuth 2.0
  • 开发者门户
  • API文档
  • 使用分析
  • 商业化
实现:
yaml
undefined

Usage 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

开发者门户

plugins:
undefined
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
undefined
plugins:
  • name: prometheus config: per_consumer: true

GraphQL facade over REST

计费集成

plugins:
  • name: graphql-proxy-cache-advanced
plugins:
undefined

SOAP to REST transformation

用例5:遗留系统现代化

plugins:
  • name: request-transformer-advanced config:

    Transform REST to SOAP

    replace: headers: - "Content-Type:text/xml"
需求:
  • REST转GraphQL
  • 协议转换
  • 请求/响应转换
  • 逐步迁移
  • 向后兼容
实现:
yaml
undefined

Version 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
undefined
plugins:
  • name: graphql-proxy-cache-advanced

Quick Reference

SOAP转REST转换

Essential Commands

bash
undefined
plugins:
  • 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%新流量
undefined

Database migrations

快速参考

常用命令

kong migrations bootstrap kong migrations up
bash
undefined

Start Kong

声明式配置同步

kong start
deck sync -s kong.yaml

Reload configuration

数据库迁移

kong reload
kong migrations bootstrap kong migrations up

Health check

启动Kong

List services

重载配置

List routes

健康检查

List plugins

列出服务

Configuration Templates

列出路由

Minimal Service:
yaml
services:
  - name: my-service
    url: http://api.internal:8001

routes:
  - name: my-route
    service: my-service
    paths:
      - /api
Production 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-route

Resources

列出插件


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

配置模板

最小服务配置:
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

资源


技能版本:1.0.0 最后更新:2025年10月 技能分类:API网关、微服务、流量管理 兼容版本:Kong网关3.x、Kubernetes、Docker、云平台