⚖️ Reverse Proxy vs API Gateway vs Load Balancer

So sánh chuyên sâu 3 thành phần quan trọng trong kiến trúc hệ thống hiện đại

Tổng Quan

Khi thiết kế hệ thống backend, 3 khái niệm thường xuyên được nhắc đến là Reverse Proxy, API GatewayLoad Balancer. Nhiều developer nhầm lẫn giữa chúng vì ranh giới không rõ ràng — một số công cụ như NGINX hay Traefik có thể đóng nhiều vai trò cùng lúc.

Bài viết này sẽ giúp bạn hiểu rõ bản chất, cách hoạt động, điểm khác biệt, và khi nào nên dùng mỗi loại.

🔀 Reverse Proxy

Trung gian giữa client và server. Ẩn backend, cache, SSL termination, bảo mật.

🚪 API Gateway

Cổng vào duy nhất cho microservices. Authentication, rate limiting, request transformation.

⚖️ Load Balancer

Phân phối traffic đều giữa nhiều server. Đảm bảo high availability và scalability.

🔀 Reverse Proxy Là Gì?

Reverse Proxy là một server đứng trước một hoặc nhiều backend server, nhận request từ client rồi chuyển tiếp (forward) đến backend phù hợp. Client không bao giờ giao tiếp trực tiếp với backend.

Cách hoạt động

  1. Client gửi request đến Reverse Proxy (ví dụ: https://example.com)
  2. Reverse Proxy nhận request, quyết định chuyển đến backend nào
  3. Backend xử lý và trả response cho Reverse Proxy
  4. Reverse Proxy trả response cho client

Tính năng chính

  • SSL Termination: Xử lý HTTPS tại proxy, backend chỉ cần HTTP
  • Caching: Cache static content, giảm tải backend
  • Compression: Gzip/Brotli response trước khi gửi client
  • Security: Ẩn IP backend, chặn attack, WAF
  • URL Rewriting: Thay đổi URL trước khi forward

Ví dụ: NGINX làm Reverse Proxy

nginx.conf
# NGINX Reverse Proxy Configuration
server {
    listen 80;
    server_name example.com;

    # SSL Termination
    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;

    # Caching static files
    location /static/ {
        proxy_cache my_cache;
        proxy_cache_valid 200 1d;
        proxy_pass http://backend_server;
    }

    # Forward tất cả request đến backend
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

📌 Công cụ phổ biến: NGINX, HAProxy, Apache httpd, Caddy, Traefik, Envoy

🚪 API Gateway Là Gì?

API Gateway là một lớp quản lý API đứng trước các microservices. Nó không chỉ forward request mà còn cung cấp nhiều tính năng cấp ứng dụng (application-level) như authentication, rate limiting, request/response transformation, và API versioning.

Cách hoạt động

  1. Client gửi request đến API Gateway (https://api.example.com/v2/users)
  2. Gateway kiểm tra authentication (JWT, API Key, OAuth)
  3. Áp dụng rate limiting (ví dụ: 100 req/min)
  4. Transform request nếu cần (thêm/bỏ headers, đổi format)
  5. Route đến microservice phù hợp (Users Service, Orders Service...)
  6. Aggregate response từ nhiều services nếu cần
  7. Trả response cho client

Tính năng chính

  • Authentication & Authorization: JWT validation, OAuth2, API Key
  • Rate Limiting & Throttling: Giới hạn số request per client
  • Request/Response Transformation: Đổi format, thêm/bỏ fields
  • API Versioning: Quản lý nhiều version API
  • Circuit Breaker: Tự động ngắt khi service lỗi
  • Logging & Analytics: Theo dõi API usage, metrics
  • Response Aggregation: Gộp data từ nhiều services

Ví dụ: Kong API Gateway

kong.yml
# Kong Declarative Configuration
_format_version: "3.0"

services:
  - name: users-service
    url: http://users-svc:3000
    routes:
      - name: users-route
        paths:
          - /api/v1/users
        strip_path: true

  - name: orders-service
    url: http://orders-svc:3001
    routes:
      - name: orders-route
        paths:
          - /api/v1/orders
        strip_path: true

plugins:
  # Rate Limiting toàn cục
  - name: rate-limiting
    config:
      minute: 100
      policy: local

  # JWT Authentication
  - name: jwt
    config:
      claims_to_verify:
        - exp

  # Request Logging
  - name: file-log
    config:
      path: /tmp/kong-requests.log

📌 Công cụ phổ biến: Kong, AWS API Gateway, Azure API Management, Apigee (Google), Tyk, KrakenD, APISIX

⚖️ Load Balancer Là Gì?

Load Balancer phân phối incoming traffic đều giữa nhiều backend server, đảm bảo không server nào bị quá tải. Mục tiêu chính: high availability, fault tolerance, và scalability.

Hai loại Load Balancer

📡 L4 — Transport Layer

Hoạt động ở tầng TCP/UDP. Routing dựa trên IP + Port. Nhanh, low overhead. Không đọc nội dung request.

🌐 L7 — Application Layer

Hoạt động ở tầng HTTP. Routing dựa trên URL, headers, cookies. Linh hoạt hơn, có thể modify request.

Các thuật toán phổ biến

  • Round Robin: Chia đều request lần lượt cho từng server
  • Weighted Round Robin: Server mạnh hơn nhận nhiều request hơn
  • Least Connections: Chuyển đến server đang có ít connection nhất
  • IP Hash: Cùng IP luôn đến cùng server (sticky session)
  • Random: Chọn ngẫu nhiên server
  • Least Response Time: Chuyển đến server response nhanh nhất

Ví dụ: NGINX Load Balancer

nginx.conf
# NGINX Load Balancer Configuration
upstream backend_pool {
    # Thuật toán: Least Connections
    least_conn;

    server 10.0.0.1:3000 weight=3;   # Server mạnh, nhận nhiều hơn
    server 10.0.0.2:3000 weight=2;
    server 10.0.0.3:3000 weight=1;
    server 10.0.0.4:3000 backup;     # Backup server

    # Health check
    keepalive 32;
}

server {
    listen 80;

    location / {
        proxy_pass http://backend_pool;
        proxy_next_upstream error timeout http_500;
        proxy_connect_timeout 5s;
        proxy_read_timeout 60s;
    }
}

Ví dụ: HAProxy Load Balancer

haproxy.cfg
# HAProxy Load Balancer Configuration
frontend http_front
    bind *:80
    default_backend app_servers

    # L7 routing dựa trên path
    acl is_api path_beg /api
    use_backend api_servers if is_api

backend app_servers
    balance roundrobin
    option httpchk GET /health
    server web1 10.0.0.1:3000 check inter 5s fall 3 rise 2
    server web2 10.0.0.2:3000 check inter 5s fall 3 rise 2
    server web3 10.0.0.3:3000 check inter 5s fall 3 rise 2

backend api_servers
    balance leastconn
    option httpchk GET /api/health
    server api1 10.0.1.1:8080 check weight 100
    server api2 10.0.1.2:8080 check weight 100

📌 Công cụ phổ biến: AWS ALB/NLB/ELB, GCP Load Balancer, Azure Load Balancer, HAProxy, NGINX, F5, Traefik

📊 Bảng So Sánh Chi Tiết

Tiêu chí 🔀 Reverse Proxy 🚪 API Gateway ⚖️ Load Balancer
Mục tiêu chính Ẩn backend, caching, bảo mật Quản lý API, auth, rate limit Phân phối traffic đều
Tầng hoạt động L7 (HTTP) L7 (HTTP/API) L4 (TCP) hoặc L7 (HTTP)
Authentication ❌ Cơ bản (Basic Auth) ✅ JWT, OAuth2, API Key ❌ Không
Rate Limiting ⚠️ Hạn chế ✅ Per-client, per-route ❌ Không
Caching ✅ Mạnh (static + dynamic) ⚠️ Tuỳ implementation ❌ Không
SSL Termination ✅ Có ✅ Có ✅ Có (L7 LB)
Request Transform ⚠️ Hạn chế (Header) ✅ Body, header, format ❌ Không
Health Check ✅ Có ✅ Có ✅ Có
API Versioning ❌ Không ✅ Quản lý v1, v2, v3 ❌ Không
Load Balancing ⚠️ Cơ bản ⚠️ Tuỳ implementation ✅ Chuyên sâu, nhiều algorithm
Logging/Analytics ⚠️ Access log cơ bản ✅ API analytics chi tiết ⚠️ Connection metrics
Circuit Breaker ❌ Không ✅ Có ⚠️ Qua health check

🏗️ Sơ Đồ Kiến Trúc

Architecture 1: Từng thành phần riêng biệt

Mỗi layer đảm nhiệm 1 vai trò

👤 Client
⚖️ Load Balancer
Phân phối traffic
🔀 Reverse Proxy
SSL, Cache, Security
🚪 API Gateway
Auth, Rate Limit
🖥️ Services
Backend Apps

Architecture 2: Kết hợp trong Kubernetes

Ingress Controller đóng vai trò Reverse Proxy + Load Balancer

👤 Client
☁️ Cloud LB
AWS ALB / GCP LB
⚓ Ingress (NGINX)
RP + LB + TLS
🚪 Kong / APISIX
API Gateway
🐳 Pods
Microservices

💡 Insight: Trong thực tế, các vai trò thường được gộp lại. NGINX vừa là Reverse Proxy vừa là Load Balancer. Kong vừa là API Gateway vừa có tính năng Reverse Proxy. Ranh giới giữa chúng là tính năng chính mà bạn sử dụng.

🤔 Khi Nào Dùng Cái Nào?

🔀 Dùng Reverse Proxy khi

  • Cần ẩn backend server khỏi Internet
  • Muốn SSL termination tập trung
  • Cần cache static content
  • Muốn compress response
  • Chỉ có 1 backend hoặc monolith
  • Bảo vệ server khỏi DDoS cơ bản

🚪 Dùng API Gateway khi

  • Kiến trúc microservices
  • Cần authentication/authorization tập trung
  • Muốn rate limiting per-client
  • Cần API versioning (v1, v2)
  • Muốn request/response transformation
  • Cần API analytics và monitoring

⚖️ Dùng Load Balancer khi

  • Có nhiều server instances cùng chạy 1 app
  • Cần high availability (HA)
  • Traffic cao, 1 server không đủ
  • Cần zero-downtime deployments
  • Muốn horizontal scaling
  • Routing L4 (TCP) cho database, message queue

⚠️ Lưu ý: Đừng over-engineer! Nếu hệ thống nhỏ (1-3 servers, monolith), chỉ cần NGINX làm Reverse Proxy + basic Load Balancer là đủ. API Gateway chỉ thực sự cần khi bạn có kiến trúc microservices với nhiều teams và services.

🌍 Kết Hợp Trong Thực Tế

Scenario 1: Startup nhỏ — NGINX làm mọi thứ

Với ứng dụng nhỏ, NGINX đóng vai trò cả 3: Reverse Proxy + Load Balancer + basic API routing.

nginx.conf
# NGINX = Reverse Proxy + Load Balancer + Basic API Router
upstream web_servers {
    least_conn;
    server 10.0.0.1:3000;
    server 10.0.0.2:3000;
}

upstream api_servers {
    ip_hash;   # Sticky session cho API
    server 10.0.1.1:8080;
    server 10.0.1.2:8080;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    # SSL Termination (Reverse Proxy)
    ssl_certificate /etc/ssl/cert.pem;
    ssl_certificate_key /etc/ssl/key.pem;

    # Gzip Compression (Reverse Proxy)
    gzip on;
    gzip_types text/plain application/json;

    # Static file caching (Reverse Proxy)
    location /static/ {
        alias /var/www/static/;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # API routing + Load Balancing
    location /api/ {
        proxy_pass http://api_servers;
        
        # Basic rate limiting
        limit_req zone=api burst=20 nodelay;
    }

    # Web app + Load Balancing
    location / {
        proxy_pass http://web_servers;
        proxy_set_header Host $host;
    }
}

Scenario 2: Kubernetes production — Full stack

Hệ thống lớn với Kubernetes sử dụng cả 3 layer riêng biệt:

k8s-ingress.yaml
# Layer 1: Cloud Load Balancer (AWS ALB)
# → Tự động tạo khi deploy Ingress Controller

# Layer 2: NGINX Ingress = Reverse Proxy + LB
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: main-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: "10m"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "60"
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - api.example.com
      secretName: tls-secret
  rules:
    - host: api.example.com
      http:
        paths:
          # Route tất cả /api/* đến API Gateway (Kong)
          - path: /api
            pathType: Prefix
            backend:
              service:
                name: kong-proxy
                port:
                  number: 80
          # Route web app trực tiếp
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web-frontend
                port:
                  number: 80
kong-plugins.yaml
# Layer 3: Kong API Gateway
# Rate Limiting Plugin
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: rate-limit-plugin
plugin: rate-limiting
config:
  minute: 100
  policy: redis
  redis_host: redis-svc
---
# JWT Auth Plugin
apiVersion: configuration.konghq.com/v1
kind: KongPlugin
metadata:
  name: jwt-auth-plugin
plugin: jwt
config:
  claims_to_verify:
    - exp
  key_claim_name: iss

💡 Tóm tắt kiến trúc production:

Cloud LB (L4) → phân phối traffic đến cluster
NGINX Ingress (L7) → SSL, caching, routing
Kong Gateway → auth, rate limiting, API management
K8s Service → internal load balancing đến pods

📝 Kết Luận

Khi gặp yêu cầu Giải pháp
Ẩn backend, SSL, cache Reverse Proxy (NGINX, Caddy)
Auth, rate limit, API management API Gateway (Kong, AWS API GW)
Phân phối traffic, HA, scaling Load Balancer (AWS ALB, HAProxy)
Tất cả cùng lúc, startup nhỏ NGINX (đóng nhiều vai trò)
Kubernetes production Cloud LB + Ingress + API Gateway

Điều quan trọng nhất là hiểu bản chất của từng thành phần, từ đó chọn đúng công cụ phù hợp với quy mô và yêu cầu của hệ thống. Đừng dùng API Gateway khi chỉ cần Reverse Proxy, và ngược lại đừng dùng Reverse Proxy khi cần quản lý API phức tạp.