</>Học Dev
Bài học

Tuần 7 - Ngày 5: Amazon API Gateway

Tuần 7 – Ngày 5

Tuần 7 - Ngày 5: Amazon API Gateway

Mục tiêu học tập

  • Phân biệt REST, HTTP, WebSocket APIs
  • Hiểu authorization options
  • Nắm caching, throttling, stages
  • Áp dụng API Gateway với Lambda, VPC integration

1. Tổng quan API Gateway

Amazon API Gateway = managed service create, publish, secure APIs.

Đặc điểm

  • Multiple API types: REST, HTTP, WebSocket
  • Backend integration: Lambda, EC2/ALB, any HTTP, AWS services
  • Authentication: IAM, Cognito, Lambda authorizer, API keys
  • Throttling, caching, monitoring
  • Custom domain: api.example.com
  • SSL/TLS: via ACM
  • Auto-scaling: handle millions of requests

Use cases

  • Public REST APIs
  • Mobile/web app backends
  • Microservices gateway
  • Webhook receivers
  • WebSocket apps (chat, live updates)

2. API Types

REST API

  • Full-featured (most options)
  • Higher cost ($3.50/M requests)
  • Use case: Need API keys, request validation, caching, WAF, complex auth

HTTP API

  • Newer (2019+), simpler
  • Lower cost ($1.00/M requests, 70% cheaper than REST)
  • Lower latency
  • Subset of features (no API keys, no WAF directly, no request validation)
  • Use case: Lambda/HTTP proxy, simple APIs, cost-sensitive

WebSocket API

  • Bi-directional, persistent connection
  • Server can push to clients
  • Use case: Chat, live notifications, multiplayer games, real-time dashboards

Comparison

FeatureRESTHTTPWebSocket
Cost$3.50/M$1.00/M$1.00/M + connection minutes
API KeysYesNoNo
CachingYesNoNo
WAFYesNo (use CloudFront)No
Lambda authorizerYesYesYes
CognitoYesYesNo
OAuth 2.0 / JWTYes (Cognito)Yes (native JWT)Yes (Lambda)
Request validationYesNoNo
Use caseFull featuresSimple, fastReal-time bi-directional

3. Integration Types

Lambda Proxy Integration

  • Most common
  • API Gateway forwards request as-is to Lambda
  • Lambda returns response in specific format
  • Simple setup

Lambda Custom Integration

  • Transform request before Lambda
  • Transform response from Lambda
  • More configuration but flexible

HTTP Proxy

  • Forward to any HTTP endpoint (EC2, ALB, on-prem)
  • No transformation

HTTP Custom Integration

  • Transform requests/responses

AWS Service Integration

  • Direct integration with AWS services without Lambda
  • E.g., API Gateway → DynamoDB PutItem (no Lambda needed)
  • Use case: simple CRUD, save Lambda cost

Mock Integration

  • Return fixed response without backend
  • Use case: testing, placeholder during development

4. Authentication and Authorization

IAM Authorization

  • Caller signs request with AWS credentials (Sigv4)
  • Use case: backend-to-backend, internal microservices

Lambda Authorizer (formerly Custom Authorizer)

  • Lambda function validates token (JWT, OAuth, custom)
  • Returns IAM policy for caller
  • Cache policy for performance
  • Use case: custom auth logic

Cognito User Pool Authorizer

  • Validate JWT from Cognito User Pool
  • No code needed
  • Use case: web/mobile app users authenticated via Cognito

API Keys

  • Simple key string in header
  • Use case: rate limiting per customer/plan (Usage Plans)
  • REST API only

Resource Policy

  • Restrict access by IP, VPC, account
  • Like S3 bucket policy

5. Stages and Deployment

Stages

  • Deployment environment: dev, test, prod
  • Different URL per stage: api.example.com/dev, api.example.com/prod
  • Stage variables: pass config (Lambda alias, backend URL)

Deployments

  • Save snapshot of API config
  • Deploy to stage
  • Rollback: redeploy old snapshot

Canary Deployment

  • Route % of traffic to new version
  • Gradually increase if metrics good
  • Roll back if errors

6. Caching

REST API caching

  • Cache responses at API Gateway level
  • TTL: 0-3600 seconds
  • Reduces backend load
  • Cost: pay for cache size ($0.02-$3.80/hour depending on size 0.5GB-237GB)

Cache invalidation

  • Per-key invalidation via header Cache-Control: max-age=0
  • IAM permission required

7. Throttling

Account-level limits

  • 10,000 requests per second (RPS) default per region
  • 5,000 concurrent burst
  • Request increase via Service Quotas

Stage-level throttling

  • Set RPS limit per stage
  • Burst capacity

Usage Plans (REST only)

  • API key tied to Usage Plan
  • Per-key throttling, daily/monthly quotas
  • Tiers: Basic (100 req/sec), Premium (1000 req/sec)

When throttled

  • API Gateway returns 429 Too Many Requests

8. CORS (Cross-Origin Resource Sharing)

Issue

Browser at https://app.example.com calls API at https://api.example.com → CORS preflight needed.

Configure

  • Per resource: allow origin, methods, headers
  • API Gateway responds to OPTIONS preflight automatically
  • Set in API Gateway → Method → Enable CORS

9. Logging and Monitoring

CloudWatch Metrics

  • Per API, per stage, per method
  • Count, Latency, IntegrationLatency, 4XXError, 5XXError, CacheHit/Miss

Access Logging

  • Log all requests to CloudWatch Logs
  • Custom format (JSON with selected fields)

X-Ray Tracing

  • Distributed tracing through API Gateway → Lambda → DynamoDB
  • Identify slow components

10. VPC Integration

Private API

  • API Gateway endpoint only accessible from VPC (via Interface Endpoint)
  • Resource policy restricts to specific VPC endpoint
  • Use case: internal APIs

Private backend

  • API Gateway → ALB/NLB in private VPC
  • Use VPC Link to connect API Gateway → private VPC resources

Setup

API Gateway (public)
   ↓ (VPC Link)
NLB (in private VPC)
   ↓
Internal EC2 / ECS / on-prem (via Direct Connect/VPN)

11. API Gateway with Lambda Patterns

Pattern 1: Simple REST API

Client → API Gateway → Lambda → DynamoDB

Pattern 2: HTTP API with JWT (Cognito)

Client → Cognito sign-in → JWT
       → HTTP API (validate JWT)
       → Lambda → DynamoDB

Pattern 3: WebSocket chat

ClientAWebSocketAPIGatewayLambdaClientB(managesconnectionsinDynamoDB)PushtoallclientsClientC

Pattern 4: Microservice gateway

APIGatewayroutesbypath:/users/*Usermicroservice(ALBECS)/orders/*Ordermicroservice(Lambda)/payments/*Paymentmicroservice(ALBECS)

Pattern 5: Webhook receiver

External system → API Gateway → SQS (decouple)
                                  → Lambda (process)

12. Endpoint Types (REST API)

Edge-Optimized (default)

  • CloudFront-backed (low latency globally)
  • For end-user clients

Regional

  • In single region
  • For clients in same region (faster than going through CloudFront)

Private

  • Only accessible from VPC
  • Internal APIs

13. Pricing Summary

REST API

  • $3.50 per million requests
  • $0.02/GB data transfer out
  • Cache: $0.02-$3.80/hour

HTTP API

  • $1.00 per million requests (70% cheaper than REST)
  • $0.02/GB data transfer out

WebSocket API

  • $1.00 per million messages
  • $0.25 per million connection minutes

Free tier (12 months)

  • 1 million API calls per month

Câu hỏi ôn tập

  1. REST API vs HTTP API: cái nào rẻ hơn? Khi nào dùng REST?

    Xem đáp án

    HTTP API rẻ hơn ~70% so với REST API. Dùng REST API khi cần: API Keys, Usage Plans, Request/Response transformations (mapping templates), Resource Policies, WAF integration, custom domain với mutual TLS, caching tích hợp. HTTP API cho: JWT authorization, OIDC, faster (lower latency), đơn giản, Lambda proxy, private integrations — đủ cho hầu hết use cases hiện đại.

  2. WebSocket API dùng cho use case gì?

    Xem đáp án

    Persistent bidirectional communication: real-time chat, live notifications, collaborative editing, live dashboards, gaming, trading platforms. Client kết nối một lần, server có thể push messages bất kỳ lúc mà không cần client request. API Gateway manage WebSocket connections, route messages đến Lambda/HTTP backends. Dùng connectionId để identify clients và push messages về qua API Gateway Management API.

  3. Cognito Authorizer hỗ trợ trong API type nào?

    Xem đáp án

    Cả REST APIHTTP API đều hỗ trợ Cognito Authorizer. HTTP API dùng JWT Authorizer (native support cho Cognito User Pool JWT). REST API dùng Cognito User Pool Authorizer (validate token, check scopes). HTTP API JWT Authorizer cũng support bất kỳ OIDC-compliant provider, không chỉ Cognito — flexible hơn.

  4. VPC Link dùng để làm gì?

    Xem đáp án

    VPC Link cho phép API Gateway access resources trong private VPC (không có public IP): internal ALB, NLB, private EC2, ECS services. Không cần expose resource ra internet — API Gateway reach qua private ENI. VPC Link cho HTTP API dùng VPC Link v2 (NLB integration); VPC Link cho REST API dùng v1 (NLB). Phù hợp cho microservices chạy trong private VPC cần expose qua API GW.

  5. Stage variables dùng làm gì?

    Xem đáp án

    Stage variables là key-value config per deployment stage (dev, staging, prod). Dùng để: (1) Point đến different Lambda function aliases/versions per stage: ${stageVariables.lambdaAlias}, (2) Point đến different backend URLs per stage, (3) Set environment-specific config mà không cần redeploy API. Tương tự environment variables nhưng ở API Gateway level — cho phép same API definition deploy với different configurations per stage.

Bài tập thực hành

  • Tạo REST API với Lambda proxy integration
  • Setup Cognito User Pool authorizer
  • Enable caching 60s, observe perf improvement
  • Tạo HTTP API (cheaper alternative), compare cost
  • Setup custom domain với ACM cert
  • Tạo WebSocket API for simple chat app

Tài liệu tham khảo chính thức


Tiếp theo: AppSync Intro