blog.dopana

Back

API Gateway là entry point duy nhất cho tất cả client — routing, auth, rate limiting, transformation tập trung tại một chỗ.

Gateway Làm Gì?#

Client → API Gateway
            ├── /api/users → users-service
            ├── /api/orders → orders-service
            ├── /api/products → products-service
            └── /graphql → graphql-service
txt

Chức năng:

  • Routing — chuyển request đến service đúng
  • Authentication — xác thực trước khi vào internal
  • Rate limiting — bảo vệ backend
  • Transformation — đổi format request/response
  • Caching — cache response cho GET request
  • Monitoring — collect metrics và logs
  • Load balancing — phân phối đến nhiều instances

Kong Gateway#

Kong là open-source API gateway phổ biến nhất — dùng Nginx core.

Docker Compose#

Config Routes#

APISIX — Modern, Fast#

APISIX dùng Lua (OpenResty), nhanh hơn Kong ở nhiều benchmark.

services:
  apisix:
    image: apache/apisix:latest
    ports:
      - "9080:9080"  # HTTP
      - "9443:9443"  # HTTPS
    volumes:
      - ./apisix.yaml:/usr/local/apisix/conf/config.yaml
yaml

Custom Gateway — Node.js + Express#

Khi công cụ có sẵn không đáp ứng — tự viết gateway:

Response Aggregation#

Gateway gộp response từ nhiều service:

Gateway với GraphQL Federation#

Gateway GraphQL hợp nhất nhiều GraphQL service:

import { ApolloGateway, IntrospectAndCompose } from '@apollo/gateway';
import { ApolloServer } from '@apollo/server';

const gateway = new ApolloGateway({
  supergraphSdl: new IntrospectAndCompose({
    subgraphs: [
      { name: 'users', url: 'http://users-service:4001/graphql' },
      { name: 'orders', url: 'http://orders-service:4002/graphql' },
      { name: 'reviews', url: 'http://reviews-service:4003/graphql' },
    ],
  }),
});

const server = new ApolloServer({ gateway });
await server.listen({ port: 4000 });
typescript

Caching Trong Gateway#

Monitoring#

Gateway là nơi lý tưởng để collect metrics:

Kết Luận#

Giải phápKhi nào dùng
KongCần mature, nhiều plugin
APISIXCần performance cao
Custom Node.jsCần logic phức tạp
GraphQL FederationGraphQL microservices
Cloudflare API GatewayEdge gateway

Gateway không phải “nice to have” — nó essential cho microservices. Tập trung auth, rate limiting, routing tại gateway giúp service đơn giản hơn, tập trung vào business logic.

Tài liệu tham khảo#