Home > Blog > tech

API Gateway คืออะไร? สอน Kong, Envoy และ Pattern สำหรับ Microservices 2026

API Gateway Kong Envoy Guide 2026
2026-04-16 | tech | 3500 words

ใน Microservices Architecture เมื่อระบบมีหลายสิบ Service ที่ทำงานร่วมกัน การให้ Client เรียก API ของแต่ละ Service โดยตรงจะมีปัญหามากมาย ทั้งเรื่อง Authentication, Rate limiting, Routing, Monitoring, Protocol transformation ทั้งหมดนี้แก้ได้ด้วย API Gateway

บทความนี้จะอธิบาย API Gateway Pattern อย่างละเอียด พร้อมสอนใช้ Kong Gateway และ Envoy Proxy ซึ่งเป็น API Gateway ที่นิยมที่สุดในปี 2026

API Gateway Pattern คืออะไร?

API Gateway คือจุดเข้าเดียว (Single Entry Point) ที่อยู่ระหว่าง Client กับ Backend Services ทุก Request จาก Client ต้องผ่าน Gateway ก่อน แล้ว Gateway จะ Route ไปยัง Service ที่ถูกต้อง

ทำไมต้องมี API Gateway?

// ไม่มี API Gateway — Client ต้องรู้จักทุก Service
Client → User Service     (port 8001)
Client → Order Service    (port 8002)
Client → Payment Service  (port 8003)
Client → Product Service  (port 8004)
// ปัญหา: Client ต้องจัดการ Auth, Rate limit, Error handling เอง
// ทุก Service ต้อง Expose public endpoint

// มี API Gateway — Client รู้แค่ Gateway
Client → API Gateway (port 443) → User Service
                                 → Order Service
                                 → Payment Service
                                 → Product Service
// Gateway จัดการ Auth, Rate limit, Routing, Monitoring ให้ทั้งหมด

Gateway Responsibilities — หน้าที่ของ API Gateway

หน้าที่คำอธิบายตัวอย่าง
RoutingRoute Request ไปยัง Service ที่ถูกต้อง/api/users → User Service, /api/orders → Order Service
Authenticationตรวจสอบ Identity ของ ClientJWT Token validation, API Key check
Authorizationตรวจสอบสิทธิ์การเข้าถึงAdmin-only endpoints, Role-based access
Rate Limitingจำกัดจำนวน Request ต่อช่วงเวลา100 req/min per API key
Request/Response Transformationแปลงรูปแบบข้อมูลXML → JSON, Add headers, Remove fields
CachingCache Response เพื่อลด Load บน ServicesCache GET /products for 60s
Load Balancingกระจาย Traffic ไปหลาย InstanceRound-robin, Least connections
Circuit Breakingตัด Traffic ไปยัง Service ที่ล่มถ้า error > 50% → ส่ง fallback response
Logging/Monitoringบันทึก Request ทั้งหมดAccess log, Metrics, Tracing
SSL/TLS Terminationจัดการ HTTPSClient → HTTPS → Gateway → HTTP → Services

Kong Gateway — สอนใช้งานจริง

Kong เป็น API Gateway ยอดนิยมที่สุด สร้างบน Nginx + OpenResty มีทั้ง Open Source (Kong OSS) และ Enterprise:

ติดตั้ง Kong ด้วย Docker

# Docker Compose สำหรับ Kong
# docker-compose.yml
version: '3.8'
services:
  kong-database:
    image: postgres:15
    environment:
      POSTGRES_USER: kong
      POSTGRES_DB: kong
      POSTGRES_PASSWORD: kongpass
    volumes:
      - kong-db-data:/var/lib/postgresql/data

  kong-migration:
    image: kong:3.6
    command: kong migrations bootstrap
    environment:
      KONG_DATABASE: postgres
      KONG_PG_HOST: kong-database
      KONG_PG_PASSWORD: kongpass
    depends_on:
      - kong-database

  kong:
    image: kong:3.6
    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
      - "8443:8443"   # Proxy SSL
      - "8001:8001"   # Admin API
    depends_on:
      - kong-migration

volumes:
  kong-db-data:

# เริ่มต้น
# docker compose up -d

Kong DB-less Mode (Declarative Config)

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

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

  - name: order-service
    url: http://order-svc:8080
    routes:
      - name: order-route
        paths:
          - /api/orders
        strip_path: true

plugins:
  - name: rate-limiting
    config:
      minute: 100
      policy: local

  - name: key-auth
    config:
      key_names:
        - apikey

  - name: cors
    config:
      origins:
        - "*"
      methods:
        - GET
        - POST
        - PUT
        - DELETE

# ใช้ DB-less mode
# docker run -d --name kong \
#   -e "KONG_DATABASE=off" \
#   -e "KONG_DECLARATIVE_CONFIG=/kong/kong.yml" \
#   -v ./kong.yml:/kong/kong.yml \
#   -p 8000:8000 \
#   kong:3.6

Kong Plugins ยอดนิยม

Pluginหน้าที่ตัวอย่างใช้งาน
rate-limitingจำกัด Request rate100 req/min, 1000 req/hour
key-authAuthentication ด้วย API KeyHeader: apikey: abc123
jwtJWT Token validationAuthorization: Bearer token
oauth2OAuth 2.0 flowAuthorization code, Client credentials
corsCross-Origin Resource SharingAllow specific origins
request-transformerแก้ไข RequestAdd/remove headers, Change body
response-transformerแก้ไข ResponseAdd headers, Remove fields
proxy-cacheCache ResponseCache GET for 300s
prometheusMetrics สำหรับ MonitoringGrafana dashboard
tcp-log / http-logส่ง Log ไป ExternalELK Stack, Splunk

Envoy Proxy — L7 Proxy สำหรับ Cloud Native

Envoy เป็น L7 Proxy ที่ออกแบบมาสำหรับ Cloud-native applications สร้างโดย Lyft ปัจจุบันเป็น CNCF Graduated Project:

จุดเด่นของ Envoy

Envoy Configuration ตัวอย่าง

# envoy.yaml
static_resources:
  listeners:
    - name: listener_0
      address:
        socket_address:
          address: 0.0.0.0
          port_value: 8080
      filter_chains:
        - filters:
            - name: envoy.filters.network.http_connection_manager
              typed_config:
                "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
                stat_prefix: ingress_http
                route_config:
                  name: local_route
                  virtual_hosts:
                    - name: backend
                      domains: ["*"]
                      routes:
                        - match:
                            prefix: "/api/users"
                          route:
                            cluster: user_service
                        - match:
                            prefix: "/api/orders"
                          route:
                            cluster: order_service
                http_filters:
                  - name: envoy.filters.http.router
                    typed_config:
                      "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router

  clusters:
    - name: user_service
      connect_timeout: 5s
      type: STRICT_DNS
      load_assignment:
        cluster_name: user_service
        endpoints:
          - lb_endpoints:
              - endpoint:
                  address:
                    socket_address:
                      address: user-svc
                      port_value: 8080

    - name: order_service
      connect_timeout: 5s
      type: STRICT_DNS
      lb_policy: LEAST_REQUEST
      circuit_breakers:
        thresholds:
          - max_connections: 100
            max_pending_requests: 50
            max_requests: 200
      load_assignment:
        cluster_name: order_service
        endpoints:
          - lb_endpoints:
              - endpoint:
                  address:
                    socket_address:
                      address: order-svc
                      port_value: 8080

AWS API Gateway

สำหรับคนที่ใช้ AWS, Amazon API Gateway เป็น Managed service ที่ไม่ต้องจัดการ Infrastructure:

ประเภทใช้สำหรับราคา
HTTP APIREST API ทั่วไป, Lambda integration$1.00/ล้าน requests
REST APIFull-featured, API Key, Usage plans$3.50/ล้าน requests
WebSocket APIReal-time, Chat, Notifications$1.00/ล้าน messages
# AWS API Gateway + Lambda (Serverless)
# ไม่ต้องจัดการ Server เลย
# Client → API Gateway → Lambda → DynamoDB

# สร้างด้วย AWS CDK (TypeScript)
const api = new apigateway.RestApi(this, 'MyApi', {
  restApiName: 'My Service',
  description: 'API Gateway for my microservices'
});

const usersResource = api.root.addResource('users');
usersResource.addMethod('GET', new apigateway.LambdaIntegration(getUsersLambda));
usersResource.addMethod('POST', new apigateway.LambdaIntegration(createUserLambda));

Traefik as API Gateway

Traefik เป็น Edge Router ที่นิยมใช้กับ Docker/Kubernetes เพราะ Auto-discovery:

# docker-compose.yml with Traefik
version: '3.8'
services:
  traefik:
    image: traefik:v3.0
    command:
      - "--api.insecure=true"
      - "--providers.docker=true"
      - "--entrypoints.web.address=:80"
    ports:
      - "80:80"
      - "8080:8080"  # Dashboard
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock

  user-service:
    image: user-service:latest
    labels:
      - "traefik.http.routers.users.rule=PathPrefix(`/api/users`)"
      - "traefik.http.services.users.loadbalancer.server.port=8080"

  order-service:
    image: order-service:latest
    labels:
      - "traefik.http.routers.orders.rule=PathPrefix(`/api/orders`)"
      - "traefik.http.services.orders.loadbalancer.server.port=8080"

# Traefik Auto-discover services จาก Docker labels!
# ไม่ต้อง Config route เอง

API Gateway vs Service Mesh

คุณสมบัติAPI GatewayService Mesh (Istio/Linkerd)
ตำแหน่งEdge (North-South traffic)Between services (East-West traffic)
หน้าที่หลักExternal API managementInter-service communication
Traffic typeClient → ServicesService → Service
AuthExternal auth (JWT, API Key)mTLS between services
ArchitectureCentralized proxySidecar proxy per service
Complexityปานกลางสูง
ใช้เมื่อExpose APIs to externalSecure inter-service comms
ใช้ร่วมกัน?ได้! API Gateway อยู่ Edge + Service Mesh อยู่ภายใน

BFF Pattern (Backend for Frontend)

BFF คือ Pattern ที่สร้าง API Gateway แยกตาม Client type:

// BFF Pattern
// Mobile App → Mobile BFF Gateway → Microservices
// Web App   → Web BFF Gateway    → Microservices
// Admin     → Admin BFF Gateway  → Microservices

// ทำไมต้อง BFF?
// - Mobile ต้องการ Response ที่เล็ก (ประหยัด Bandwidth)
// - Web ต้องการ Response ที่มีข้อมูลมากกว่า
// - Admin ต้องการ Endpoint ที่ต่างจาก User
// - แต่ละ BFF ปรับแต่ง Response ให้เหมาะกับ Client

// Mobile BFF — ส่ง Response เล็ก
GET /api/user/profile → { name, avatar, badge_count }

// Web BFF — ส่ง Response ใหญ่กว่า
GET /api/user/profile → { name, avatar, badge_count, recent_orders, notifications, settings }

Gateway Security

JWT Validation

# Kong — JWT Plugin
# สร้าง Consumer
curl -X POST http://localhost:8001/consumers \
  -d "username=my-app"

# สร้าง JWT Credential
curl -X POST http://localhost:8001/consumers/my-app/jwt \
  -d "algorithm=HS256" \
  -d "secret=my-super-secret"

# เปิด JWT Plugin บน Service
curl -X POST http://localhost:8001/services/user-service/plugins \
  -d "name=jwt"

# Client ส่ง Request พร้อม JWT
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
  http://localhost:8000/api/users

OAuth 2.0 Flow

# API Gateway ทำหน้าที่ OAuth Resource Server
# 1. Client ได้ Token จาก Authorization Server (Auth0, Keycloak)
# 2. Client ส่ง Token ใน Request header
# 3. Gateway ตรวจสอบ Token กับ Authorization Server
# 4. ถ้า Valid → Forward request ไป Service
# 5. ถ้า Invalid → Return 401 Unauthorized

Gateway Monitoring

# Kong + Prometheus + Grafana
# 1. เปิด Prometheus Plugin
curl -X POST http://localhost:8001/plugins \
  -d "name=prometheus"

# 2. Scrape metrics จาก Kong
# prometheus.yml
scrape_configs:
  - job_name: 'kong'
    static_configs:
      - targets: ['kong:8001']
    metrics_path: /metrics

# Metrics ที่สำคัญ:
# - kong_http_requests_total (จำนวน Request)
# - kong_request_latency_ms (Response time)
# - kong_upstream_target_health (Service health)
# - kong_bandwidth_bytes (Bandwidth usage)

# 3. สร้าง Grafana Dashboard
# - Request rate per service
# - P50, P95, P99 latency
# - Error rate
# - Upstream health

เลือก API Gateway ที่เหมาะสม

Gatewayเหมาะกับจุดเด่นจุดด้อย
Kongทั่วไป, EnterprisePlugin ecosystem, Community ใหญ่Memory usage สูง (Lua/Nginx)
EnvoyCloud-native, gRPCPerformance สูง, xDS APIConfig ซับซ้อน
AWS API GatewayAWS Serverlessไม่ต้องจัดการ InfraVendor lock-in, แพง
TraefikDocker/K8sAuto-discovery, ง่ายPlugin น้อยกว่า Kong
NGINXง่ายๆ ไม่ซับซ้อนเร็วมาก, คุ้นเคยต้อง Config เอง ไม่มี Plugin
APISIXHigh performanceเร็ว, Dashboard ดีCommunity เล็กกว่า Kong
เลือกอย่างไร? ถ้าใช้ AWS → AWS API Gateway + Lambda, ถ้าใช้ Docker/K8s → Kong หรือ Traefik, ถ้าต้องการ Service Mesh → Envoy (เป็น Data plane ของ Istio), ถ้าต้องการง่ายที่สุด → NGINX reverse proxy

สรุป

API Gateway เป็น Component ที่ขาดไม่ได้ใน Microservices Architecture ทำหน้าที่เป็น Single Entry Point จัดการ Routing, Authentication, Rate Limiting, Caching, Monitoring ให้ทั้งหมด ไม่ว่าจะเลือก Kong, Envoy, AWS API Gateway หรือ Traefik สิ่งสำคัญคือเข้าใจ Pattern และเลือกเครื่องมือที่เหมาะกับ Tech Stack ของทีม

เริ่มต้นด้วยการ Docker run Kong หรือ Traefik ขึ้นมา ลองตั้งค่า Route + Rate limiting + JWT Auth แล้วคุณจะเข้าใจว่าทำไม API Gateway ถึงเป็นหัวใจของ Modern Backend Architecture ในปี 2026


Back to Blog | iCafe Forex | SiamLanCard | Siam2R