api-gateway-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Gateway Patterns

API Gateway 模式

Expert guidance for implementing API gateways with routing, authentication, traffic management, and service composition patterns for microservices architectures at scale.
为大规模微服务架构中实现具备路由、认证、流量管理和服务组合能力的API网关提供专业指导。

When to Use This Skill

适用场景

  • Implementing API gateway infrastructure for microservices
  • Designing Backend for Frontend (BFF) layers
  • Adding authentication and authorization at the gateway level
  • Implementing rate limiting, circuit breakers, and retry logic
  • Setting up service discovery and dynamic routing
  • Building API composition and aggregation layers
  • Managing cross-cutting concerns (logging, monitoring, CORS)
  • Evaluating gateway solutions (Kong, Nginx, Envoy, AWS API Gateway)
  • 为微服务实现API网关基础设施
  • 设计Backend for Frontend(BFF)层
  • 在网关层面添加认证与授权机制
  • 实现限流、断路器和重试逻辑
  • 配置服务发现与动态路由
  • 构建API组合与聚合层
  • 管理横切关注点(日志、监控、CORS)
  • 评估网关解决方案(Kong、Nginx、Envoy、AWS API Gateway)

Core Concepts

核心概念

Gateway Responsibilities

网关职责

Routing: Direct requests to appropriate backend services based on path, headers, or host Security: Centralized authentication, authorization, and API key validation Traffic Management: Rate limiting, circuit breakers, retry logic Composition: Aggregate multiple service calls into unified responses Transformation: Modify requests/responses for client optimization or legacy adaptation
路由:根据路径、请求头或主机将请求转发至对应的后端服务 安全:集中式认证、授权和API密钥验证 流量管理:限流、断路器、重试逻辑 组合:将多个服务调用聚合为统一响应 转换:修改请求/响应以优化客户端适配或兼容遗留系统

Architecture Patterns

架构模式

Single Gateway: One gateway for all clients (simple, potential bottleneck) BFF Pattern: Separate gateway per client type (mobile, web, admin) - optimized for each GraphQL Gateway: Schema stitching across services, client-driven data fetching Service Mesh: Distributed gateway pattern with sidecar proxies (Istio, Linkerd)
单一网关:为所有客户端提供统一网关(实现简单,但可能成为瓶颈) BFF模式:为不同客户端类型(移动端、网页端、管理端)分别设置网关——针对各端优化 GraphQL网关:跨服务的Schema拼接,支持客户端驱动的数据获取 服务网格:带边车代理的分布式网关模式(Istio、Linkerd)

Quick Reference

快速参考

TaskLoad reference
Routing strategies (path, header, host-based)
skills/api-gateway-patterns/references/routing-patterns.md
Request/response transformation
skills/api-gateway-patterns/references/transformation.md
API composition and aggregation
skills/api-gateway-patterns/references/composition.md
Authentication & authorization (JWT, OAuth, RBAC)
skills/api-gateway-patterns/references/authentication.md
Traffic management (rate limiting, circuit breakers)
skills/api-gateway-patterns/references/traffic-management.md
Backend for Frontend (BFF) pattern
skills/api-gateway-patterns/references/bff-pattern.md
Service discovery integration
skills/api-gateway-patterns/references/service-discovery.md
Gateway implementations (Kong, Nginx, Envoy, AWS)
skills/api-gateway-patterns/references/implementations.md
任务参考文档路径
路由策略(基于路径、请求头、主机)
skills/api-gateway-patterns/references/routing-patterns.md
请求/响应转换
skills/api-gateway-patterns/references/transformation.md
API组合与聚合
skills/api-gateway-patterns/references/composition.md
认证与授权(JWT、OAuth、RBAC)
skills/api-gateway-patterns/references/authentication.md
流量管理(限流、断路器)
skills/api-gateway-patterns/references/traffic-management.md
Backend for Frontend(BFF)模式
skills/api-gateway-patterns/references/bff-pattern.md
服务发现集成
skills/api-gateway-patterns/references/service-discovery.md
网关实现方案(Kong、Nginx、Envoy、AWS)
skills/api-gateway-patterns/references/implementations.md

Implementation Workflow

实施流程

Phase 1: Requirements Analysis

阶段1:需求分析

  1. Identify client types: Mobile, web, admin, partners
  2. Map service landscape: Catalog backend services and endpoints
  3. Define cross-cutting concerns: Auth, logging, monitoring, CORS
  4. Determine composition needs: Which endpoints require aggregation?
  5. Establish SLAs: Latency, throughput, availability targets
  1. 识别客户端类型:移动端、网页端、管理端、合作方
  2. 梳理服务版图:编目后端服务及端点
  3. 定义横切关注点:认证、日志、监控、CORS
  4. 确定组合需求:哪些端点需要聚合?
  5. 设定SLA:延迟、吞吐量、可用性指标

Phase 2: Gateway Design

阶段2:网关设计

  1. Choose architecture: Single gateway vs BFF vs GraphQL
  2. Select implementation: Kong, Nginx, Envoy, AWS API Gateway
  3. Design routing rules: Path-based, header-based, host-based
  4. Plan authentication: JWT, OAuth 2.0, API keys, or hybrid
  5. Define traffic policies: Rate limits, circuit breakers, timeouts
  1. 选择架构模式:单一网关 vs BFF vs GraphQL
  2. 选择实现方案:Kong、Nginx、Envoy、AWS API Gateway
  3. 设计路由规则:基于路径、请求头、主机
  4. 规划认证机制:JWT、OAuth 2.0、API密钥或混合模式
  5. 定义流量策略:限流、断路器、超时设置

Phase 3: Implementation

阶段3:落地实施

  1. Set up infrastructure: Deploy gateway instances, configure load balancer
  2. Implement routing: Configure service discovery and route definitions
  3. Add authentication: JWT validation, OAuth integration, API key management
  4. Apply traffic management: Rate limiting, circuit breakers, retry logic
  5. Enable observability: Distributed tracing, metrics, structured logging
  1. 搭建基础设施:部署网关实例,配置负载均衡器
  2. 实现路由功能:配置服务发现与路由规则
  3. 添加认证模块:JWT验证、OAuth集成、API密钥管理
  4. 应用流量管理:限流、断路器、重试逻辑
  5. 启用可观测性:分布式追踪、指标监控、结构化日志

Phase 4: Testing & Optimization

阶段4:测试与优化

  1. Load testing: Verify performance under expected and peak load
  2. Failure injection: Test circuit breakers and retry logic
  3. Security testing: Verify auth flows, token validation, RBAC policies
  4. Latency optimization: Cache strategies, connection pooling
  5. Monitor and tune: Adjust timeouts, limits based on real traffic
  1. 负载测试:验证预期及峰值负载下的性能
  2. 故障注入测试:测试断路器与重试逻辑
  3. 安全测试:验证认证流程、令牌校验、RBAC策略
  4. 延迟优化:缓存策略、连接池配置
  5. 监控与调优:根据真实流量调整超时时间、限流阈值

Best Practices

最佳实践

  1. Centralize Cross-Cutting Concerns: Authentication, logging, monitoring at gateway
  2. Keep Gateway Lightweight: Avoid complex business logic, delegate to services
  3. Implement Health Checks: Monitor upstream service health, remove unhealthy instances
  4. Use Circuit Breakers: Prevent cascading failures, fail fast
  5. Apply Rate Limiting: Protect services from overload, implement tiered limits
  6. Enable Observability: Distributed tracing, metrics, structured logging
  7. Version APIs: Support multiple API versions, plan deprecation
  8. Secure Communication: TLS everywhere, mutual TLS for service-to-service
  9. Cache Strategically: Response caching, but invalidate properly
  10. Test Resilience: Chaos engineering, failure injection, load testing
  1. 集中管理横切关注点:在网关层面统一处理认证、日志、监控
  2. 保持网关轻量化:避免复杂业务逻辑,将其委托给后端服务
  3. 实现健康检查:监控上游服务健康状态,剔除不健康实例
  4. 使用断路器:防止级联故障,快速失败
  5. 应用限流机制:保护服务避免过载,实现分层限流
  6. 启用可观测性:分布式追踪、指标监控、结构化日志
  7. API版本化:支持多版本API,规划废弃策略
  8. 安全通信:全链路TLS,服务间使用双向TLS
  9. 策略性缓存:响应缓存,但需确保正确失效
  10. 测试韧性:混沌工程、故障注入、负载测试

Common Mistakes

常见误区

  1. Business Logic in Gateway: Keep gateway focused on routing/security, not business rules
  2. Chatty Composition: Too many upstream calls (use BFF, GraphQL, or caching)
  3. Single Point of Failure: Deploy redundantly, use load balancers
  4. No Timeout Configuration: Always set connection/read timeouts to prevent hanging requests
  5. Ignoring Backpressure: Implement queue limits, graceful degradation
  6. Over-Aggregation: Don't make gateway do too much work (compute-heavy transformations)
  7. Inadequate Monitoring: Must track latency, errors, throughput at gateway level
  8. No Rate Limiting: Services will be overwhelmed eventually without protection
  9. Synchronous Everything: Use async patterns for non-critical operations
  10. No Version Strategy: Breaking changes break all clients simultaneously
  1. 在网关中嵌入业务逻辑:网关应专注于路由/安全,而非业务规则
  2. 频繁调用上游服务的组合:过多上游调用(可使用BFF、GraphQL或缓存优化)
  3. 单点故障:冗余部署,使用负载均衡器
  4. 未配置超时:务必设置连接/读取超时,避免请求挂起
  5. 忽略背压:实现队列限制、优雅降级
  6. 过度聚合:不要让网关承担过多工作(如计算密集型转换)
  7. 监控不足:必须在网关层面追踪延迟、错误、吞吐量
  8. 未设置限流:若无保护,服务最终会被压垮
  9. 全同步操作:非关键操作使用异步模式
  10. 无版本策略:破坏性变更会同时影响所有客户端

Resources

资源