API网关是什么?微服务的统一入口点
DevOps

API网关是什么?微服务的统一入口点

API网关是位于客户端与微服务之间的唯一入口点,负责路由、认证、限流和SSL终止。深入了解其工作原理,比较Kong、NGINX、AWS API Gateway,并学习网关层安全实践。

系列文章: DevOps
  1. 1 API网关是什么?微服务的统一入口点
  2. 2 NAT是什么?计算机网络中的网络地址转换详解
  3. 3 GitLab CI/CD是什么?自动化构建、测试与部署流水线
  4. 4 Apache Kafka是什么?分布式事件流处理平台详解
  5. 5 Serverless是什么?FaaS、冷启动与何时选择无服务器架构
  6. 6 Subnet和CIDR是什么?IP网络分段与现代路由
  7. 7 什么是Kubernetes?当今最流行的容器编排平台
  8. 8 Proxy是什么?正向代理、反向代理与SOCKS5详解
  9. 9 什么是Nginx?集Web服务器、反向代理与负载均衡于一体
✦ 快速摘要
API网关是位于客户端与微服务之间的唯一入口点,负责路由、认证、限流和SSL终止。深入了解其工作原理,比较Kong、NGINX、AWS API Gateway,并学习网关层安全实践。
这篇文章怎么样?

API网关是客户端与背后数十个微服务之间的智能中间层:它接收所有请求、验证身份、执行限流、路由到正确的服务并返回结果——一切都通过单一入口点完成。本文解释什么是API网关、请求如何流经网关、比较最流行的解决方案,并介绍如何在网关层保护系统安全。

什么是API网关?

API网关是一个反向代理,充当整个微服务架构的统一入口点。客户端无需直接调用每个独立服务(每个服务有不同的地址和端口),只需知道一个地址——网关地址。

网关同时承担多项职责:

  • 路由: 根据路径(/users/* → 用户服务,/orders/* → 订单服务)、请求头或HTTP方法,将请求转发到正确的后端服务。
  • 认证与授权: 在请求到达服务之前验证JWT令牌、API密钥或会话。
  • 限流: 限制时间窗口内的请求数量,保护服务免受过载。
  • SSL终止: 在网关处理HTTPS,内部服务只需使用简单的HTTP。
  • 负载均衡: 将流量分发到同一服务的多个实例。
  • 请求/响应转换: 添加请求头、转换格式(XML ↔ JSON)、隐藏敏感字段。

没有网关,每个微服务都必须自己实现整个安全和认证层——导致代码重复、维护困难和更高的漏洞风险。

API网关的核心功能

一个生产就绪的API网关通常涵盖至少七个功能组:

1. 智能路由

网关解析请求的URL、HTTP方法和请求头,然后决定转发到哪个上游服务。某些网关支持路径重写——例如从客户端接收/v1/products,但转发/internal/catalog给服务。

2. 认证——身份验证

网关与身份提供商(IdP)集成,验证JWT令牌、OAuth2令牌或API密钥。如果令牌无效,网关立即返回401 Unauthorized,请求甚至不会到达后端服务。

3. 限流

常见机制:令牌桶滑动窗口。每个客户端(或API密钥)都有请求配额。超过阈值时,网关返回429 Too Many Requests并附带Retry-After头。

4. SSL/TLS终止

网关接受来自互联网的HTTPS连接,在此处终止TLS,然后以明文HTTP转发到内部服务。这减少了服务上的CPU负载,并简化了证书管理——只需在一处续期。

5. 负载均衡

网关可以通过轮询、最少连接或加权方式将请求分配到同一服务的多个实例,并通过健康检查自动移除无响应的实例。

6. 熔断器

当后端服务持续失败(超时、5xx错误)时,熔断器"断路"以停止发送更多请求——返回可控的错误,而不是让客户端等待。这有助于系统更快恢复。

7. 可观测性:日志、指标、追踪

网关是注入请求ID、收集延迟指标和转发集中式日志的理想位置。由于每个请求都经过这里,无需对每个服务单独进行仪表化。

请求流经API网关的过程

理解请求流有助于调试问题和设计系统:

客户端
  │
  ▼  (HTTPS)
┌─────────────────────────────┐
│        API网关               │
│  ┌──────────┐ ┌───────────┐ │
│  │ 认证检查  │ │   限流    │ │
│  └────┬─────┘ └─────┬─────┘ │
│       │             │       │
│  ┌────▼─────────────▼─────┐ │
│  │         路由器           │ │
│  └────┬──────────┬────────┘ │
└───────┼──────────┼──────────┘
        │          │
   (HTTP)          (HTTP)
        ▼          ▼
   用户服务      订单服务

详细处理步骤:

  1. 客户端发送请求 — 始终发送到网关地址,例如https://api.example.com/v1/orders
  2. SSL终止 — 网关解密TLS,请求变为内部明文HTTP。
  3. 认证检查 — 网关检查Authorization头中的JWT或API密钥。缺失或无效 → 401
  4. 限流检查 — 网关按键(IP、用户ID、API密钥)计数请求。超过阈值 → 429
  5. 路由 — 网关将路径与路由表匹配并选择上游服务。
  6. 负载均衡 — 如果服务有多个实例,网关按配置的算法选择一个。
  7. 转发请求 — 网关将请求(HTTP)发送到服务,添加X-Request-IDX-Forwarded-For等头。
  8. 服务处理 — 服务接收、处理并返回响应。
  9. 响应到客户端 — 网关接收服务的响应,可选择添加头(CORS、安全头),然后通过HTTPS返回给客户端。

对于优化良好的配置(无大量转换或缓存),网关总处理时间通常只需1–5毫秒。

最流行的API网关

从自托管到完全托管,有许多选择:

网关 平台 优势
Kong 自托管(NGINX + Lua) 丰富的插件生态系统,Admin API
NGINX 自托管 高性能,灵活配置
Traefik 自托管(Docker/K8s原生) 自动发现,内置Let's Encrypt
Envoy 自托管(C++) 极速,用于服务网格
AWS API Gateway 完全托管 Lambda/IAM集成,自动扩展
Kong Konnect 云托管 Kong引擎 + SaaS控制平面

Kong — 声明式配置

Kong允许将整个配置定义为YAML文件(声明式):

YAML
 1# kong.yaml — Kong声明式配置
 2_format_version: "3.0"
 3
 4services:
 5  - name: user-service
 6    url: http://user-svc:8080
 7    routes:
 8      - name: user-routes
 9        paths:
10          - /v1/users
11        strip_path: true
12    plugins:
13      - name: rate-limiting
14        config:
15          minute: 100          # 每个消费者每分钟最多100个请求
16          policy: local
17      - name: key-auth          # 需要API密钥
18        config:
19          key_names:
20            - apikey
21
22  - name: order-service
23    url: http://order-svc:8080
24    routes:
25      - name: order-routes
26        paths:
27          - /v1/orders
28        strip_path: true
29    plugins:
30      - name: rate-limiting
31        config:
32          minute: 50
33          policy: local
34      - name: jwt               # 需要JWT令牌
35        config:
36          secret_is_base64: false

使用以下命令应用配置:deck gateway sync kong.yaml

NGINX — location块

使用location块将NGINX作为基本反向代理:

nginx
 1# /etc/nginx/conf.d/api-gateway.conf
 2
 3upstream user_service {
 4    server user-svc-1:8080;
 5    server user-svc-2:8080;
 6    keepalive 32;              # 维护连接池
 7}
 8
 9upstream order_service {
10    server order-svc:8080;
11}
12
13server {
14    listen 443 ssl;
15    server_name api.example.com;
16
17    ssl_certificate     /etc/ssl/certs/api.crt;
18    ssl_certificate_key /etc/ssl/private/api.key;
19
20    # 路由 /v1/users → 用户服务
21    location /v1/users/ {
22        proxy_pass         http://user_service/;
23        proxy_set_header   Host $host;
24        proxy_set_header   X-Real-IP $remote_addr;
25        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
26        proxy_set_header   X-Request-ID $request_id;
27
28        # 限流(limit_req_zone在此块外定义)
29        limit_req zone=api_limit burst=20 nodelay;
30    }
31
32    # 路由 /v1/orders → 订单服务
33    location /v1/orders/ {
34        proxy_pass         http://order_service/;
35        proxy_set_header   Host $host;
36        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
37        limit_req zone=api_limit burst=10 nodelay;
38    }
39
40    # 网关健康检查端点
41    location /health {
42        return 200 "OK\n";
43        add_header Content-Type text/plain;
44    }
45}
46
47# 限流区 — 10MB共享内存,每IP每秒30个请求
48limit_req_zone $binary_remote_addr zone=api_limit:10m rate=30r/s;

深入了解NGINX及其反向代理配置方法

API网关 vs 负载均衡器 vs 反向代理

这三个概念经常被混淆,因为它们都位于服务"前面",但角色明显不同:

标准 API网关 负载均衡器 反向代理
目的 复杂API管理 流量分发 请求转发
路由 按路径、请求头、方法 仅按IP/端口 按路径/域名
认证 内置(JWT、OAuth2) 否(通常)
限流 否(通常)
请求转换 有限
使用场景 微服务API 水平扩展 简化访问
示例 Kong、AWS API GW AWS ALB、HAProxy NGINX、Caddy

何时使用哪个?

  • 只需要在相同实例间分配负载 → 负载均衡器(ALB、HAProxy)已足够且更快。
  • 需要SSL终止 + 静态文件服务 → 反向代理(NGINX)是合理选择。
  • 多个不同服务,需要集中认证/限流 → API网关是正确选择。
  • 大规模微服务架构 → 通常结合所有三层:最外层API网关,后面是每个服务集群的负载均衡器。

API网关的安全性

网关是实施集中安全的理想位置,而不是在每个服务中重复实现相同的安全措施:

JWT验证

JWT(JSON Web Token)是REST API中最常见的认证机制。网关使用公钥(RS256)或共享密钥(HS256)验证令牌签名:

YAML
 1# Kong JWT插件
 2plugins:
 3  - name: jwt
 4    config:
 5      key_claim_name: iss        # 包含密钥ID的声明
 6      claims_to_verify:
 7        - exp                    # 验证令牌未过期
 8        - nbf                    # 验证令牌已生效
 9      secret_is_base64: false
10      run_on_preflight: false    # 跳过OPTIONS请求(CORS预检)

当JWT有效时,网关将X-Consumer-IDX-Consumer-Username头添加到请求中,使后端服务无需自行解码令牌即可知道调用者身份。

OAuth2授权码流程

对于需要细粒度授权(基于scope)的API,网关与授权服务器集成:

客户端 → 网关: GET /v1/orders (Authorization: Bearer <access_token>)
网关 → 授权服务器: 检查令牌(验证scope "orders:read")
授权服务器 → 网关: {"active": true, "scope": "orders:read", "sub": "user123"}
网关 → 订单服务: 转发请求 + X-User-ID: user123
订单服务 → 网关: 200 OK + 响应体
网关 → 客户端: 200 OK + 响应体

API密钥认证

比JWT更简单——适合服务间API或第三方集成:

nginx
 1# NGINX — 通过X-API-Key请求头验证API密钥
 2map $http_x_api_key $api_key_valid {
 3    default         0;
 4    "secret-key-A"  1;
 5    "secret-key-B"  1;
 6}
 7
 8server {
 9    location /v1/data/ {
10        if ($api_key_valid = 0) {
11            return 403 '{"error": "Invalid API key"}';
12        }
13        proxy_pass http://data_service/;
14    }
15}

在实践中,API密钥应存储在密钥管理系统(Vault、AWS Secrets Manager)中,而不是硬编码在配置文件中。

网关安全最佳实践

  • 只开放HTTPS — 禁用HTTP或将所有请求重定向到HTTPS。
  • 验证输入 — 限制请求体大小,检查Content-Type。
  • 隐藏内部拓扑 — 不在响应头或错误信息中泄露内部服务名称。
  • 定期轮换API密钥和JWT密钥 — 与密钥管理工具集成。
  • 为面向互联网的网关启用WAF(Web应用防火墙)— 在网关层阻止SQLi、XSS和路径遍历攻击。

真实使用案例

Netflix Zuul(第一代API网关)

Netflix是最早推广API网关模式的公司之一。Zuul(用Java编写;Zuul 2添加了非阻塞I/O)每天处理数十亿请求,负责Netflix所有后端服务的动态路由、监控、弹性(Hystrix熔断器)和安全。

AWS API Gateway + Lambda(无服务器模式)

AWS上最常见的模式:API Gateway接收HTTP请求,触发Lambda函数处理业务逻辑——无需持久服务器。所有基础设施由AWS管理。

客户端 → AWS API Gateway → AWS Lambda → DynamoDB
                        ↑
               (自动扩展,通过Cognito认证,
                通过使用计划限流,
                通过CloudWatch记录日志)

低流量时成本极低(按请求付费),但在高流量时需要仔细计算,因为成本增长可能比EC2或Fargate更快。

Kong + Kubernetes Ingress

在Kubernetes环境中,Kong通常部署为Ingress控制器——与Kubernetes原生集成(使用CRD定义路由),同时保留所有Kong插件功能。

YAML
 1# Kong Ingress资源
 2apiVersion: networking.k8s.io/v1
 3kind: Ingress
 4metadata:
 5  name: api-routes
 6  annotations:
 7    konghq.com/plugins: rate-limiting,jwt-auth
 8spec:
 9  ingressClassName: kong
10  rules:
11    - host: api.example.com
12      http:
13        paths:
14          - path: /v1/users
15            pathType: Prefix
16            backend:
17              service:
18                name: user-service
19                port:
20                  number: 8080

深入了解NGINX——反向代理和负载均衡配置

JWT是什么?JSON Web Token在API认证中的工作原理

微服务是什么?服务拆分架构及其实际优势

常见问题Q&A
简单来说,什么是API网关?
API网关是一个反向代理,充当整个微服务系统的统一入口点(single entry point)。客户端只需要知道一个地址——网关地址,网关负责路由、认证并将请求转发到正确的后端服务,然后将聚合后的响应返回给客户端。
API网关与负载均衡器有何不同?
负载均衡器只是将流量分发到同一服务的多个相同实例上。而API网关则根据路径或请求头将流量路由到不同的服务,同时处理认证、限流和请求/响应转换。简单来说:负载均衡器是'分流',API网关是'智能大门'。
API网关中的限流是什么?
限流是一种机制,用于限制客户端在特定时间窗口内可以发送的请求数量。例如:每个API密钥每分钟最多允许100个请求。超过阈值时,网关返回HTTP 429 Too Many Requests。目的是保护后端服务免受过载,并防止滥用。
Kong还是NGINX更适合做API网关?
取决于您的需求。Kong(基于NGINX)专为API管理而设计——拥有丰富的插件生态系统(认证、限流、日志),通过Admin API管理,支持多服务声明式配置。原生NGINX更灵活、性能更高,但需要更多手动配置。如果需要管理许多复杂的API,Kong是更好的选择;如果只需要简单网关,NGINX已经足够。
什么时候应该使用AWS API Gateway?
当整个后端已经在AWS上时,AWS API Gateway是理想选择——尤其是与Lambda(无服务器)结合使用。它与IAM、Cognito、CloudWatch原生集成,并自动扩展。适合不想运维自有基础设施的项目。缺点是供应商锁定,以及流量大时成本可能较高。
API网关会使请求变慢吗?
会增加延迟,但通常只有1–5毫秒(对于优化良好的网关层)。Kong和Envoy采用异步I/O设计,可以以非常高的吞吐量运行。为减少延迟:将网关部署在靠近服务的位置(同一地区/数据中心),使用连接池,并为不经常变化的响应启用缓存。

An API Gateway is the intelligent intermediary between clients and the dozens of microservices behind it: it receives every request, validates identity, enforces rate limits, routes to the correct service and returns the result — all through a single entry point. This article explains what an API Gateway is, how a request flows through it, compares the most popular solutions and shows how to secure a system at the gateway layer.

What is an API Gateway?

An API Gateway is a reverse proxy that acts as the single entry point for an entire microservices architecture. Instead of clients calling each individual service directly (each with its own address and port), clients only need to know a single address — the gateway.

The gateway handles multiple responsibilities simultaneously:

  • Routing: Based on path (/users/* → User Service, /orders/* → Order Service), headers or HTTP method, it forwards requests to the correct backend service.
  • Authentication & Authorization: Validates JWT tokens, API keys or sessions before a request ever reaches a service.
  • Rate Limiting: Limits the number of requests within a time window to protect services from overload.
  • SSL Termination: Handles HTTPS at the gateway; internal services only need plain HTTP.
  • Load Balancing: Distributes traffic across multiple instances of the same service.
  • Request/Response Transformation: Adds headers, converts formats (XML ↔ JSON), hides sensitive fields.

Without a gateway, every microservice would have to implement its own security and authentication layer — leading to duplicated code, maintenance headaches and a higher risk of vulnerabilities.

Core Functions of an API Gateway

A production-ready API Gateway typically covers at least seven function groups:

1. Smart Routing

The gateway parses the URL, HTTP method and headers of a request, then decides which upstream to forward to. Some gateways support path rewriting — for example, receiving /v1/products from the client but forwarding /internal/catalog to the service.

2. Authentication — identity verification

The gateway integrates with an Identity Provider (IdP) to verify JWT tokens, OAuth2 tokens or API keys. If the token is invalid, the gateway immediately returns 401 Unauthorized without the request ever reaching a backend service.

3. Rate Limiting

Common mechanisms: token bucket or sliding window. Each client (or API key) has a request quota. When the threshold is exceeded, the gateway returns 429 Too Many Requests with a Retry-After header.

4. SSL/TLS Termination

The gateway accepts HTTPS connections from the internet, terminates TLS there, and forwards plain HTTP to internal services. This reduces CPU load on services and simplifies certificate management — you only need to renew in one place.

5. Load Balancing

The gateway can round-robin, least-connections or weighted-balance requests across multiple instances of the same service, with health checks to automatically remove unresponsive instances.

6. Circuit Breaker

When a backend service continuously fails (timeouts, 5xx errors), the circuit breaker "trips" to stop sending more requests — returning a controlled error rather than letting clients hang. This helps the system recover faster.

7. Observability: Logging, Metrics, Tracing

The gateway is the ideal place to inject request IDs, collect latency metrics and forward centralised logs. Since every request passes through here, there is no need to instrument each individual service.

Request Flow through an API Gateway

Understanding the request flow helps with debugging and system design:

Client
  │
  ▼  (HTTPS)
┌─────────────────────────────┐
│        API Gateway          │
│  ┌──────────┐ ┌───────────┐ │
│  │Auth Check│ │Rate Limit │ │
│  └────┬─────┘ └─────┬─────┘ │
│       │             │       │
│  ┌────▼─────────────▼─────┐ │
│  │       Router            │ │
│  └────┬──────────┬────────┘ │
└───────┼──────────┼──────────┘
        │          │
   (HTTP)          (HTTP)
        ▼          ▼
   User Service  Order Service

Detailed processing steps:

  1. Client sends request — always to the gateway address, e.g. https://api.example.com/v1/orders.
  2. SSL Termination — the gateway decrypts TLS; the request becomes plain internal HTTP.
  3. Authentication Check — the gateway checks the JWT or API key in the Authorization header. Missing or invalid → 401.
  4. Rate Limit Check — the gateway counts requests per key (IP, user ID, API key). Threshold exceeded → 429.
  5. Routing — the gateway matches the path against the route table and selects an upstream service.
  6. Load Balancing — if the service has multiple instances, the gateway selects one per the configured algorithm.
  7. Forward Request — the gateway sends the request (HTTP) to the service, adding headers like X-Request-ID and X-Forwarded-For.
  8. Service processes — the service receives, processes and returns a response.
  9. Response to client — the gateway receives the response from the service, optionally adds headers (CORS, security headers) and returns it to the client over HTTPS.

Total gateway processing time is typically only 1–5ms for a well-optimised setup without heavy transformation or caching.

There are many options ranging from self-hosted to fully managed:

Gateway Platform Strengths
Kong Self-hosted (NGINX + Lua) Rich plugin ecosystem, Admin API
NGINX Self-hosted High performance, flexible config
Traefik Self-hosted (Docker/K8s native) Auto-discovery, built-in Let's Encrypt
Envoy Self-hosted (C++) Extremely fast, used in service mesh
AWS API Gateway Fully managed Lambda/IAM integration, auto-scales
Kong Konnect Cloud managed Kong engine + SaaS control plane

Kong — declarative config

Kong lets you define the entire configuration as a YAML file (declarative):

YAML
 1# kong.yaml — Kong declarative configuration
 2_format_version: "3.0"
 3
 4services:
 5  - name: user-service
 6    url: http://user-svc:8080
 7    routes:
 8      - name: user-routes
 9        paths:
10          - /v1/users
11        strip_path: true
12    plugins:
13      - name: rate-limiting
14        config:
15          minute: 100          # max 100 req/min per consumer
16          policy: local
17      - name: key-auth          # require API key
18        config:
19          key_names:
20            - apikey
21
22  - name: order-service
23    url: http://order-svc:8080
24    routes:
25      - name: order-routes
26        paths:
27          - /v1/orders
28        strip_path: true
29    plugins:
30      - name: rate-limiting
31        config:
32          minute: 50
33          policy: local
34      - name: jwt               # require JWT token
35        config:
36          secret_is_base64: false

Apply the config with: deck gateway sync kong.yaml

NGINX — location block

NGINX as a basic reverse proxy using location blocks:

nginx
 1# /etc/nginx/conf.d/api-gateway.conf
 2
 3upstream user_service {
 4    server user-svc-1:8080;
 5    server user-svc-2:8080;
 6    keepalive 32;              # maintain connection pool
 7}
 8
 9upstream order_service {
10    server order-svc:8080;
11}
12
13server {
14    listen 443 ssl;
15    server_name api.example.com;
16
17    ssl_certificate     /etc/ssl/certs/api.crt;
18    ssl_certificate_key /etc/ssl/private/api.key;
19
20    # Route /v1/users → User Service
21    location /v1/users/ {
22        proxy_pass         http://user_service/;
23        proxy_set_header   Host $host;
24        proxy_set_header   X-Real-IP $remote_addr;
25        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
26        proxy_set_header   X-Request-ID $request_id;
27
28        # Rate limiting (limit_req_zone defined outside this block)
29        limit_req zone=api_limit burst=20 nodelay;
30    }
31
32    # Route /v1/orders → Order Service
33    location /v1/orders/ {
34        proxy_pass         http://order_service/;
35        proxy_set_header   Host $host;
36        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
37        limit_req zone=api_limit burst=10 nodelay;
38    }
39
40    # Gateway health check endpoint
41    location /health {
42        return 200 "OK\n";
43        add_header Content-Type text/plain;
44    }
45}
46
47# Rate limit zone — 10MB shared memory, 30 req/s per IP
48limit_req_zone $binary_remote_addr zone=api_limit:10m rate=30r/s;

Learn more about NGINX and how to configure a reverse proxy

API Gateway vs Load Balancer vs Reverse Proxy

These three concepts are often confused because they all sit "in front of" services, but their roles are clearly distinct:

Criterion API Gateway Load Balancer Reverse Proxy
Purpose Complex API management Traffic distribution Request forwarding
Routing By path, header, method By IP/port only By path/domain
Auth Built-in (JWT, OAuth2) No No (usually)
Rate Limiting Yes No No (usually)
Request Transform Yes No Limited
Use case Microservices API Horizontal scaling Simplified access
Examples Kong, AWS API GW AWS ALB, HAProxy NGINX, Caddy

When to use which?

  • Just need to spread load across identical instances → A Load Balancer (ALB, HAProxy) is sufficient and faster.
  • Need SSL termination + static file serving → A Reverse Proxy (NGINX) makes sense.
  • Multiple different services with centralised auth/rate-limiting → An API Gateway is the right choice.
  • Large-scale microservices architecture → Usually combines all three layers: API Gateway at the edge, Load Balancers per service cluster behind it.

Security at the API Gateway

The gateway is the ideal place to implement centralised security, rather than repeating the same implementation in every service:

JWT Validation

JWT (JSON Web Token) is the most common authentication mechanism in REST APIs. The gateway verifies the token's signature using a public key (RS256) or a shared secret (HS256):

YAML
 1# Kong JWT plugin
 2plugins:
 3  - name: jwt
 4    config:
 5      key_claim_name: iss        # claim that holds the key ID
 6      claims_to_verify:
 7        - exp                    # verify token has not expired
 8        - nbf                    # verify token is already valid
 9      secret_is_base64: false
10      run_on_preflight: false    # skip OPTIONS requests (CORS preflight)

When a JWT is valid, the gateway adds X-Consumer-ID and X-Consumer-Username headers to the request so backend services know who is calling without needing to decode the token themselves.

OAuth2 Authorization Code Flow

For APIs that need fine-grained authorisation (scope-based), the gateway integrates with an Authorization Server:

Client → Gateway: GET /v1/orders (Authorization: Bearer <access_token>)
Gateway → Auth Server: Introspect token (check scope "orders:read")
Auth Server → Gateway: {"active": true, "scope": "orders:read", "sub": "user123"}
Gateway → Order Service: Forward request + X-User-ID: user123
Order Service → Gateway: 200 OK + response body
Gateway → Client: 200 OK + response body

API Key Authentication

Simpler than JWT — suitable for server-to-server APIs or third-party integrations:

nginx
 1# NGINX — verify API key via X-API-Key header
 2map $http_x_api_key $api_key_valid {
 3    default         0;
 4    "secret-key-A"  1;
 5    "secret-key-B"  1;
 6}
 7
 8server {
 9    location /v1/data/ {
10        if ($api_key_valid = 0) {
11            return 403 '{"error": "Invalid API key"}';
12        }
13        proxy_pass http://data_service/;
14    }
15}

In practice, API keys should be stored in a secret store (Vault, AWS Secrets Manager) rather than hardcoded in config files.

Security best practices at the gateway

  • Expose HTTPS only — disable HTTP or redirect everything to HTTPS.
  • Validate input — limit request body size, check Content-Type.
  • Hide internal topology — never let internal service names leak via response headers or error messages.
  • Rotate API keys and JWT secrets regularly — integrate with secret management tooling.
  • Enable a WAF (Web Application Firewall) for internet-facing gateways — block SQLi, XSS and path traversal at the gateway layer.

Real-World Use Cases

Netflix Zuul (first-generation API Gateway)

Netflix was one of the earliest companies to popularise the API Gateway pattern. Zuul (written in Java; Zuul 2 adds non-blocking I/O) handles billions of requests per day, responsible for dynamic routing, monitoring, resiliency (Hystrix circuit breaker) and security across all of Netflix's backend services.

AWS API Gateway + Lambda (Serverless pattern)

The most common pattern on AWS: API Gateway receives HTTP requests, triggers a Lambda function to handle business logic — no persistent servers needed. All infrastructure is managed by AWS.

Client → AWS API Gateway → AWS Lambda → DynamoDB
                        ↑
               (auto-scale, auth via Cognito,
                rate-limit via usage plan,
                logging via CloudWatch)

Cost is very low at low traffic (pay-per-request), but needs careful calculation at high traffic as costs can grow faster than EC2 or Fargate.

Kong + Kubernetes Ingress

In Kubernetes environments, Kong is often deployed as an Ingress Controller — integrating natively with Kubernetes (using CRDs to define routes) while retaining all of Kong's plugin capabilities.

YAML
 1# Kong Ingress Resource
 2apiVersion: networking.k8s.io/v1
 3kind: Ingress
 4metadata:
 5  name: api-routes
 6  annotations:
 7    konghq.com/plugins: rate-limiting,jwt-auth
 8spec:
 9  ingressClassName: kong
10  rules:
11    - host: api.example.com
12      http:
13        paths:
14          - path: /v1/users
15            pathType: Prefix
16            backend:
17              service:
18                name: user-service
19                port:
20                  number: 8080

Learn more about NGINX — configuring a reverse proxy and load balancing

What is JWT? How JSON Web Token works in API authentication

What are Microservices? Service decomposition architecture and real-world benefits

Frequently Asked QuestionsQ&A
What is an API Gateway in simple terms?
An API Gateway is a reverse proxy that acts as the single entry point for an entire microservices system. Clients only need to know one address — the gateway — which then routes, authenticates and forwards requests to the correct backend service, then returns the aggregated response to the client.
How is an API Gateway different from a Load Balancer?
A Load Balancer distributes traffic across multiple identical instances of the same service. An API Gateway, by contrast, routes traffic to many different services based on path or headers, while also handling authentication, rate limiting and request/response transformation. In short: a Load Balancer 'distributes load', while an API Gateway is an 'intelligent front door'.
What is rate limiting in an API Gateway?
Rate limiting is a mechanism that restricts how many requests a client can send within a given time window. For example: allowing a maximum of 100 requests per minute per API key. When the threshold is exceeded, the gateway returns HTTP 429 Too Many Requests. The goal is to protect backend services from overload and prevent abuse.
Is Kong or NGINX a better API Gateway?
It depends on your requirements. Kong (built on NGINX) is purpose-designed for API management — it has a rich plugin ecosystem (auth, rate-limiting, logging), is managed via an Admin API and supports multi-service declarative config. Plain NGINX is more flexible and performant but requires more manual configuration. If you need to manage many complex APIs, Kong is the better choice; for a simple gateway, NGINX is sufficient.
When should I use AWS API Gateway?
AWS API Gateway is ideal when your entire backend already lives on AWS — especially when combined with Lambda (serverless). It integrates natively with IAM, Cognito, CloudWatch and scales automatically. It suits projects that do not want to operate their own infrastructure. Downsides are vendor lock-in and potentially high cost at scale.
Does an API Gateway slow down requests?
It adds latency, but typically only 1–5ms for a well-optimised gateway layer. Kong and Envoy are designed to run at very high throughput with async I/O. To minimise latency: deploy the gateway close to services (same region/datacenter), use connection pooling, and enable caching for responses that do not change frequently.