API Gateways: From Concepts to Implementation

Contents

1. What Is an API Gateway?

1.1 Definition of an API Gateway

An API gateway is an intermediary layer between clients and backend services, serving as the entry point for all API requests. It is particularly important in a microservices architecture, acting as a gateway that presents multiple independent services as one unified API.

1.2 Core API Gateway Features

1.3 Why an API Gateway Is Needed

Addressing microservices architecture complexity

Stronger security

2. Comparing Major API Gateway Solutions

2.1 Amazon API Gateway

Features

Infrastructure Setup

yaml
# serverless.yml 예시 (Serverless Framework 사용)
service: my-api-gateway

provider:
  name: aws
  runtime: nodejs18.x
  region: ap-northeast-2

functions:
  getUsers:
    handler: handlers/users.get
    events:
      - http:
          path: users
          method: get
          cors: true
          authorizer:
            name: authenticate
            resultTtlInSeconds: 300

  createUser:
    handler: handlers/users.create
    events:
      - http:
          path: users
          method: post
          cors: true

resources:
  Resources:
    GatewayResponseDefault4XX:
      Type: 'AWS::ApiGateway::GatewayResponse'
      Properties:
        ResponseParameters:
          gatewayresponse.header.Access-Control-Allow-Origin: "'*'"
        ResponseType: DEFAULT_4XX
        RestApiId: !Ref RestApi

Configuration with Terraform

hcl
resource "aws_api_gateway_rest_api" "example" {
  name        = "example-api"
  description = "Example API Gateway"
}

resource "aws_api_gateway_resource" "users" {
  rest_api_id = aws_api_gateway_rest_api.example.id
  parent_id   = aws_api_gateway_rest_api.example.root_resource_id
  path_part   = "users"
}

resource "aws_api_gateway_method" "users_get" {
  rest_api_id   = aws_api_gateway_rest_api.example.id
  resource_id   = aws_api_gateway_resource.users.id
  http_method   = "GET"
  authorization = "AWS_IAM"
}

resource "aws_api_gateway_integration" "users_lambda" {
  rest_api_id = aws_api_gateway_rest_api.example.id
  resource_id = aws_api_gateway_resource.users.id
  http_method = aws_api_gateway_method.users_get.http_method

  integration_http_method = "POST"
  type                   = "AWS_PROXY"
  uri                    = aws_lambda_function.users.invoke_arn
}

Advantages

Disadvantages

2.2 Kong Gateway

Features

Setup with Docker Compose

yaml
version: '3.8'

services:
  kong-database:
    image: postgres:13
    environment:
      POSTGRES_USER: kong
      POSTGRES_PASSWORD: kongpass
      POSTGRES_DB: kong
    volumes:
      - kong_data:/var/lib/postgresql/data
    networks:
      - kong-net

  kong-migrations:
    image: kong:3.4
    command: kong migrations bootstrap
    depends_on:
      - kong-database
    environment:
      KONG_DATABASE: postgres
      KONG_PG_HOST: kong-database
      KONG_PG_USER: kong
      KONG_PG_PASSWORD: kongpass
    networks:
      - kong-net

  kong:
    image: kong:3.4
    depends_on:
      - kong-migrations
    environment:
      KONG_DATABASE: postgres
      KONG_PG_HOST: kong-database
      KONG_PG_USER: kong
      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 port
    networks:
      - kong-net

  konga:
    image: pantsel/konga:latest
    depends_on:
      - kong
    environment:
      NODE_ENV: production
    ports:
      - "1337:1337"
    networks:
      - kong-net

volumes:
  kong_data:

networks:
  kong-net:

Setup with Kubernetes

yaml
apiVersion: v1
kind: Namespace
metadata:
  name: kong
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kong
  namespace: kong
spec:
  replicas: 2
  selector:
    matchLabels:
      app: kong
  template:
    metadata:
      labels:
        app: kong
    spec:
      containers:
      - name: kong
        image: kong:3.4
        env:
        - name: KONG_DATABASE
          value: "off"
        - name: KONG_DECLARATIVE_CONFIG
          value: "/kong/declarative/kong.yml"
        - name: KONG_PROXY_ACCESS_LOG
          value: "/dev/stdout"
        - name: KONG_ADMIN_ACCESS_LOG
          value: "/dev/stdout"
        - name: KONG_PROXY_ERROR_LOG
          value: "/dev/stderr"
        - name: KONG_ADMIN_ERROR_LOG
          value: "/dev/stderr"
        - name: KONG_ADMIN_LISTEN
          value: "0.0.0.0:8001"
        ports:
        - containerPort: 8000
        - containerPort: 8443
        - containerPort: 8001
        volumeMounts:
        - name: kong-config
          mountPath: /kong/declarative/
      volumes:
      - name: kong-config
        configMap:
          name: kong-declarative-config
---
apiVersion: v1
kind: Service
metadata:
  name: kong-proxy
  namespace: kong
spec:
  type: LoadBalancer
  ports:
  - name: proxy
    port: 80
    targetPort: 8000
  - name: proxy-ssl
    port: 443
    targetPort: 8443
  selector:
    app: kong

Advantages

Disadvantages

2.3 Istio

Features

Setup in Kubernetes

yaml
# istio-gateway.yaml
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
  name: api-gateway
  namespace: default
spec:
  selector:
    istio: ingressgateway
  servers:
  - port:
      number: 80
      name: http
      protocol: HTTP
    hosts:
    - api.example.com
  - port:
      number: 443
      name: https
      protocol: HTTPS
    tls:
      mode: SIMPLE
      credentialName: api-tls-secret
    hosts:
    - api.example.com
---
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: api-routes
  namespace: default
spec:
  hosts:
  - api.example.com
  gateways:
  - api-gateway
  http:
  - match:
    - uri:
        prefix: /users
    route:
    - destination:
        host: user-service
        port:
          number: 8080
    fault:
      delay:
        percentage:
          value: 0.1
        fixedDelay: 5s
  - match:
    - uri:
        prefix: /orders
    route:
    - destination:
        host: order-service
        port:
          number: 8080
      weight: 90
    - destination:
        host: order-service-v2
        port:
          number: 8080
      weight: 10

Security Policy Configuration

yaml
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: api-authz
  namespace: default
spec:
  rules:
  - from:
    - source:
        principals: ["cluster.local/ns/default/sa/api-client"]
    to:
    - operation:
        methods: ["GET", "POST"]
    when:
    - key: request.headers[version]
      values: ["v1", "v2"]

Advantages

Disadvantages

3. Detailed Comparison

3.1 Performance Comparison

Category Amazon API Gateway Kong Gateway Istio
Latency Low–medium Very low Low
Throughput High Very high High
Memory usage N/A (managed) Medium High
CPU usage N/A (managed) Low Medium

3.2 Feature Comparison

Feature Amazon API Gateway Kong Gateway Istio
Authentication/authorization ✅ Full support ✅ Full support ✅ Full support
Load balancing ✅ Supported ✅ Full support ✅ Advanced support
API versioning ✅ Supported ✅ Supported ✅ Supported
Monitoring ✅ CloudWatch ✅ Various options ✅ Prometheus
Caching ✅ Supported ✅ Plugin ✅ Supported
Request transformation ✅ Supported ✅ Full support ✅ Supported
Service discovery ✅ AWS integration ✅ Various backends ✅ Kubernetes integration

3.3 Cost Comparison

Amazon API Gateway

Kong Gateway

Istio

3.4 Community Size and Ecosystem

Amazon API Gateway

Kong Gateway

Istio

4. Selection Criteria and Recommendations

4.1 When to Choose Amazon API Gateway

4.2 When to Choose Kong Gateway

4.3 When to Choose Istio

5. Best Practices and Precautions

5.1 Common Best Practices

Security

yaml
# 보안 헤더 설정 예시
response:
  headers:
    - name: "X-Content-Type-Options"
      value: "nosniff"
    - name: "X-Frame-Options"
      value: "DENY"
    - name: "X-XSS-Protection"
      value: "1; mode=block"

Monitoring

API design

5.2 Precautions

Avoiding a single point of failure

Performance optimization

Stronger security

6. Hands-on Example: Building a Simple API Gateway

6.1 Kong Gateway Exercise

Step 1: Run Kong with Docker

bash
# 네트워크 생성
docker network create kong-net

# PostgreSQL 데이터베이스 실행
docker run -d --name kong-database \
  --network=kong-net \
  -p 5432:5432 \
  -e "POSTGRES_USER=kong" \
  -e "POSTGRES_DB=kong" \
  -e "POSTGRES_PASSWORD=kongpass" \
  postgres:13

# Kong 마이그레이션 실행
docker run --rm --network=kong-net \
  -e "KONG_DATABASE=postgres" \
  -e "KONG_PG_HOST=kong-database" \
  -e "KONG_PG_USER=kong" \
  -e "KONG_PG_PASSWORD=kongpass" \
  kong:3.4 kong migrations bootstrap

# Kong 실행
docker run -d --name kong \
  --network=kong-net \
  -e "KONG_DATABASE=postgres" \
  -e "KONG_PG_HOST=kong-database" \
  -e "KONG_PG_USER=kong" \
  -e "KONG_PG_PASSWORD=kongpass" \
  -e "KONG_PROXY_ACCESS_LOG=/dev/stdout" \
  -e "KONG_ADMIN_ACCESS_LOG=/dev/stdout" \
  -e "KONG_PROXY_ERROR_LOG=/dev/stderr" \
  -e "KONG_ADMIN_ERROR_LOG=/dev/stderr" \
  -e "KONG_ADMIN_LISTEN=0.0.0.0:8001" \
  -p 8000:8000 \
  -p 8443:8443 \
  -p 8001:8001 \
  kong:3.4

Step 2: Register services and routes

bash
# 백엔드 서비스 등록
curl -i -X POST http://localhost:8001/services/ \
  --data "name=example-service" \
  --data "url=http://httpbin.org"

# 라우트 등록
curl -i -X POST http://localhost:8001/services/example-service/routes \
  --data "hosts[]=example.com"

# 테스트
curl -i -X GET http://localhost:8000/get \
  --header "Host: example.com"

6.2 Amazon API Gateway Exercise (Using the AWS CLI)

bash
# API 생성
aws apigateway create-rest-api \
  --name "example-api" \
  --description "Example API Gateway"

# 리소스 생성
aws apigateway create-resource \
  --rest-api-id {api-id} \
  --parent-id {root-resource-id} \
  --path-part "users"

# 메서드 생성
aws apigateway put-method \
  --rest-api-id {api-id} \
  --resource-id {resource-id} \
  --http-method GET \
  --authorization-type NONE

# 통합 설정
aws apigateway put-integration \
  --rest-api-id {api-id} \
  --resource-id {resource-id} \
  --http-method GET \
  --type HTTP \
  --integration-http-method GET \
  --uri "http://httpbin.org/get"

# 배포
aws apigateway create-deployment \
  --rest-api-id {api-id} \
  --stage-name prod

7. Performance Optimization and Monitoring

7.1 Performance Optimization Strategies

Caching strategy

Connection pooling

yaml
# Kong 연결 풀 설정 예시
upstream:
  healthchecks:
    active:
      http_path: "/health"
      healthy:
        interval: 10
        successes: 3
      unhealthy:
        interval: 10
        http_failures: 3

Request limiting

yaml
# Rate Limiting 플러그인 설정
plugins:
- name: rate-limiting
  config:
    minute: 100
    hour: 1000
    policy: local

7.2 Monitoring and Alerts

Key metrics

Example Grafana dashboard

json
{
  "dashboard": {
    "title": "API Gateway Metrics",
    "panels": [
      {
        "title": "Request Rate",
        "type": "graph",
        "targets": [
          {
            "expr": "sum(rate(kong_http_requests_total[5m]))",
            "legendFormat": "Total Requests/sec"
          }
        ]
      },
      {
        "title": "Response Time",
        "type": "graph",
        "targets": [
          {
            "expr": "histogram_quantile(0.95, sum(rate(kong_request_duration_ms_bucket[5m])) by (le))",
            "legendFormat": "95th percentile"
          }
        ]
      }
    ]
  }
}

8. Security Enhancements

8.1 Authentication and Authorization

JWT authentication example (Kong)

bash
# JWT 플러그인 활성화
curl -X POST http://localhost:8001/services/example-service/plugins \
  --data "name=jwt"

# Consumer 생성
curl -X POST http://localhost:8001/consumers \
  --data "username=testuser"

# JWT 자격 증명 생성
curl -X POST http://localhost:8001/consumers/testuser/jwt \
  --data "key=a36c3049b36249a3c9f8891cb127243c" \
  --data "secret=e71829c351aa4242c2719cbfbe671c09"

OAuth 2.0 configuration (Amazon API Gateway)

json
{
  "authorizerUri": "arn:aws:apigateway:region:lambda:path/2015-03-31/functions/function-arn/invocations",
  "authorizerCredentials": "arn:aws:iam::account-id:role/role-name",
  "authorizerResultTtlInSeconds": 300,
  "identitySource": "method.request.header.Authorization",
  "type": "TOKEN"
}

8.2 API Security Best Practices

Input validation

yaml
# Kong Request Validation 플러그인
plugins:
- name: request-validator
  config:
    version: draft4
    body_schema: |
      {
        "type": "object",
        "properties": {
          "name": {"type": "string"},
          "email": {"type": "string", "format": "email"}
        },
        "required": ["name", "email"]
      }

CORS configuration

yaml
# CORS 플러그인 설정
plugins:
- name: cors
  config:
    origins:
    - "https://myapp.com"
    methods:
    - GET
    - POST
    headers:
    - Accept
    - Content-Type
    - Authorization
    exposed_headers:
    - X-Auth-Token
    max_age: 3600
    credentials: true

9. Troubleshooting Guide

9.1 Common Problems

High latency

Authentication failures

Performance degradation

bash
# Kong 성능 모니터링
curl -s http://localhost:8001/status | jq

# 연결 상태 확인
curl -s http://localhost:8001/services/example-service/health

# 업스트림 타겟 확인
curl -s http://localhost:8001/upstreams/example-upstream/targets

9.2 Log Analysis

Structured logging

json
{
  "timestamp": "2024-01-15T10:30:00Z",
  "level": "INFO",
  "service": "api-gateway",
  "method": "GET",
  "path": "/api/users",
  "status": 200,
  "duration": 150,
  "user_id": "user123",
  "correlation_id": "req-abc123"
}

Log aggregation and analysis

yaml
# Fluentd 설정 예시
<source>
  @type tail
  tag kong.access
  path /var/log/kong/access.log
  pos_file /var/log/fluentd/kong-access.log.pos
  format json
</source>

<match kong.access>
  @type elasticsearch
  host elasticsearch.example.com
  port 9200
  index_name kong-logs
</match>

10. Outlook and Future Development

10.1 Technology Trends

Serverless integration

AI/ML integration

GraphQL support

10.2 Industry Trends

Cloud native

Stronger security

Conclusion

An API gateway is an essential component of modern application architecture. Each solution has different strengths and weaknesses, so consider the following factors when choosing one.

Consider Amazon API Gateway for early-stage projects or rapid development, Kong Gateway when high performance and flexibility are needed, and Istio for complex microservices environments.

Above all, understand your current requirements accurately and consider future growth when selecting a solution. During implementation, make active use of each tool's official documentation and community.


This guide was written as of 2024 and reflects the latest versions and features of each solution at that time. Refer to the latest documentation when implementing it.

Diagram

100%

Drag to pan; pinch or use the wheel to zoom. Keyboard: arrow keys pan, + − zoom, 0 fits, Esc closes. The same content is in “Read the diagram as text” below the figure.