API Gateway Complete Guide

Nếu bạn đã từng build hoặc làm việc với microservices, chắc chắn bạn đã gặp vấn đề này: client cần giao tiếp với nhiều backend service. Không có một entry point duy nhất thì sao? Mỗi client phải biết địa chỉ từng service, tự handle authentication riêng, rồi còn phải deal với đủ loại protocol và format khác nhau.
API gateway sinh ra để giải quyết chuyện đó. Nó là cánh cửa chính cho toàn bộ API traffic — một URL duy nhất, một chỗ authentication, một chỗ rate limiting, và routing thông minh đến tất cả backend service.
Trong bài Reverse Proxy, mình đã cover cách reverse proxy handle SSL termination, caching, và load balancing. API gateway làm tất cả những thứ đó cộng thêm các concern đặc thù cho API: authentication, request transformation, rate limiting theo API key, và response aggregation.
Thời gian: 1-2 giờ
Yêu cầu: Hiểu về REST API, HTTP, và reverse proxy
Bạn Sẽ Học Được Gì
✅ API gateway là gì và tại sao microservices cần nó
✅ API gateway khác gì reverse proxy
✅ Routing pattern — path-based, header-based, và versioned routing
✅ Authentication và authorization tại gateway
✅ Rate limiting — theo client, theo API key, theo endpoint
✅ Request/response transformation và aggregation
✅ Circuit breaking và resilience pattern
✅ Setup thực tế với Kong, AWS API Gateway, và Spring Cloud Gateway
1. API Gateway Là Gì?
API gateway là một server nằm giữa client và các backend service. Nó nhận tất cả API request, route đến đúng service, và trả về response.
Không có API gateway, mỗi client phải:
- Biết địa chỉ của từng service
- Tự handle authentication với mỗi service riêng
- Deal với các protocol và format khác nhau
- Tự implement retry logic và circuit breaking
- Handle API versioning cho từng service
Gateway tập trung hết tất cả vào một chỗ.
Nó Làm Gì?
Khi một request đến API gateway:
- Authenticate — validate API key, JWT token, hoặc OAuth token
- Authorize — kiểm tra client có quyền truy cập endpoint này không
- Rate limit — kiểm tra client đã vượt quota chưa
- Route — xác định backend service nào sẽ handle request này
- Transform — thay đổi format request nếu cần (header, body)
- Forward — gửi request đến backend service
- Aggregate — tùy chọn gộp response từ nhiều service lại
- Return — trả response về cho client
2. API Gateway vs Reverse Proxy
Reverse proxy và API gateway có phần chồng lấp khá nhiều. Khác biệt chính nằm ở cấp độ hoạt động.
| Khía cạnh | Reverse Proxy | API Gateway |
|---|---|---|
| Focus | Infrastructure (HTTP traffic) | Application (API management) |
| Routing | Path/host-based | Path, header, method, query param, version |
| Authentication | Basic (IP, client cert) | JWT, OAuth2, API key, OIDC |
| Rate limiting | Theo IP | Theo API key, theo user, theo endpoint |
| Transformation | Header manipulation | Request/response body transformation |
| Aggregation | Không | Gộp response từ nhiều service |
| API versioning | Không (manual) | Quản lý version tích hợp |
| Developer portal | Không | API docs, key management, usage analytics |
| Ví dụ | Nginx, HAProxy | Kong, AWS API Gateway, Apigee |
Nghĩ đơn giản thế này:
- Reverse proxy: "Route cái HTTP request này đến đúng server"
- API gateway: "Authenticate API consumer này, check rate limit, transform request, route nó, rồi log usage"
Trên thực tế, nhiều tool làm mờ ranh giới này. Nginx với Lua plugin có thể hoạt động như API gateway. Kong được build trên Nginx nhưng thêm API management feature. Sự khác biệt nằm ở capability, không phải category cứng nhắc.
3. Core Feature
3.1 Request Routing
Feature cơ bản nhất — route request đến đúng backend service.
Path-based routing:
GET /api/users/123 → User Service
GET /api/orders/456 → Order Service
POST /api/payments → Payment Service
GET /api/notifications → Notification ServiceHeader-based routing:
X-API-Version: v1 → Legacy Service
X-API-Version: v2 → New ServiceMethod-based routing:
GET /api/products → Product Read Service (optimize cho query)
POST /api/products → Product Write Service (optimize cho write)Query parameter routing:
GET /api/search?type=products → Product Search Service
GET /api/search?type=users → User Search Service3.2 Authentication và Authorization
Gateway là chỗ hoàn hảo để handle auth — validate một lần, forward identity xuống downstream.
Các auth pattern phổ biến tại gateway:
| Pattern | Cách Hoạt Động | Phù Hợp Cho |
|---|---|---|
| API Key | Client gửi key trong header (X-API-Key) | Third-party integration |
| JWT | Client gửi token trong Authorization: Bearer header | SPA, mobile app |
| OAuth2 | Gateway handle full OAuth2 flow | Third-party API access |
| mTLS | Client present certificate | Service-to-service |
| OIDC | OpenID Connect cho identity verification | Enterprise SSO |
Nguyên tắc quan trọng: Gateway validate token và extract identity. Backend service nhận trusted header (X-User-ID, X-Role) — không cần tự validate token nữa.
3.3 Rate Limiting
Kiểm soát số request mỗi client được gửi. Bảo vệ backend khỏi abuse và đảm bảo fair usage.
Các chiến lược rate limiting:
| Chiến Lược | Ví Dụ | Use Case |
|---|---|---|
| Theo IP | 100 req/phút mỗi IP | Basic DDoS protection |
| Theo API key | 1000 req/giờ mỗi key | Third-party API access |
| Theo user | 50 req/phút mỗi user | Authenticated endpoint |
| Theo endpoint | 10 req/phút trên /login | Brute-force protection |
| Global | 10.000 req/phút tổng cộng | Overall system protection |
Rate limit response:
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1710000000
Retry-After: 30
{
"error": "rate_limit_exceeded",
"message": "You have exceeded 100 requests per minute",
"retry_after": 30
}Các thuật toán rate limiting:
- Fixed window: Đếm request trong window cố định (ví dụ mỗi phút). Đơn giản nhưng có thể cho phép burst tại biên window.
- Sliding window: Phân phối mượt hơn bằng rolling time window. Chính xác hơn.
- Token bucket: Token tích lũy theo thời gian, mỗi request tiêu một token. Cho phép burst có kiểm soát.
- Leaky bucket: Request xếp hàng và xử lý ở tốc độ cố định. Output mượt nhất.
3.4 Request/Response Transformation
Transform request và response khi đi qua gateway.
Request transformation:
Client gửi:
POST /api/v2/users
Content-Type: application/json
{ "firstName": "John", "lastName": "Doe" }
Gateway transform thành:
POST /users
Content-Type: application/json
X-API-Version: 2
{ "first_name": "John", "last_name": "Doe" }Response transformation:
Backend trả về:
{ "user_id": 123, "first_name": "John", "created_at": "2026-03-11T..." }
Gateway transform thành:
{ "id": 123, "firstName": "John", "createdAt": "2026-03-11T..." }Các transformation phổ biến:
- Header injection: Thêm API version, correlation ID, request timestamp
- Body format: Convert giữa camelCase và snake_case
- Field filtering: Loại bỏ field nội bộ khỏi response
- Protocol translation: Nhận REST, forward dưới dạng gRPC
- Response wrapping: Bọc response trong envelope chuẩn
3.5 Request Aggregation (API Composition)
Một trong những feature mạnh nhất — gộp response từ nhiều service thành một response duy nhất cho client.
Không có aggregation, client phải gọi 3 API call riêng biệt. Với aggregation, một call trả về hết.
Ví dụ aggregated response:
{
"user": {
"id": 123,
"name": "John Doe",
"email": "[email protected]"
},
"recentOrders": [
{ "id": 456, "total": 99.99, "status": "delivered" },
{ "id": 457, "total": 49.99, "status": "processing" }
],
"paymentMethods": [
{ "type": "credit_card", "last4": "4242" }
]
}Đặc biệt có giá trị cho mobile client — nơi mà giảm thiểu network request là rất quan trọng.
3.6 Circuit Breaking
Khi một backend service đang fail, gateway có thể ngừng gửi request đến nó — ngăn chặn cascading failure.
Các trạng thái circuit:
| Trạng Thái | Hành Vi |
|---|---|
| Closed | Hoạt động bình thường — tất cả request được forward |
| Open | Backend đang fail — trả fallback/error ngay, không forward |
| Half-Open | Sau timeout, gửi một test request. Nếu thành công, đóng circuit. Nếu fail, giữ open. |
Ví dụ cấu hình:
circuit_breaker:
threshold: 5 # Mở sau 5 lần fail liên tiếp
timeout: 30s # Đợi 30s trước khi thử half-open
half_open_requests: 3 # Cho phép 3 test request ở half-open
failure_codes: # Những HTTP code nào tính là failure
- 500
- 502
- 503
- 5044. Các API Gateway Pattern
4.1 Single Gateway
Pattern đơn giản nhất — một gateway cho tất cả client và service.
Ưu điểm: Đơn giản, cấu hình tập trung, dễ monitor.
Nhược điểm: Single point of failure, một team sở hữu gateway, có thể trở thành bottleneck.
4.2 Backend for Frontend (BFF)
Mỗi loại client có gateway riêng, được tùy chỉnh cho nhu cầu của nó.
Tại sao dùng BFF?
- Mobile cần response gọn (bandwidth hạn chế) và aggregation khác
- Web cần response phong phú hơn và có thể truy cập nhiều service hơn
- Third-party cần API ổn định, có version với rate limiting nghiêm ngặt
Mỗi team BFF có thể deploy độc lập mà không cần phối hợp với team khác.
4.3 Gateway per Domain
Trong tổ chức lớn, mỗi domain/team sở hữu gateway riêng.
Ưu điểm: Team sở hữu gateway của mình, deploy độc lập, domain isolation.
Nhược điểm: Cross-cutting concern bị duplicate, khó enforce global policy.
4.4 Sidecar Gateway (Service Mesh)
Thay vì gateway tập trung, mỗi service có proxy sidecar riêng (như Envoy trong Istio).
Đây là cách tiếp cận service mesh (Istio, Linkerd). Sidecar handle mTLS, retry, circuit breaking, và observability cho service-to-service communication. Ingress gateway handle external client traffic.
5. API Versioning Tại Gateway
Gateway là chỗ lý tưởng để quản lý API version mà không cần thay đổi backend service.
Các Chiến Lược Versioning
URL path versioning:
GET /api/v1/users/123 → User Service v1
GET /api/v2/users/123 → User Service v2Header versioning:
GET /api/users/123
Accept: application/vnd.api.v2+json → User Service v2Query parameter versioning:
GET /api/users/123?version=2 → User Service v2Gateway-Level Version Routing
Gateway có thể route version khác nhau đến backend deployment khác nhau:
routes:
- path: /api/v1/users
service: user-service-v1
strip_prefix: /api/v1
- path: /api/v2/users
service: user-service-v2
strip_prefix: /api/v2
# Default latest version
- path: /api/users
service: user-service-v2
strip_prefix: /apiHoặc gateway có thể transform request để match format backend mong đợi — cho phép một backend serve nhiều API version:
routes:
- path: /api/v1/users
service: user-service
transform:
request:
rename_fields:
firstName: first_name
lastName: last_name
response:
rename_fields:
first_name: firstName
last_name: lastName6. Setup Thực Tế: Kong
Kong là API gateway open-source phổ biến nhất. Build trên Nginx + Lua, kết hợp performance cao với plugin ecosystem phong phú.
Setup Với Docker
# docker-compose.yml
version: "3.8"
services:
kong-database:
image: postgres:15-alpine
environment:
POSTGRES_USER: kong
POSTGRES_DB: kong
POSTGRES_PASSWORD: kongpass
volumes:
- kong-data:/var/lib/postgresql/data
kong-migration:
image: kong:3.6
depends_on:
- kong-database
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_PASSWORD: kongpass
command: kong migrations bootstrap
kong:
image: kong:3.6
depends_on:
- kong-database
- kong-migration
environment:
KONG_DATABASE: postgres
KONG_PG_HOST: kong-database
KONG_PG_PASSWORD: kongpass
KONG_PROXY_ACCESS_LOG: /dev/stdout
KONG_ADMIN_ACCESS_LOG: /dev/stdout
KONG_PROXY_ERROR_LOG: /dev/stderr
KONG_ADMIN_ERROR_LOG: /dev/stderr
KONG_ADMIN_LISTEN: "0.0.0.0:8001"
ports:
- "8000:8000" # Proxy port
- "8443:8443" # Proxy SSL port
- "8001:8001" # Admin API
volumes:
kong-data:Cấu Hình Route
# Tạo service
curl -i -X POST http://localhost:8001/services/ \
--data "name=user-service" \
--data "url=http://user-service:3000"
# Tạo route cho service
curl -i -X POST http://localhost:8001/services/user-service/routes \
--data "name=user-routes" \
--data "paths[]=/api/users" \
--data "strip_path=true"
# Tạo service khác
curl -i -X POST http://localhost:8001/services/ \
--data "name=order-service" \
--data "url=http://order-service:3001"
# Route cho order service
curl -i -X POST http://localhost:8001/services/order-service/routes \
--data "name=order-routes" \
--data "paths[]=/api/orders" \
--data "strip_path=true"Thêm Plugin
# Rate limiting — 100 request mỗi phút per consumer
curl -i -X POST http://localhost:8001/services/user-service/plugins \
--data "name=rate-limiting" \
--data "config.minute=100" \
--data "config.policy=local"
# JWT authentication
curl -i -X POST http://localhost:8001/services/user-service/plugins \
--data "name=jwt"
# Request logging
curl -i -X POST http://localhost:8001/services/user-service/plugins \
--data "name=file-log" \
--data "config.path=/tmp/api-logs.log"
# CORS
curl -i -X POST http://localhost:8001/services/user-service/plugins \
--data "name=cors" \
--data "config.origins[]=https://example.com" \
--data "config.methods[]=GET" \
--data "config.methods[]=POST" \
--data "config.headers[]=Authorization" \
--data "config.headers[]=Content-Type"
# Response transformer — xóa internal header
curl -i -X POST http://localhost:8001/services/user-service/plugins \
--data "name=response-transformer" \
--data "config.remove.headers=X-Powered-By" \
--data "config.remove.headers=Server"Kong Declarative Configuration
Cho production, dùng declarative config (YAML) thay vì Admin API:
# kong.yml
_format_version: "3.0"
services:
- name: user-service
url: http://user-service:3000
routes:
- name: user-routes
paths:
- /api/users
strip_path: true
plugins:
- name: rate-limiting
config:
minute: 100
policy: redis
redis_host: redis
- name: jwt
- name: cors
config:
origins:
- "https://example.com"
methods:
- GET
- POST
- PUT
- DELETE
- name: order-service
url: http://order-service:3001
routes:
- name: order-routes
paths:
- /api/orders
strip_path: true
plugins:
- name: rate-limiting
config:
minute: 50
policy: redis
redis_host: redis
consumers:
- username: mobile-app
jwt_secrets:
- key: mobile-app-key
algorithm: HS256
secret: your-secret-key
- username: web-app
jwt_secrets:
- key: web-app-key
algorithm: HS256
secret: your-other-secret7. Setup Thực Tế: AWS API Gateway
AWS API Gateway là managed service — không cần quản lý server.
REST API Configuration
# serverless.yml (Serverless Framework)
service: my-api
provider:
name: aws
runtime: nodejs20.x
region: us-east-1
functions:
getUsers:
handler: handlers/users.getAll
events:
- http:
path: /users
method: get
cors: true
authorizer:
type: COGNITO_USER_POOLS
authorizerId:
Ref: ApiGatewayAuthorizer
getUser:
handler: handlers/users.getById
events:
- http:
path: /users/{id}
method: get
cors: true
createOrder:
handler: handlers/orders.create
events:
- http:
path: /orders
method: post
cors: true
resources:
Resources:
# Usage plan với rate limiting
ApiUsagePlan:
Type: AWS::ApiGateway::UsagePlan
Properties:
UsagePlanName: BasicPlan
Throttle:
BurstLimit: 100
RateLimit: 50
Quota:
Limit: 10000
Period: MONTH
# API Key
ApiKey:
Type: AWS::ApiGateway::ApiKey
Properties:
Name: mobile-app-key
Enabled: true
# Cognito authorizer
ApiGatewayAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
Name: CognitoAuthorizer
Type: COGNITO_USER_POOLS
ProviderARNs:
- !GetAtt UserPool.Arn
RestApiId:
Ref: ApiGatewayRestApi
IdentitySource: method.request.header.AuthorizationHTTP API (Đơn Giản Hơn, Rẻ Hơn)
# AWS SAM template
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
HttpApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
CorsConfiguration:
AllowMethods:
- GET
- POST
- PUT
- DELETE
AllowOrigins:
- "https://example.com"
AllowHeaders:
- Authorization
- Content-Type
GetUsersFunction:
Type: AWS::Serverless::Function
Properties:
Handler: handlers/users.getAll
Runtime: nodejs20.x
Events:
GetUsers:
Type: HttpApi
Properties:
ApiId: !Ref HttpApi
Path: /users
Method: GETSo Sánh AWS API Gateway
| Feature | REST API | HTTP API |
|---|---|---|
| Chi phí | Cao hơn | Rẻ hơn ~70% |
| Latency | Cao hơn | Thấp hơn |
| Caching | Tích hợp | Không |
| API Key | Có | Không |
| Usage plan | Có | Không |
| Request validation | Có | Không |
| WAF integration | Có | Có |
| JWT authorizer | Qua Lambda | Tích hợp |
| Phù hợp cho | Full API management | API đơn giản, tiết kiệm |
8. Setup Thực Tế: Spring Cloud Gateway
Nếu bạn ở trong hệ sinh thái Java/Spring, Spring Cloud Gateway là lựa chọn tự nhiên.
Setup
<!-- pom.xml -->
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
</dependencies>Cấu Hình
# application.yml
spring:
cloud:
gateway:
routes:
# User service
- id: user-service
uri: http://user-service:3000
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- name: CircuitBreaker
args:
name: userServiceCB
fallbackUri: forward:/fallback/users
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
key-resolver: "#{@apiKeyResolver}"
- AddRequestHeader=X-Gateway, spring-cloud
# Order service
- id: order-service
uri: http://order-service:3001
predicates:
- Path=/api/orders/**
- Method=GET,POST,PUT
filters:
- StripPrefix=1
- name: Retry
args:
retries: 3
statuses: BAD_GATEWAY,SERVICE_UNAVAILABLE
methods: GET
backoff:
firstBackoff: 100ms
maxBackoff: 500ms
factor: 2
# Version-based routing
- id: user-service-v2
uri: http://user-service-v2:3000
predicates:
- Path=/api/users/**
- Header=X-API-Version, v2
filters:
- StripPrefix=1
# Default filter áp dụng cho tất cả route
default-filters:
- name: RequestSize
args:
maxSize: 5MB
- DedupeResponseHeader=Access-Control-Allow-Origin
# Global CORS
globalcors:
corsConfigurations:
"[/**]":
allowedOrigins: "https://example.com"
allowedMethods: "*"
allowedHeaders: "*"Custom Filter
@Component
public class JwtAuthFilter implements GatewayFilterFactory<JwtAuthFilter.Config> {
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
String token = exchange.getRequest().getHeaders()
.getFirst(HttpHeaders.AUTHORIZATION);
if (token == null || !token.startsWith("Bearer ")) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
try {
Claims claims = validateToken(token.substring(7));
// Thêm user info dưới dạng header cho downstream service
ServerHttpRequest modifiedRequest = exchange.getRequest()
.mutate()
.header("X-User-ID", claims.getSubject())
.header("X-User-Role", claims.get("role", String.class))
.build();
return chain.filter(
exchange.mutate().request(modifiedRequest).build()
);
} catch (Exception e) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
};
}
public static class Config {
// Configuration properties
}
}Rate Limiter Với Redis
@Configuration
public class RateLimiterConfig {
@Bean
public KeyResolver apiKeyResolver() {
return exchange -> {
String apiKey = exchange.getRequest().getHeaders()
.getFirst("X-API-Key");
return Mono.just(apiKey != null ? apiKey : exchange.getRequest()
.getRemoteAddress().getAddress().getHostAddress());
};
}
@Bean
public KeyResolver userKeyResolver() {
return exchange -> {
String userId = exchange.getRequest().getHeaders()
.getFirst("X-User-ID");
return Mono.just(userId != null ? userId : "anonymous");
};
}
}9. Observability
API gateway là chỗ hoàn hảo để thu thập metric, trace, và log — nó thấy mọi request.
Key Metric
| Metric | Cho Bạn Biết Gì |
|---|---|
| Request rate | Bạn đang handle bao nhiêu traffic |
| Error rate | Tỷ lệ response 4xx và 5xx |
| Latency (p50, p95, p99) | Response nhanh cỡ nào |
| Rate limit hit | Client bị limit thường xuyên không |
| Circuit breaker trip | Service nào đang fail |
| Request size | Pattern bandwidth consumption |
| Active connection | Load hiện tại trên gateway |
Logging Best Practice
Mỗi request qua gateway nên log:
{
"timestamp": "2026-03-11T10:30:00Z",
"request_id": "req-abc-123",
"method": "GET",
"path": "/api/users/123",
"status": 200,
"latency_ms": 45,
"client_ip": "203.0.113.50",
"api_key": "mobile-app",
"user_id": "user-456",
"upstream_service": "user-service",
"upstream_latency_ms": 38,
"cache_status": "MISS",
"rate_limit_remaining": 95
}Data này cho phép:
- Debug: Trace request xuyên suốt hệ thống
- Analytics: Hiểu API usage pattern
- Alert: Phát hiện anomaly trong error rate hoặc latency
- Billing: Tính phí API consumer dựa trên usage
10. Security Best Practice
Defense in Depth
Layer 1 — WAF (Web Application Firewall): Chặn SQL injection, XSS, attack pattern đã biết trước khi đến gateway.
Layer 2 — API Gateway: Authenticate, authorize, rate limit, validate request schema.
Layer 3 — Service Mesh: mTLS giữa các service, network policy, service-level auth.
Layer 4 — Backend Service: Input validation, business logic authorization.
Security Checklist
✅ Luôn dùng HTTPS — terminate TLS tại gateway hoặc load balancer
✅ Validate mọi token — đừng trust client-provided identity mà không verify
✅ Rate limit mọi thứ — đặc biệt auth endpoint
✅ Validate request schema — reject request bất hợp lệ tại gateway
✅ Strip sensitive header — xóa X-Powered-By, Server, internal header
✅ Log mọi request — với correlation ID để trace
✅ Dùng API key cho third-party — track và control external access
✅ Implement CORS đúng cách — đừng dùng * cho allowed origin trong production
✅ Set request size limit — ngăn payload quá lớn
✅ Rotate credential thường xuyên — API key, JWT secret, certificate
11. Khi Nào Nên (và Không Nên) Dùng API Gateway
Dùng API Gateway Khi
- Bạn có nhiều backend service mà client cần truy cập
- Bạn cần centralized authentication xuyên suốt các service
- Bạn cần rate limiting theo API key (không chỉ theo IP)
- Bạn cần request aggregation để giảm round-trip cho client
- Bạn có nhiều loại client (mobile, web, third-party) với nhu cầu khác nhau
- Bạn cần API versioning mà không cần thay đổi backend service
- Bạn cần developer portal với API documentation và key management
Không Nên Dùng API Gateway Khi
- Bạn có monolithic application — reverse proxy là đủ
- Bạn chỉ có 1-2 service — overhead không đáng
- Service của bạn chỉ dùng nội bộ (không có external API consumer)
- Bạn đang ở giai đoạn đầu — bắt đầu đơn giản, thêm gateway khi cần
- Bạn sẽ tạo ra single point of failure mà không có HA setup đúng cách
Chọn Solution Phù Hợp
| Tình Huống | Khuyến Nghị |
|---|---|
| Reverse proxy đơn giản | Nginx, Caddy |
| Docker/Kubernetes microservices | Kong, Traefik |
| AWS serverless | AWS API Gateway |
| Spring Boot ecosystem | Spring Cloud Gateway |
| Enterprise với policy phức tạp | Apigee, MuleSoft |
| Service mesh + gateway | Istio + Envoy |
| Tiết kiệm chi phí | Kong OSS, Traefik |
12. So Sánh Các API Gateway Solution
| Feature | Kong | AWS API Gateway | Spring Cloud GW | Traefik | Apigee |
|---|---|---|---|---|---|
| Loại | Open source | Managed | Open source | Open source | Managed |
| Ngôn ngữ | Lua/Nginx | N/A | Java | Go | N/A |
| Deploy | Self-hosted/Cloud | Chỉ AWS | Self-hosted | Self-hosted | Google Cloud |
| Auth | Plugin | Tích hợp | Filter | Middleware | Tích hợp |
| Rate limiting | Plugin | Tích hợp | Filter + Redis | Middleware | Tích hợp |
| Plugin | 100+ | Hạn chế | Custom filter | Middleware | Policy |
| Performance | Xuất sắc | Tốt | Tốt | Xuất sắc | Tốt |
| Kubernetes | Ingress controller | N/A | Pod deployment | Ingress controller | Adapter |
| Phù hợp cho | General purpose | AWS app | Spring app | Container routing | Enterprise |
Tổng Kết
| Chủ Đề | Nội Dung |
|---|---|
| Khái niệm | API gateway là entry point duy nhất cho tất cả API traffic trong microservices architecture |
| vs Reverse Proxy | API gateway thêm auth, rate limiting theo key, aggregation, và API management lên trên reverse proxy |
| Routing | Path-based, header-based, method-based, và versioned routing |
| Authentication | JWT, API key, OAuth2, mTLS — validate một lần tại gateway |
| Rate Limiting | Theo IP, theo key, theo user, theo endpoint với nhiều thuật toán |
| Aggregation | Gộp response từ nhiều service trong một call duy nhất |
| Circuit Breaking | Ngừng gửi request đến service đang fail, dùng fallback |
| Pattern | Single gateway, BFF, gateway per domain, service mesh |
| Solution | Kong (general), AWS API Gateway (serverless), Spring Cloud Gateway (Java) |
| Security | Defense in depth — WAF → Gateway → Service Mesh → Backend |
Những điểm quan trọng:
✅ API gateway tập trung cross-cutting concern — auth, rate limiting, logging, routing
✅ Bắt đầu với reverse proxy; thêm API gateway khi bạn có nhiều service và external consumer
✅ BFF pattern cho mỗi loại client một gateway optimize riêng
✅ Circuit breaking ngăn cascading failure xuyên suốt các service
✅ Rate limit theo API key, không chỉ theo IP — enable fair usage cho API consumer
✅ Gateway là chỗ tốt nhất cho observability — nó thấy mọi request
✅ Chọn gateway dựa trên ecosystem: Kong cho general use, AWS cho serverless, Spring Cloud cho Java
API gateway không chỉ là một router — nó là nơi bạn define cách thế giới bên ngoài tương tác với hệ thống của bạn. Làm đúng, microservices architecture của bạn sẽ sạch, an toàn, và observable. Làm sai, nó trở thành bottleneck mà mọi team đều phàn nàn.
📬 Đăng ký nhận bản tin
Nhận những bài viết mới nhất qua email mỗi tuần. Không spam, hủy đăng ký bất cứ lúc nào.
Chúng tôi tôn trọng quyền riêng tư của bạn. Hủy đăng ký bất cứ lúc nào.
💬 Comments
Đăng nhập để bình luận
Chúng tôi sẽ không đăng bất cứ điều gì mà không có sự cho phép của bạn.