mcpField
A
api-gateway-patterns

api-gateway-patterns

github.com/manutejクラウド・DevOps62481 回インストール40 週間前に更新
リポジトリ

api-gateway-patterns について

api-gateway-patternsは、Kongを使った本番向けAPIゲートウェイの設計・運用を扱うスキルです。マイクロサービスのゲートウェイを構築するチーム向けに、ルーティング、セキュリティ、トラフィック制御、可観測性のパターンを説明します。

主な機能

  1. 01Kongのゲートウェイ構成とエンティティ
  2. 02パス、ヘッダー、メソッド、ホストによるルーティング
  3. 03レート制限と利用枠
  4. 04APIキー、JWT、OAuth 2.0、OIDC、mTLS
  5. 05ロードバランシングとカナリア配信
  6. 06ログ、監視、APIライフサイクルの指針

活用シーン

  1. 01マイクロサービス間のリクエスト振り分け
  2. 02ゲートウェイでの認証とトラフィックポリシー適用
  3. 03重み付けトラフィックによるAPIバージョン展開
  4. 04ゲートウェイのセキュリティと耐障害性の計画

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/manutej/luxor-claude-marketplace --skill api-gateway-patterns

インストール後、Claude Code で/api-gateway-patternsを入力して読み込まれたか確認します。

同梱ファイルEXAMPLES.mdREADME.md

詳細

API ゲートウェイのパターン

Kong と業界のベストプラクティスを活用して、本番環境に対応した API ゲートウェイを実装するための包括的なスキルです。マイクロサービスアーキテクチャ向けの高度なルーティング、認証、レート制限、ロードバランシング、トラフィック管理、可観測性のパターンを網羅しています。

このスキルを使用する場面

次のような場合に、このスキルを使用します。

  • マイクロサービスアーキテクチャ向けに API ゲートウェイを実装する
  • トラフィックのルーティング、ロードバランシング、サービスディスカバリーを管理する
  • ゲートウェイレベルで認証と認可を実装する
  • レート制限、クォータ、トラフィックポリシーを適用する
  • API トラフィックに可観測性、ログ記録、モニタリングを追加する
  • リクエスト/レスポンスの変換とキャッシュを実装する
  • API のバージョン管理と非推奨化戦略を管理する
  • サーキットブレーカーとレジリエンスパターンを設定する
  • 複数環境への API デプロイを構成する
  • API セキュリティポリシー(CORS、CSRF、WAF)を実装する
  • 開発者ポータルと API ドキュメントを構築する
  • 開発から本番環境までの API ライフサイクルを管理する

コアコンセプト

API ゲートウェイアーキテクチャ

API ゲートウェイは、クライアントアプリケーションの単一のエントリーポイントとして機能します。リクエストを適切なバックエンドサービスにルーティングしながら、横断的な関心事にも対応します。

  • リバースプロキシ:クライアントのリクエストをバックエンドサービスにルーティングします
  • API コンポジション:複数のサービス呼び出しを集約し、単一のレスポンスを返します
  • プロトコル変換:プロトコル間(HTTP、gRPC、WebSocket)の変換を行います
  • 横断的な関心事:認証、ログ記録、レート制限、キャッシュ
  • トラフィック管理:ロードバランシング、サーキットブレーカー、リトライ
  • セキュリティ:SSL 終端、API キーの検証、OAuth2 フロー
主なゲートウェイコンポーネント
  1. サービス:ゲートウェイがプロキシする上流 API
  2. ルート:サービスへのルーティングを決定するリクエスト照合ルール
  3. アップストリーム:サービスインスタンスのロードバランサー構成
  4. プラグイン:機能(認証、ログ記録など)を提供する拡張可能なミドルウェア
  5. コンシューマー:認証情報を持つ API クライアント
  6. 証明書:セキュアな通信のための SSL/TLS 証明書
  7. SNI:マルチドメイン SSL のためのサーバー名表示
Kong Gateway の基礎

Kong はクラウドネイティブで、プラットフォームに依存せず、スケーラブルな API ゲートウェイです。

アーキテクチャ:

  • コントロールプレーン:構成管理用の Admin API
  • データプレーン:実行時のトラフィックを処理するプロキシレイヤー
  • データベース:構成を保存する PostgreSQL または Cassandra(DB レスモードも利用可能)
  • プラグインシステム:カスタムロジックを追加できる Lua ベースの拡張機能

コアエンティティ:

Service (upstream API)
  └── Routes (request matching)
       └── Plugins (features/policies)

Upstream (load balancer)
  └── Targets (service instances)

Consumer (API client)
  └── Credentials (auth keys/tokens)
       └── Plugins (consumer-specific policies)

ルーティングパターン

パターン 1:パスベースのルーティング

URL パスに基づいて、リクエストを異なるバックエンドサービスにルーティングします。

用途: 異なる URL プレフィックス(例:/users、/orders、/products)を持つマイクロサービス

構成:

# Users Service
service:
  name: users-service
  url: http://users-api:8001

routes:
  - name: users-route
    paths:
      - /users
      - /api/users
    strip_path: true
    methods:
      - GET
      - POST
      - PUT
      - DELETE

# Orders Service
service:
  name: orders-service
  url: http://orders-api:8002

routes:
  - name: orders-route
    paths:
      - /orders
      - /api/orders
    strip_path: true

主なオプション:

  • strip_path: true - プロキシする前に一致したパスを削除します(例:/users/123 → /123)
  • strip_path: false - パス全体を保持します(例:/users/123 → /users/123)
  • preserve_host: true - 元の Host ヘッダーをアップストリームに転送します
パターン 2:ヘッダーベースのルーティング

A/B テスト、カナリアデプロイ、API バージョン管理のために、HTTP ヘッダーに基づいてルーティングします。

用途: 新しい API バージョンや機能フラグの段階的な展開

構成:

# V1 Service (stable)
service:
  name: api-v1
  url: http://api-v1:8001

routes:
  - name: api-v1-route
    paths:
      - /api
    headers:
      X-API-Version:
        - "1"
        - "1.0"

# V2 Service (beta)
service:
  name: api-v2
  url: http://api-v2:8002

routes:
  - name: api-v2-route
    paths:
      - /api
    headers:
      X-API-Version:
        - "2"
        - "2.0"

# Default route (no version header)
routes:
  - name: api-default
    paths:
      - /api
    # Routes to V1 by default

高度なヘッダールーティング:

# Mobile vs Web routing
routes:
  - name: mobile-api
    headers:
      User-Agent:
        - ".*Mobile.*"
        - ".*Android.*"
        - ".*iOS.*"
    service: mobile-optimized-api

  - name: web-api
    headers:
      User-Agent:
        - ".*Chrome.*"
        - ".*Firefox.*"
        - ".*Safari.*"
    service: web-api
パターン 3:メソッドベースのルーティング

異なる HTTP メソッドを、専用のサービスにルーティングします。

用途: CQRS パターン — 読み取りサービスと書き込みサービスの分離

構成:

# Read Service (queries)
service:
  name: query-service
  url: http://read-api:8001

routes:
  - name: read-operations
    paths:
      - /api/resources
    methods:
      - GET
      - HEAD
      - OPTIONS

# Write Service (commands)
service:
  name: command-service
  url: http://write-api:8002

routes:
  - name: write-operations
    paths:
      - /api/resources
    methods:
      - POST
      - PUT
      - PATCH
      - DELETE
パターン 4:ホストベースのルーティング

リクエストされたホスト名に基づいて、マルチテナントアプリケーション向けにルーティングします。

用途: 顧客や環境ごとに異なるサブドメインを使用する場合

構成:

# Tenant A
service:
  name: tenant-a-api
  url: http://tenant-a:8001

routes:
  - name: tenant-a-route
    hosts:
      - tenant-a.api.example.com
      - a.api.example.com

# Tenant B
service:
  name: tenant-b-api
  url: http://tenant-b:8002

routes:
  - name: tenant-b-route
    hosts:
      - tenant-b.api.example.com
      - b.api.example.com

# Wildcard for dynamic tenants
routes:
  - name: dynamic-tenant
    hosts:
      - "*.api.example.com"
    service: multi-tenant-api
パターン 5:重み付けルーティング(カナリアデプロイ)

サービスのバージョン間でトラフィックを段階的に移行します。

実装:

# Create two upstreams with weight distribution
upstream:
  name: api-upstream
  algorithm: round-robin

targets:
  - target: api-v1:8001
    weight: 90  # 90% traffic to stable version

  - target: api-v2:8002
    weight: 10  # 10% traffic to canary version

service:
  name: api-service
  host: api-upstream  # Points to upstream

routes:
  - name: api-route
    paths:
      - /api

段階的なロールアウト戦略:

  1. 開始:v1 が 100%、v2 が 0%
  2. フェーズ 1:v1 が 90%、v2 が 10%(メトリクスを監視)
  3. フェーズ 2:v1 が 75%、v2 が 25%
  4. フェーズ 3:v1 が 50%、v2 が 50%
  5. フェーズ 4:v1 が 25%、v2 が 75%
  6. 完了:v1 が 0%、v2 が 100%

レート制限のパターン

パターン 1:グローバルレート制限

グローバルな制限を適用して、API 全体を不正利用から保護します。

ユースケース: DDoS 攻撃を防ぎ、公平な利用を確保する

設定:

plugins:
  - name: rate-limiting
    config:
      minute: 1000
      hour: 10000
      day: 100000
      policy: local  # or 'cluster', 'redis'
      fault_tolerant: true
      hide_client_headers: false
      limit_by: ip  # or 'consumer', 'credential', 'service'

ポリシーの選択肢:

  • local:メモリ内で管理し、単一ノードで動作します(クラスターセーフではありません)
  • cluster:データベースを介して Kong ノード間で共有します
  • redis:Redis を介した高性能な分散レート制限です
パターン 2:コンシューマー別レート制限

API コンシューマー(ティア)ごとに異なる制限を設定します。

ユースケース: ティア別料金を設定したフリーミアムモデル

設定:

# Free tier consumer
consumer:
  username: free-user-123

plugins:
  - name: rate-limiting
    consumer: free-user-123
    config:
      minute: 10
      hour: 100
      day: 1000

# Premium tier consumer
consumer:
  username: premium-user-456

plugins:
  - name: rate-limiting
    consumer: premium-user-456
    config:
      minute: 1000
      hour: 10000
      day: 100000

# Enterprise tier (unlimited)
consumer:
  username: enterprise-user-789
# No rate limiting plugin for enterprise
パターン 3:エンドポイント別レート制限

API エンドポイントごとに異なる制限を設定します。

ユースケース: 高コストな処理を保護しつつ、低コストな処理にはより高いレートを許可する

設定:

# Expensive search endpoint - strict limits
routes:
  - name: search-route
    paths:
      - /api/search

plugins:
  - name: rate-limiting
    route: search-route
    config:
      minute: 10
      hour: 100

# Regular CRUD endpoints - moderate limits
routes:
  - name: users-route
    paths:
      - /api/users

plugins:
  - name: rate-limiting
    route: users-route
    config:
      minute: 100
      hour: 1000

# Health check - no limits
routes:
  - name: health-route
    paths:
      - /health
# No rate limiting plugin
パターン 4:スライディングウィンドウレート制限

スライディングウィンドウを使用して、より正確なレート制限を実現します。

ユースケース: 固定ウィンドウの境界を悪用するバースト攻撃を防ぐ

設定:

plugins:
  - name: rate-limiting-advanced  # Kong Enterprise
    config:
      limit:
        - 100  # Limit value
      window_size:
        - 60  # Window in seconds
      window_type: sliding
      retry_after_jitter_max: 1
      sync_rate: 0.5
      namespace: my-api
      strategy: redis
      redis:
        host: redis
        port: 6379
        database: 0

スライディングウィンドウと固定ウィンドウの比較:

  • 固定:1 分あたり 100 件のリクエスト。毎分 00 秒にリセットされます
  • スライディング:任意の 60 秒間に 100 件のリクエスト
  • スライディングウィンドウは、ウィンドウ境界でのバーストの悪用を防ぎます
パターン 5:クォータ管理

長期的な利用クォータ(月単位、年単位)を管理します。

ユースケース: プランに基づいてサブスクリプションの制限を適用する

設定:

plugins:
  - name: request-termination
    enabled: false  # Will be enabled when quota exceeded

plugins:
  - name: acme  # Custom quota tracking plugin
    config:
      quota:
        month: 1000000
      reset_on: first_day
      consumer_groups:
        - name: starter
          quota: 10000
        - name: professional
          quota: 100000
        - name: enterprise
          quota: 1000000

認証のパターン

パターン 1:API キー認証

基本的なセキュリティのため、シンプルな API キー検証を行います。

ユースケース: 内部 API、開発環境、シンプルな連携

設定:

# Enable key-auth plugin
plugins:
  - name: key-auth
    config:
      key_names:
        - apikey
        - api-key
        - X-API-Key
      hide_credentials: true
      anonymous: null  # Require authentication
      run_on_preflight: false

# Create consumer with API key
consumers:
  - username: mobile-app
    custom_id: app-001

# Add key credential
keyauth_credentials:
  - consumer: mobile-app
    key: sk_live_abc123def456ghi789

使用方法:

curl -H "apikey: sk_live_abc123def456ghi789" \
  https://api.example.com/users

ベストプラクティス:

  • 暗号学的に安全なランダムキー(最低 32 文字)を使用する
  • キーを定期的にローテーションする
  • 環境ごとに異なるキーを使用する
  • キーをバージョン管理に絶対にコミットしない
  • 通信中のキーを保護するため HTTPS を使用する
パターン 2:JWT 認証

ペイロードを検証するトークンベースの認証です。

ユースケース: 最新の SPA、モバイルアプリ、マイクロサービス

設定:

plugins:
  - name: jwt
    config:
      uri_param_names:
        - jwt
      cookie_names:
        - jwt_token
      header_names:
        - Authorization
      claims_to_verify:
        - exp
        - nbf
      key_claim_name: iss
      secret_is_base64: false
      anonymous: null
      run_on_preflight: false
      maximum_expiration: 3600  # 1 hour max

# Create consumer with JWT credential
consumers:
  - username: web-app

jwt_secrets:
  - consumer: web-app
    key: myapp-issuer
    algorithm: HS256
    secret: my-secret-key-change-in-production

RS256(非対称)設定:

jwt_secrets:
  - consumer: mobile-app
    key: mobile-issuer
    algorithm: RS256
    rsa_public_key: |
      -----BEGIN PUBLIC KEY-----
      MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
      -----END PUBLIC KEY-----

トークン形式:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJteWFwcC1pc3N1ZXIiLCJzdWIiOiJ1c2VyMTIzIiwiZXhwIjoxNjQwOTk1MjAwfQ.signature
パターン 3:OAuth 2.0 認可

サードパーティ連携向けの完全な OAuth 2.0 フローです。

ユースケース: パブリック API、サードパーティ開発者によるアクセス

サポートされているフロー:

  • 認可コードフロー
  • クライアントクレデンシャルフロー
  • インプリシットフロー(非推奨)
  • リソースオーナーパスワードフロー

設定:

plugins:
  - name: oauth2
    config:
      scopes:
        - read
        - write
        - admin
      mandatory_scope: true
      token_expiration: 3600
      enable_authorization_code: true
      enable_client_credentials: true
      enable_implicit_grant: false
      enable_password_grant: false
      hide_credentials: true
      accept_http_if_already_terminated: false
      refresh_token_ttl: 1209600  # 14 days

# Create OAuth application
oauth2_credentials:
  - consumer: third-party-app
    name: "Partner Integration"
    client_id: client_abc123
    client_secret: secret_xyz789
    redirect_uris:
      - https://partner.com/callback

認可コードフロー:

# 1. Get authorization code
GET /oauth2/authorize?
  response_type=code&
  client_id=client_abc123&
  redirect_uri=https://partner.com/callback&
  scope=read write

# 2. Exchange code for token
POST /oauth2/token
  grant_type=authorization_code&
  client_id=client_abc123&
  client_secret=secret_xyz789&
  code=AUTH_CODE&
  redirect_uri=https://partner.com/callback
パターン 4:OpenID Connect(OIDC)

ID プロバイダーとのエンタープライズ SSO 連携です。

ユースケース: Google、Okta、Auth0、Azure AD を使用したエンタープライズ認証

設定:

plugins:
  - name: openid-connect
    config:
      issuer: https://accounts.google.com
      client_id: your-client-id.apps.googleusercontent.com
      client_secret: your-client-secret
      redirect_uri:
        - https://api.example.com/callback
      scopes:
        - openid
        - email
        - profile
      auth_methods:
        - authorization_code
      login_redirect_uri: https://app.example.com/login
      logout_redirect_uri: https://app.example.com/logout
      ssl_verify: true
      session_secret: change-this-secret-in-production
      discovery: https://accounts.google.com/.well-known/openid-configuration

複数プロバイダーの設定:

# Google OIDC
plugins:
  - name: openid-connect
    route: google-login
    config:
      issuer: https://accounts.google.com
      client_id: google-client-id
      client_secret: google-secret

# Azure AD OIDC
plugins:
  - name: openid-connect
    route: azure-login
    config:
      issuer: https://login.microsoftonline.com/tenant-id/v2.0
      client_id: azure-client-id
      client_secret: azure-secret

# Okta OIDC
plugins:
  - name: openid-connect
    route: okta-login
    config:
      issuer: https://dev-123456.okta.com
      client_id: okta-client-id
      client_secret: okta-secret
パターン 5:mTLS(相互 TLS)認証

サービス間のセキュリティに証明書ベースの認証を使用します。

ユースケース: マイクロサービス間の相互認証、B2B 連携

設定:

# Enable mTLS plugin
plugins:
  - name: mtls-auth
    config:
      ca_certificates:
        - ca-cert-id-1
        - ca-cert-id-2
      skip_consumer_lookup: false
      anonymous: null
      revocation_check_mode: SKIP  # or IGNORE_CA_ERROR, STRICT

# Upload CA certificate
ca_certificates:
  - cert: |
      -----BEGIN CERTIFICATE-----
      MIIDXTCCAkWgAwIBAgIJAKL...
      -----END CERTIFICATE-----

# Create consumer mapped to client certificate
consumers:
  - username: service-a
    custom_id: service-a-001

# Map certificate to consumer
mtls_auth_credentials:
  - consumer: service-a
    subject_name: CN=service-a,O=MyOrg

負荷分散のパターン

パターン 1:ラウンドロビン負荷分散

サービスインスタンス間でリクエストを均等に分散します。

ユースケース: 容量が均一なステートレスサービス

設定:

upstreams:
  - name: api-upstream
    algorithm: round-robin
    slots: 10000
    healthchecks:
      active:
        type: http
        http_path: /health
        healthy:
          interval: 5
          successes: 2
        unhealthy:
          interval: 5
          http_failures: 3
          timeouts: 3
      passive:
        healthy:
          successes: 5
        unhealthy:
          http_failures: 5
          timeouts: 2

targets:
  - upstream: api-upstream
    target: api-1.internal:8001
    weight: 100

  - upstream: api-upstream
    target: api-2.internal:8001
    weight: 100

  - upstream: api-upstream
    target: api-3.internal:8001
    weight: 100
パターン 2:重み付け負荷分散

サーバーの容量に応じた比率でトラフィックを分散します。

ユースケース: 容量が異なるサーバーが混在する環境

設定:

upstreams:
  - name: api-upstream
    algorithm: round-robin

targets:
  # Powerful server - 50% traffic
  - target: api-1.internal:8001
    weight: 500

  # Medium server - 30% traffic
  - target: api-2.internal:8001
    weight: 300

  # Small server - 20% traffic
  - target: api-3.internal:8001
    weight: 200

重みの分布:

  • 重みの合計:500 + 300 + 200 = 1000
  • api-1:500/1000 = リクエストの 50%
  • api-2:300/1000 = リクエストの 30%
  • api-3:200/1000 = リクエストの 20%
パターン 3:コンシステントハッシュ

同じクライアントからのリクエストを同じバックエンドにルーティングします(セッションアフィニティ)。

ユースケース: セッションの永続化が必要なステートフルサービス

設定:

upstreams:
  - name: api-upstream
    algorithm: consistent-hashing
    hash_on: header
    hash_on_header: X-User-ID
    hash_fallback: ip
    hash_fallback_header: X-Forwarded-For

targets:
  - target: api-1.internal:8001
  - target: api-2.internal:8001
  - target: api-3.internal:8001

ハッシュのオプション:

  • hash_on: none - ランダムに分散します
  • hash_on: consumer - 認証済みのコンシューマーに基づいてハッシュ化します
  • hash_on: ip - クライアントの IP アドレスに基づいてハッシュ化します
  • hash_on: header - 指定したヘッダー値に基づいてハッシュ化します
  • hash_on: cookie - Cookie の値に基づいてハッシュ化します
  • hash_on: path - リクエストパスに基づいてハッシュ化します

ハッシュタイプ別のユースケース:

  • ユーザーセッション:hash_on: header(X-User-ID)
  • 地理的なルーティング:hash_on: ip
  • テナントの分離:hash_on: header(X-Tenant-ID)
  • ショッピングカート:hash_on: cookie(session_id)
パターン 4:最少接続数

アクティブな接続数が最も少ないサーバーにルーティングします。

ユースケース: 長時間接続(WebSocket、ストリーミング)

設定:

upstreams:
  - name: websocket-upstream
    algorithm: least-connections

targets:
  - target: ws-1.internal:8001
  - target: ws-2.internal:8001
  - target: ws-3.internal:8001

使用する状況:

  • WebSocket サーバー
  • ロングポーリングのエンドポイント
  • ストリーミング API(SSE、gRPC ストリーミング)
  • リクエストの処理時間にばらつきがあるサービス
パターン 5:アクティブヘルスチェック

正常でないターゲットを自動的にローテーションから除外します。

ユースケース: 自動フェイルオーバーによる高可用性

設定:

upstreams:
  - name: api-upstream
    healthchecks:
      active:
        type: http
        http_path: /health
        https_verify_certificate: true
        concurrency: 10
        timeout: 1
        headers:
          X-Health-Check:
            - gateway
        healthy:
          interval: 5  # Check every 5 seconds
          http_statuses:
            - 200
            - 302
          successes: 2  # 2 successes → healthy
        unhealthy:
          interval: 5
          http_statuses:
            - 429
            - 500
            - 503
          http_failures: 3  # 3 failures → unhealthy
          tcp_failures: 3
          timeouts: 3

      passive:
        type: http
        healthy:
          http_statuses:
            - 200
            - 201
            - 202
            - 203
            - 204
            - 205
            - 206
            - 207
            - 208
            - 226
            - 300
            - 301
            - 302
          successes: 5
        unhealthy:
          http_statuses:
            - 429
            - 500
            - 503
          http_failures: 5
          tcp_failures: 2
          timeouts: 2

トラフィック制御パターン

パターン 1:サーキットブレーカー

下流サービスが正常でない場合にすばやく失敗させ、障害の連鎖を防ぎます。

ユースケース: 依存先に障害が発生した際にシステムを保護します

設定:

plugins:
  - name: proxy-cache-advanced  # Kong Enterprise
    config:
      # Serve stale cache during outages
      cache_control: false

plugins:
  - name: request-termination
    enabled: false  # Enabled programmatically on circuit open

# Custom circuit breaker (via passive health checks)
upstreams:
  - name: api-upstream
    healthchecks:
      passive:
        unhealthy:
          http_failures: 5  # Open circuit after 5 failures
          timeouts: 3
        healthy:
          successes: 3  # Close circuit after 3 successes

サーキットの状態:

  1. Closed:通常の動作状態で、リクエストはそのまま通過します
  2. Open:障害が検出され、リクエストは直ちに失敗します
  3. Half-Open:サービスが復旧したかをテストするため、限られた数のリクエストを許可します
パターン 2:リクエストのタイムアウト

時間のかかるリクエストによってリソースが占有されるのを防ぎます。

ユースケース: 応答の遅いバックエンドによるリソース枯渇を防ぎます

設定:

services:
  - name: api-service
    url: http://api.internal:8001
    read_timeout: 5000    # 5 seconds
    write_timeout: 5000   # 5 seconds
    connect_timeout: 2000 # 2 seconds

plugins:
  - name: request-timeout  # Additional timeout enforcement
    config:
      http_timeout: 5000
      stream_timeout: 30000

タイムアウト戦略:

connect_timeout: 2s   → Connection establishment
write_timeout: 5s     → Writing request to upstream
read_timeout: 5s      → Reading response from upstream
http_timeout: 5s      → Overall HTTP transaction
パターン 3:リトライロジック

指数バックオフを使用して、失敗したリクエストを自動的に再試行します。

ユースケース: 分散システムにおける一時的な障害に対処します

設定:

services:
  - name: api-service
    retries: 5  # Maximum retry attempts

plugins:
  - name: proxy-retry  # Custom retry plugin
    config:
      retries: 3
      retry_on:
        - 500
        - 502
        - 503
        - 504
      backoff:
        type: exponential
        base: 2
        max: 30
      jitter: 0.5

リトライのスケジュール:

Attempt 1: Immediate
Attempt 2: 2s + jitter
Attempt 3: 4s + jitter
Attempt 4: 8s + jitter
Attempt 5: 16s + jitter

冪等性に関する考慮事項:

  • GET、HEAD、PUT、DELETE は再試行します(冪等)
  • 冪等性キーを使用しない限り、POST は再試行しないでください
  • Idempotency-Key ヘッダーを確認します
パターン 4:リクエストサイズの制限

大きなペイロードを使った攻撃やメモリ枯渇を防ぎます。

ユースケース: サイズが大きすぎるリクエストボディから保護します

設定:

plugins:
  - name: request-size-limiting
    config:
      allowed_payload_size: 10  # Megabytes
      size_unit: megabytes
      require_content_length: true

# Different limits per route
plugins:
  - name: request-size-limiting
    route: file-upload
    config:
      allowed_payload_size: 100  # Allow larger files

  - name: request-size-limiting
    route: api-endpoints
    config:
      allowed_payload_size: 1  # Strict limit for APIs
パターン 5:トラフィックシェーピング(スロットリング)

単純なレート制限よりも細かくリクエストレートを制御します。

ユースケース: トラフィックの急増を平準化し、バックエンドの過負荷を防ぎます

設定:

plugins:
  - name: request-transformer-advanced
    config:
      # Add delay headers for client-side throttling
      add:
        headers:
          - "Retry-After:60"

plugins:
  - name: proxy-cache-advanced
    config:
      # Cache responses to reduce backend load
      cache_ttl: 300
      strategy: memory

# Upstream connection limits
upstreams:
  - name: api-upstream
    slots: 1000  # Limit concurrent connections

リクエスト/レスポンスの変換

パターン 1:リクエストヘッダーの操作

プロキシする前に、リクエストヘッダーを追加、変更、または削除します。

ユースケース: 認証、トレース、またはコンテキスト用のヘッダーを追加します

設定:

plugins:
  - name: request-transformer
    config:
      add:
        headers:
          - "X-Gateway:kong"
          - "X-Request-ID:$(uuid)"
          - "X-Forwarded-Proto:https"
      append:
        headers:
          - "X-Trace-Id:$(uuid)"
      replace:
        headers:
          - "User-Agent:Kong-Gateway/3.0"
      remove:
        headers:
          - "X-Internal-Secret"

高度な変換:

plugins:
  - name: request-transformer-advanced
    config:
      add:
        headers:
          - "X-Consumer-Username:$(consumer_username)"
          - "X-Consumer-ID:$(consumer_id)"
          - "X-Authenticated-Scope:$(authenticated_credential.scope)"
          - "X-Client-IP:$(remote_addr)"
      rename:
        headers:
          - "Authorization:X-Original-Auth"
パターン 2:レスポンスヘッダーの操作

クライアントに返す前に、レスポンスヘッダーを変更します。

ユースケース: セキュリティヘッダー、CORS、キャッシュディレクティブを追加します

設定:

plugins:
  - name: response-transformer
    config:
      add:
        headers:
          - "X-Gateway-Response-Time:$(latencies.request)"
          - "X-Server-ID:$(upstream_addr)"
      remove:
        headers:
          - "X-Powered-By"
          - "Server"

# Security headers
plugins:
  - name: response-transformer
    config:
      add:
        headers:
          - "Strict-Transport-Security:max-age=31536000; includeSubDomains"
          - "X-Content-Type-Options:nosniff"
          - "X-Frame-Options:DENY"
          - "X-XSS-Protection:1; mode=block"
          - "Content-Security-Policy:default-src 'self'"
パターン 3:リクエストボディの変換

転送する前に、リクエストのペイロードを変更します。

ユースケース: フィールドの追加、形式の変換、入力のサニタイズを行います

設定:

plugins:
  - name: request-transformer-advanced
    config:
      add:
        body:
          - "gateway_timestamp:$(timestamp)"
          - "request_id:$(uuid)"
      remove:
        body:
          - "internal_field"
      replace:
        body:
          - "api_version:v2"
パターン 4:GraphQL から REST への変換

REST API を GraphQL エンドポイントとして公開します。

ユースケース: レガシーな REST API を GraphQL でモダナイズします

設定:

plugins:
  - name: graphql-proxy-cache-advanced
    config:
      strategy: memory

# Define GraphQL schema mapping
graphql_schemas:
  - name: users-graphql
    schema: |
      type Query {
        user(id: ID!): User
        users: [User]
      }

      type User {
        id: ID!
        name: String!
        email: String!
      }
    resolvers:
      Query:
        user: http://users-api/users/{id}
        users: http://users-api/users
パターン 5:プロトコル変換

HTTP、gRPC、WebSocket の各プロトコル間で変換します。

ユースケース: gRPC サービスを HTTP/JSON 経由で公開します

設定:

# gRPC to HTTP/JSON
plugins:
  - name: grpc-gateway
    config:
      proto: /path/to/service.proto

services:
  - name: grpc-service
    url: grpc://grpc.internal:9000
    protocol: grpc

routes:
  - name: grpc-http-route
    paths:
      - /v1/users
    protocols:
      - http
      - https

キャッシュパターン

パターン 1:レスポンスのキャッシュ

上流からのレスポンスをキャッシュし、バックエンドの負荷を軽減します。

ユースケース: コストの高いクエリをキャッシュし、データベースの負荷を軽減します

設定:

plugins:
  - name: proxy-cache
    config:
      strategy: memory  # or 'redis'
      content_type:
        - "application/json"
        - "text/html"
      cache_ttl: 300  # 5 minutes
      cache_control: false  # Ignore client cache headers
      storage_ttl: 600  # Backend storage TTL
      memory:
        dictionary_name: kong_cache
      vary_headers:
        - "Accept-Language"
        - "X-User-Tier"

Redis ベースのキャッシュ:

plugins:
  - name: proxy-cache-advanced
    config:
      strategy: redis
      cache_ttl: 3600
      redis:
        host: redis.internal
        port: 6379
        database: 0
        password: redis-password
        timeout: 2000
        sentinel_master: mymaster
        sentinel_addresses:
          - redis-sentinel-1:26379
          - redis-sentinel-2:26379
パターン 2:条件付きキャッシュ

ステータスコード、ヘッダー、またはリクエスト条件に基づいてキャッシュします。

ユースケース: 成功したレスポンスのみをキャッシュし、エラーは除外します

設定:

plugins:
  - name: proxy-cache-advanced
    config:
      response_code:
        - 200
        - 301
        - 302
      request_method:
        - GET
        - HEAD
      vary_headers:
        - "Accept"
        - "Accept-Encoding"
      vary_query_params:
        - "page"
        - "limit"
      ignore_uri_case: true
パターン 3:キャッシュの無効化

オンデマンドまたはイベントに基づいてキャッシュを消去します。

ユースケース: データ変更時にキャッシュを更新する

設定:

# Admin API cache purge
POST /cache/purge

# Purge specific endpoint
POST /cache/purge/users

# TTL-based expiration
plugins:
  - name: proxy-cache
    config:
      cache_ttl: 60  # Short TTL for frequently updated data

# Event-based invalidation (custom plugin)
plugins:
  - name: custom-cache-invalidator
    config:
      invalidate_on:
        - POST
        - PUT
        - PATCH
        - DELETE
      propagate: true  # Clear related caches
パターン 4:マルチティアキャッシュ

ゲートウェイとバックエンドにキャッシュを配置します。

ユースケース: 各層でキャッシュヒット率を最大化する

アーキテクチャ:

Client
  ↓
Kong Gateway Cache (L1)
  ↓
Backend API Cache (L2)
  ↓
Database

設定:

# Gateway cache (L1)
plugins:
  - name: proxy-cache
    config:
      strategy: memory
      cache_ttl: 60  # 1 minute

# Backend passes Cache-Control headers
# Gateway respects them if cache_control: true
plugins:
  - name: proxy-cache
    config:
      cache_control: true  # Respect upstream Cache-Control
      vary_headers:
        - "Cache-Control"
パターン 5:サロゲートキーに基づく無効化

キャッシュにタグを付けて、きめ細かな無効化を行います。

ユースケース: 関連するリソースを効率的に無効化する

設定:

# Tag responses with surrogate keys
plugins:
  - name: response-transformer
    config:
      add:
        headers:
          - "Surrogate-Key:user-$(user_id) tenant-$(tenant_id)"

# Invalidate by surrogate key
# Custom plugin or Varnish integration
POST /cache/purge
Headers:
  Surrogate-Key: user-123

セキュリティパターン

パターン 1:CORS(クロスオリジンリソース共有)

制御されたクロスオリジンリクエストを有効にします。

ユースケース: 異なるドメインから API を呼び出す Web アプリ

設定:

plugins:
  - name: cors
    config:
      origins:
        - "https://app.example.com"
        - "https://admin.example.com"
      methods:
        - GET
        - POST
        - PUT
        - PATCH
        - DELETE
        - OPTIONS
      headers:
        - Accept
        - Authorization
        - Content-Type
        - X-Request-ID
      exposed_headers:
        - X-Total-Count
        - X-Page-Number
      credentials: true
      max_age: 3600
      preflight_continue: false

ワイルドカード CORS(開発時のみ):

plugins:
  - name: cors
    config:
      origins:
        - "*"
      methods:
        - "*"
      headers:
        - "*"
      credentials: false  # Must be false with wildcard origins
パターン 2:IP 制限

IP アドレスに基づいて許可または拒否します。

ユースケース: 管理者用 API へのアクセスを社内 IP に制限する

設定:

# Whitelist approach
plugins:
  - name: ip-restriction
    config:
      allow:
        - 10.0.0.0/8
        - 192.168.1.100
        - 203.0.113.0/24

# Blacklist approach
plugins:
  - name: ip-restriction
    config:
      deny:
        - 1.2.3.4
        - 5.6.7.0/24

認証との組み合わせ:

# Admin route: IP + Auth
plugins:
  - name: ip-restriction
    route: admin-api
    config:
      allow:
        - 10.0.0.0/8

  - name: key-auth
    route: admin-api
パターン 3:ボット検出

悪意のあるボットを検出してブロックします。

ユースケース: スクレイピング、ブルートフォース攻撃、スパムを防止する

設定:

plugins:
  - name: bot-detection
    config:
      allow:
        - "googlebot"
        - "bingbot"
        - "slackbot"
      deny:
        - "curl"
        - "wget"
        - "scrapy"
      blacklist_cache_size: 10000
      whitelist_cache_size: 10000
パターン 4:リクエストの検証

スキーマに照らしてリクエストを検証します。

ユースケース: API コントラクトへの準拠を確保し、インジェクションを防止する

設定:

plugins:
  - name: request-validator
    config:
      body_schema: |
        {
          "type": "object",
          "properties": {
            "username": {
              "type": "string",
              "minLength": 3,
              "maxLength": 50
            },
            "email": {
              "type": "string",
              "format": "email"
            },
            "age": {
              "type": "integer",
              "minimum": 18,
              "maximum": 120
            }
          },
          "required": ["username", "email"]
        }
      parameter_schema:
        - name: page
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
パターン 5:WAF(Web アプリケーションファイアウォール)

OWASP Top 10 の脆弱性から保護します。

ユースケース: SQL インジェクション、XSS、パストラバーサルをブロックする

設定:

plugins:
  - name: waf  # Kong Enterprise or ModSecurity plugin
    config:
      rule_sets:
        - owasp_crs
      anomaly_threshold: 5
      paranoia_level: 1
      blocked_status_code: 403

可観測性パターン

パターン 1:リクエストのロギング

監査とデバッグのため、すべての API リクエストを記録します。

ユースケース: コンプライアンス、デバッグ、分析

設定:

plugins:
  - name: file-log
    config:
      path: /var/log/kong/requests.log
      reopen: true

# JSON structured logging
plugins:
  - name: http-log
    config:
      http_endpoint: http://logstash:5000
      method: POST
      content_type: application/json
      timeout: 5000
      keepalive: 60000
      custom_fields_by_lua:
        request_id: "return kong.request.get_header('X-Request-ID')"

複数の送信先へのログ出力:

# Elasticsearch
plugins:
  - name: http-log
    config:
      http_endpoint: http://elasticsearch:9200/_bulk

# Splunk
plugins:
  - name: http-log
    config:
      http_endpoint: https://splunk:8088/services/collector
      headers:
        Authorization: "Splunk token"

# Datadog
plugins:
  - name: datadog
    config:
      host: datadog-agent
      port: 8125
パターン 2:分散トレーシング

マイクロサービス間のリクエストを追跡します。

ユースケース: レイテンシの診断、リクエストの流れの把握

設定:

# Zipkin
plugins:
  - name: zipkin
    config:
      http_endpoint: http://zipkin:9411/api/v2/spans
      sample_ratio: 0.1  # Trace 10% of requests
      include_credential: true
      traceid_byte_count: 16
      header_type: preserve  # or 'jaeger', 'b3', 'w3c'

# Jaeger
plugins:
  - name: opentelemetry
    config:
      endpoint: http://jaeger:14268/api/traces
      resource_attributes:
        service.name: api-gateway
        service.version: 1.0.0
      batch_span_processor:
        max_queue_size: 2048
        batch_timeout: 5000

W3C Trace Context:

plugins:
  - name: opentelemetry
    config:
      propagation:
        default: w3c
      headers:
        - traceparent
        - tracestate
パターン 3:メトリクスの収集

監視用に Prometheus メトリクスを公開します。

ユースケース: ゲートウェイのパフォーマンス、エラー、レイテンシを監視する

設定:

plugins:
  - name: prometheus
    config:
      per_consumer: true
      status_code_metrics: true
      latency_metrics: true
      bandwidth_metrics: true
      upstream_health_metrics: true

# Expose /metrics endpoint
routes:
  - name: metrics
    paths:
      - /metrics
    service: prometheus-service

利用可能なメトリクス:

# Requests
kong_http_requests_total{service,route,code}

# Latency
kong_latency_ms{type,service,route}
kong_request_latency_ms{service,route}
kong_upstream_latency_ms{service,route}

# Bandwidth
kong_bandwidth_bytes{type,service,route}

# Connections
kong_datastore_reachable
kong_nginx_connections_total{state}
パターン 4:ヘルスチェック

ヘルスチェック用エンドポイントを公開します。

ユースケース: Kubernetes の liveness/readiness プローブ

設定:

# Gateway health
routes:
  - name: health
    paths:
      - /health
    plugins:
      - name: request-termination
        config:
          status_code: 200
          message: "OK"

# Detailed status
routes:
  - name: status
    paths:
      - /status
    service: kong-status-service

# Upstream health aggregation
plugins:
  - name: upstream-health-check
    config:
      healthy_threshold: 2
      unhealthy_threshold: 3
パターン 5:エラー追跡

エラーを追跡し、監視システムに報告します。

ユースケース: エラーの事前検出とアラート通知

設定:

# Sentry integration
plugins:
  - name: sentry
    config:
      dsn: https://[email protected]/project
      environment: production
      release: v1.2.3

# Custom error logging
plugins:
  - name: http-log
    config:
      http_endpoint: http://error-tracker:5000
      custom_fields_by_lua:
        error_type: |
          if kong.response.get_status() >= 500 then
            return "server_error"
          elseif kong.response.get_status() >= 400 then
            return "client_error"
          end

マルチ環境パターン

パターン 1:環境の分離

開発、ステージング、本番用の設定を分離します。

ユースケース: 環境間で一貫したデプロイを行う

構成:

config/
  ├── base.yaml          # Shared configuration
  ├── dev.yaml           # Development overrides
  ├── staging.yaml       # Staging overrides
  └── production.yaml    # Production overrides

設定:

# base.yaml
_format_version: "3.0"

services:
  - name: users-api
    url: http://users-service:8001

routes:
  - name: users-route
    service: users-api
    paths:
      - /users

# production.yaml
_format_version: "3.0"

services:
  - name: users-api
    url: https://users-api-prod.internal:8001
    retries: 5
    read_timeout: 5000

plugins:
  - name: rate-limiting
    service: users-api
    config:
      minute: 1000
パターン 2:ブルーグリーンデプロイ

即時ロールバックが可能な、ダウンタイムゼロのデプロイです。

ユースケース: 本番環境へ安全にデプロイする

設定:

# Blue environment (current production)
upstreams:
  - name: api-blue
    targets:
      - target: api-blue-1:8001
      - target: api-blue-2:8001

# Green environment (new version)
upstreams:
  - name: api-green
    targets:
      - target: api-green-1:8001
      - target: api-green-2:8001

# Route points to active environment
services:
  - name: api-service
    host: api-blue  # Switch to api-green for deployment

# Rollback: Switch service.host back to api-blue
パターン 3:カナリアリリース

監視しながら段階的に展開します。

ユースケース: 新しいリリースのリスクを軽減する

設定:

# Canary routing with header
routes:
  - name: api-canary
    paths:
      - /api
    headers:
      X-Canary:
        - "true"
    service: api-v2

routes:
  - name: api-stable
    paths:
      - /api
    service: api-v1

# Weighted canary (10% traffic)
upstreams:
  - name: api-upstream
    targets:
      - target: api-v1:8001
        weight: 90
      - target: api-v2:8001
        weight: 10

カナリアの段階的な展開:

Phase 1: 5% canary, monitor errors
Phase 2: 25% canary, check metrics
Phase 3: 50% canary, verify performance
Phase 4: 100% canary, deprecate old version
パターン 4:機能フラグ

機能を動的に有効化または無効化します。

ユースケース: A/B テスト、機能の段階的な展開

設定:

# Feature flag via header
routes:
  - name: new-feature
    paths:
      - /api/new-feature
    headers:
      X-Feature-Flag:
        - "new-dashboard"
    service: new-feature-service

# Default route (feature disabled)
routes:
  - name: old-feature
    paths:
      - /api/new-feature
    service: old-feature-service

# Consumer-based feature flags
plugins:
  - name: request-transformer
    consumer: beta-users
    config:
      add:
        headers:
          - "X-Feature-Flags:new-dashboard,advanced-search"
パターン 5:マルチリージョンデプロイ

レイテンシを低くするため、最寄りのリージョンにルーティングします。

ユースケース: リージョン間のフェイルオーバーに対応したグローバル API

設定:

# US region
upstreams:
  - name: api-us
    targets:
      - target: api-us-east:8001
      - target: api-us-west:8001

# EU region
upstreams:
  - name: api-eu
    targets:
      - target: api-eu-west:8001
      - target: api-eu-central:8001

# Geographic routing (via DNS or header)
routes:
  - name: us-traffic
    hosts:
      - us.api.example.com
    service: api-us-service

routes:
  - name: eu-traffic
    hosts:
      - eu.api.example.com
    service: api-eu-service

ベストプラクティス

アーキテクチャ設計
  1. 単一責任: ゲートウェイは横断的関心事のみを処理します
  2. ステートレス設計: 水平スケーリングのため、ゲートウェイをステートレスに保ちます
  3. 宣言的な設定: バージョン管理された設定には YAML/JSON を使用します
  4. データベースレスモード: よりシンプルなデプロイには DB-less を使用します
  5. プラグインの最小化: 必要なプラグインのみを有効にします
セキュリティのベストプラクティス
  1. 多層防御:複数のセキュリティメカニズムを組み合わせます
  2. 最小権限:利用者に付与する権限を最小限にします
  3. シークレット管理:認証情報をハードコードしないでください
  4. すべての通信で TLS を使用:すべてのトラフィック(クライアントおよび上流)を暗号化します
  5. レート制限:パブリックエンドポイントは必ず保護します
  6. 入力検証:すべてのリクエストデータを検証します
  7. 定期的な更新:Kong とプラグインを最新の状態に保ちます
パフォーマンスの最適化
  1. キャッシュを有効化:レスポンスを積極的にキャッシュします
  2. コネクションプーリング:上流接続を再利用します
  3. ロードバランシング:負荷を均等に分散します
  4. ヘルスチェック:正常でないターゲットを速やかに除外します
  5. タイムアウト:処理の停止を防ぐため、適切なタイムアウトを設定します
  6. モニタリング:レイテンシ、エラー、スループットを追跡します
  7. リソース制限:メモリと接続数の上限を設定します
運用の卓越性
  1. ロギング:すべてのリクエストを構造化ログに記録します
  2. モニタリング:包括的なメトリクス収集を行います
  3. アラート:異常やエラーを検知したらアラートを発します
  4. ドキュメント:すべてのルートとプラグインを文書化します
  5. テスト:ステージング環境でゲートウェイ設定をテストします
  6. バージョン管理:すべての設定をバージョン管理します
  7. 災害復旧:フェイルオーバーのシナリオを計画します
プラグイン戦略
  1. 順序が重要:プラグインは特定の順序で実行されます
  2. 適切なスコープ設定:グローバル、サービス、ルート、またはコンシューマーに設定します
  3. 徹底的なテスト:プラグインの組み合わせをテストします
  4. 影響をモニタリング:プラグインによるパフォーマンスへのオーバーヘッドを追跡します
  5. カスタムプラグイン:固有のニーズに応じてカスタムプラグインを作成します

プラグインの実行順序:

1. Authentication (key-auth, jwt, oauth2)
2. Security (ip-restriction, bot-detection)
3. Traffic Control (rate-limiting, request-size-limiting)
4. Transformation (request-transformer)
5. Logging (file-log, http-log)
6. Analytics (prometheus, datadog)
設定管理
  1. バージョン管理:すべての設定に Git を使用します
  2. 環境間の一貫性:各環境で設定を統一します
  3. 自動デプロイ:設定変更に CI/CD を使用します
  4. 検証:適用前に設定を検証します
  5. ロールバック計画:問題発生時に速やかにロールバックします
  6. 変更履歴:すべての設定変更を記録します
スケーリングのガイドライン
  1. 水平スケーリング:Kong ノードを追加します
  2. データベースのスケーリング:PostgreSQL を個別にスケーリングします
  3. キャッシュのオフロード:分散キャッシュに Redis を使用します
  4. リージョン別デプロイ:ユーザーに近い場所にデプロイします
  5. CDN 統合:静的コンテンツをオフロードします
  6. 接続数の制限:ワーカーごとの上限を設定します

一般的なユースケース

ユースケース 1:SaaS API プラットフォーム

要件:

  • マルチテナントの分離
  • 段階的な料金体系(無料、プロ、エンタープライズ)
  • ティアごとのレート制限
  • 顧客ごとの分析
  • セルフサービスの開発者ポータル

実装:

# Tenant identification
plugins:
  - name: key-auth
    config:
      key_names:
        - X-API-Key

# Tier-based rate limiting
consumers:
  - username: free-tier-customer
    custom_id: customer-123

plugins:
  - name: rate-limiting
    consumer: free-tier-customer
    config:
      minute: 60
      hour: 1000

# Usage analytics
plugins:
  - name: prometheus
    config:
      per_consumer: true

# Request transformation (add tenant context)
plugins:
  - name: request-transformer
    config:
      add:
        headers:
          - "X-Tenant-ID:$(consumer_custom_id)"
ユースケース 2:マイクロサービスゲートウェイ

要件:

  • サービスディスカバリー
  • ロードバランシング
  • サーキットブレーカー
  • 分散トレーシング
  • 一元化された認証

実装:

# Service registry
services:
  - name: users-service
    url: http://users.internal:8001

  - name: orders-service
    url: http://orders.internal:8002

  - name: inventory-service
    url: http://inventory.internal:8003

# Load balancing with health checks
upstreams:
  - name: users-upstream
    healthchecks:
      active:
        http_path: /health
        healthy:
          interval: 5

# Distributed tracing
plugins:
  - name: zipkin
    config:
      http_endpoint: http://zipkin:9411/api/v2/spans

# JWT authentication (single sign-on)
plugins:
  - name: jwt
    config:
      claims_to_verify:
        - exp
ユースケース 3:モバイルバックエンド

要件:

  • バージョン管理された API
  • GraphQL のサポート
  • オフラインキャッシュ
  • プッシュ通知
  • デバイスごとのレート制限

実装:

# API versioning
routes:
  - name: api-v1
    paths:
      - /api/v1
    service: mobile-api-v1

  - name: api-v2
    paths:
      - /api/v2
    service: mobile-api-v2

# GraphQL endpoint
plugins:
  - name: graphql-proxy-cache-advanced
    route: graphql-route

# Aggressive caching for mobile
plugins:
  - name: proxy-cache
    config:
      cache_ttl: 3600
      strategy: redis

# Device-based rate limiting
plugins:
  - name: rate-limiting
    config:
      limit_by: header
      header_name: X-Device-ID
      minute: 100
ユースケース 4:パブリック API

要件:

  • OAuth 2.0
  • 開発者ポータル
  • API ドキュメント
  • 使用状況の分析
  • 収益化

実装:

# OAuth 2.0
plugins:
  - name: oauth2
    config:
      scopes:
        - read
        - write
        - admin
      enable_authorization_code: true

# Developer portal
routes:
  - name: developer-docs
    paths:
      - /docs
    service: developer-portal

# Usage tracking
plugins:
  - name: prometheus
    config:
      per_consumer: true

# Billing integration
plugins:
  - name: http-log
    config:
      http_endpoint: http://billing-system:5000
ユースケース 5:レガシーシステムのモダナイゼーション

要件:

  • REST から GraphQL への変換
  • プロトコル変換
  • リクエスト/レスポンスの変換
  • 段階的な移行
  • 後方互換性

実装:

# GraphQL facade over REST
plugins:
  - name: graphql-proxy-cache-advanced

# SOAP to REST transformation
plugins:
  - name: request-transformer-advanced
    config:
      # Transform REST to SOAP
      replace:
        headers:
          - "Content-Type:text/xml"

# Version migration (route legacy to new)
upstreams:
  - name: api-upstream
    targets:
      - target: legacy-api:8001
        weight: 20  # 20% legacy
      - target: new-api:8002
        weight: 80  # 80% new

クイックリファレンス

基本コマンド
# Declarative configuration
deck sync -s kong.yaml

# Database migrations
kong migrations bootstrap
kong migrations up

# Start Kong
kong start

# Reload configuration
kong reload

# Health check
curl http://localhost:8001/status

# List services
curl http://localhost:8001/services

# List routes
curl http://localhost:8001/routes

# List plugins
curl http://localhost:8001/plugins
設定テンプレート

最小限のサービス:

services:
  - name: my-service
    url: http://api.internal:8001

routes:
  - name: my-route
    service: my-service
    paths:
      - /api

本番環境向けサービス:

services:
  - name: production-service
    url: http://api.internal:8001
    protocol: http
    retries: 5
    connect_timeout: 5000
    read_timeout: 60000
    write_timeout: 60000

upstreams:
  - name: production-upstream
    algorithm: consistent-hashing
    hash_on: header
    hash_on_header: X-User-ID
    healthchecks:
      active:
        http_path: /health
        healthy:
          interval: 5
          successes: 2
        unhealthy:
          http_failures: 3
          timeouts: 3

targets:
  - upstream: production-upstream
    target: api-1:8001
  - upstream: production-upstream
    target: api-2:8001

routes:
  - name: production-route
    service: production-service
    paths:
      - /api
    protocols:
      - https
    strip_path: true
    preserve_host: false

plugins:
  - name: rate-limiting
    route: production-route
    config:
      minute: 1000
      policy: redis

  - name: jwt
    route: production-route

  - name: cors
    route: production-route

  - name: prometheus
    route: production-route

リソース


スキルバージョン:1.0.0 最終更新日:2025年10月 スキルカテゴリ:API ゲートウェイ、マイクロサービス、トラフィック管理 対応環境:Kong Gateway 3.x、Kubernetes、Docker、クラウドプラットフォーム

コメント