devHọc Dev
EN
Bài học

Tuần 3 - Ngày 4: Step Functions, API Gateway và AppSync

Tuần 3 – Ngày 4

Bài này gộp 3 chủ đề: AWS Step Functions, Amazon API Gateway, AWS AppSync Intro.

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

  • Hiểu Step Functions: serverless workflow orchestration
  • Phân biệt Standard vs Express workflows
  • Nắm state types và error handling
  • Áp dụng cho ETL, ML pipelines, microservices
  • 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
  • Hiểu AppSync: managed GraphQL API
  • Phân biệt GraphQL vs REST
  • Nắm real-time subscriptions
  • Biết khi nào dùng AppSync vs API Gateway

Phần 1: AWS Step Functions

1. Tổng quan Step Functions

AWS Step Functions = serverless visual workflow service orchestrate AWS services into business processes.

Đặc điểm

  • Visual workflow editor + JSON definition (ASL - Amazon States Language)
  • 200+ AWS service integrations
  • Built-in error handling (retry, catch)
  • State management (Step Functions tracks state, no need to write own)
  • Audit trail (full execution history)
  • Long-running: up to 1 year (Standard workflow)

Use cases

  • Order processing workflows
  • ETL pipelines
  • ML training/inference pipelines
  • Microservice coordination
  • Approval workflows (with human task)
  • Saga pattern (distributed transactions)

2. Workflow Types

Standard Workflow

  • Long-running: up to 1 year
  • Exactly-once execution
  • Audit history retained 90 days
  • Pricing: per state transition ($25/M)
  • Use case: long-running business processes, batch ETL

Express Workflow

  • Short-running: up to 5 minutes
  • At-least-once execution (may execute twice)
  • CloudWatch Logs (no audit history)
  • Pricing: per execution + duration (much cheaper than Standard)
  • Use case: high-volume short workflows (IoT, mobile, streaming)

Express variants

  • Sync Express: caller waits for result (like REST)
  • Async Express: fire-and-forget (like SNS)

Comparison

StandardExpress
DurationUp to 1 yearUp to 5 min
Execution rate2K/sec100K/sec
Pricing$25/M transitions$1/M executions + $0.10/GB-hour
History90 daysCloudWatch logs
Use caseLong workflowsHigh-volume short

3. States Types

Task

  • Execute single unit of work
  • Integrations: Lambda, ECS task, AWS SDK, Activity (worker)

Pass

  • Pass input to output (transformation)
  • Useful for testing, transforming data

Wait

  • Wait for time period or until timestamp

Choice

  • Conditional branching (if/else)

Parallel

  • Execute multiple branches in parallel
  • Wait for all to complete

Map

  • Execute task for each item in array (parallel)
  • Like for-each loop

Succeed / Fail

  • Terminate workflow with success/failure

4. ASL Example

Simple Lambda task

{
  "Comment": "Order processing workflow",
  "StartAt": "ValidateOrder",
  "States": {
    "ValidateOrder": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:111:function:ValidateOrder",
      "Next": "ChargePayment"
    },
    "ChargePayment": {
      "Type": "Task",
      "Resource": "arn:aws:lambda:us-east-1:111:function:ChargePayment",
      "End": true
    }
  }
}

With error handling

{
  "ChargePayment": {
    "Type": "Task",
    "Resource": "arn:aws:lambda:us-east-1:111:function:ChargePayment",
    "Retry": [{
      "ErrorEquals": ["Lambda.ServiceException"],
      "IntervalSeconds": 2,
      "MaxAttempts": 3,
      "BackoffRate": 2.0
    }],
    "Catch": [{
      "ErrorEquals": ["PaymentDeclined"],
      "Next": "NotifyCustomer"
    }],
    "Next": "ShipOrder"
  }
}

5. Error Handling

Retry

  • Retry on specific errors
  • Configurable: interval, max attempts, backoff rate
  • Common errors:
    • States.ALL: catch all
    • States.Timeout
    • Lambda.ServiceException
    • Custom error names from Lambda

Catch

  • On error, transition to specific state
  • Like try-catch in code
  • Can chain catches for different error types

Pattern

TryTask├──Retry(transienterrors)└──Catch(businesserrors→handledifferently)

6. Service Integration Patterns

Request-Response (default)

  • Step Functions calls service, gets response immediately
  • E.g., Lambda invoke, S3 operations

Run a Job (.sync)

  • Step Functions submits job, waits for completion
  • E.g., ECS task, EMR step, Glue job, SageMaker training

Wait for a Callback (.waitForTaskToken)

  • Step Functions pauses, waits for external system to callback
  • E.g., Human approval, manual review
  • Token returned via SendTaskSuccess or SendTaskFailure API

Example: Human approval

{
  "ApprovalRequired": {
    "Type": "Task",
    "Resource": "arn:aws:states:::sns:publish.waitForTaskToken",
    "Parameters": {
      "TopicArn": "arn:aws:sns:...",
      "Message": {
        "TaskToken.$": "$$.Task.Token",
        "OrderId.$": "$.orderId"
      }
    },
    "Next": "ProcessApproval"
  }
}

Human approver gets SNS, clicks link → app calls SendTaskSuccess(token, output) → workflow resumes.

7. Map State (Iteration)

Inline Map

  • Process array in parallel (within workflow definition)
  • Up to 40 concurrent iterations
  • Use case: process up to 40 items

Distributed Map (2022+)

  • Process millions of items in parallel
  • Source: S3 objects, CSV/JSON list, inventory
  • Up to 10,000 concurrent
  • Use case: process large dataset

Example: Process S3 inventory

{
  "ProcessFiles": {
    "Type": "Map",
    "ItemReader": {
      "Resource": "arn:aws:states:::s3:listObjectsV2",
      "Parameters": {
        "Bucket": "my-bucket",
        "Prefix": "input/"
      }
    },
    "MaxConcurrency": 1000,
    "ItemProcessor": {
      "ProcessorConfig": { "Mode": "DISTRIBUTED" },
      "StartAt": "ProcessOneFile",
      "States": {
        "ProcessOneFile": {
          "Type": "Task",
          "Resource": "arn:aws:lambda:...:function:ProcessFile",
          "End": true
        }
      }
    },
    "End": true
  }
}

8. Input/Output Processing

Filtering

  • InputPath: select subset of input
  • Parameters: construct new JSON for task
  • ResultSelector: select subset of task output
  • ResultPath: where to put task output in state's output
  • OutputPath: select subset of state's output for next state

Example

State input: { "user": "alice", "order": { "id": 123 } }

InputPath: $.order
→ Task receives: { "id": 123 }

Task returns: { "status": "OK" }

ResultPath: $.result
→ State output: { "user": "alice", "order": {...}, "result": { "status": "OK" } }

9. Activities (Worker Pattern)

Định nghĩa

Activity = task processed by external worker (EC2, on-prem) instead of Lambda.

Workflow

  1. State Machine has Activity task
  2. Worker polls Step Functions for tasks (GetActivityTask)
  3. Worker processes
  4. Worker calls SendTaskSuccess / SendTaskFailure

Use case

  • Long-running tasks (> 15 min Lambda limit)
  • On-prem workers
  • Custom worker pool

10. Common Patterns

Pattern 1: Order processing

Validate→AuthorizePayment→Ship→SendConfirmation│││CatchCatch(declined)Catch(outofstock)▼▼▼NotifyRefundBackorder

Pattern 2: ML pipeline

Prepare Data (Glue) → Train Model (SageMaker .sync)
                     → Deploy Endpoint → Test → Promote to production

Pattern 3: ETL with Map

Trigger by S3 event → List files in S3 → Map (parallel process each file)
                                       → Aggregate results → Load to Redshift

Pattern 4: Saga (distributed transactions)

Step1:Bookhotel→Step2:Bookflight→Step3:Chargepayment│││└─onfailurerollback─┴────onfailurerollback┘

11. Security

IAM

  • State machine has IAM role
  • Role permissions for invoking targets (Lambda, ECS, etc.)
  • Cross-account: target accounts grant access

Encryption

  • Execution history: encrypted with AWS-managed keys
  • Can use CMK for customer-managed encryption

VPC

  • Tasks (Lambda, ECS) in VPC if needed
  • Step Functions itself is regional service, no VPC

12. Step Functions vs Lambda Choreography

Choreography (Lambdas calling Lambdas)

  • Each Lambda decides next step
  • Pros: simple for small flow
  • Cons: hard to debug, scattered logic, no central view

Orchestration (Step Functions)

  • Central workflow definition
  • Pros: visual flow, centralized error handling, easy to debug
  • Cons: extra cost (state transitions)

Decision

  • Few steps, simple flow: Lambda chain
  • Complex flow, error handling, audit: Step Functions
  • Long-running, human task: Step Functions

13. Pricing

Standard

  • $25 per million state transitions
  • Free tier: 4K transitions/month

Express

  • $1 per million executions
  • $0.10 per GB-hour duration
  • Cheaper for high-volume short workflows

Phần 2: Amazon API Gateway

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

ClientA──┐├─WebSocket→APIGateway→LambdaClientB──┤(managesconnectionsinDynamoDB)│→PushtoallclientsClientC──┘

Pattern 4: Microservice gateway

APIGatewayroutesbypath:├──/users/*→Usermicroservice(ALB→ECS)├──/orders/*→Ordermicroservice(Lambda)└──/payments/*→Paymentmicroservice(ALB→ECS)

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

Phần 3: AWS AppSync Intro

1. Tổng quan AppSync

AWS AppSync = managed GraphQL service cho mobile/web apps.

Đặc điểm

  • GraphQL APIs (query, mutation, subscription)
  • Real-time subscriptions (WebSocket)
  • Offline support (sync data when reconnected)
  • Multiple data sources: DynamoDB, Aurora, OpenSearch, Lambda, HTTP, EventBridge
  • Authentication: API Key, IAM, Cognito, OIDC, Lambda authorizer
  • Caching built-in
  • Pay per request

Use cases

  • Mobile/web apps with complex data needs
  • Real-time apps (chat, dashboards, gaming)
  • Multi-source data aggregation
  • Offline-capable mobile apps

2. GraphQL vs REST

REST

GET /users/123             → user data
GET /users/123/orders      → orders (separate call)
GET /orders/456/items      → items (another call)

3 API calls, over-fetching (get all user fields), under-fetching (need separate calls).

GraphQL

query {
  user(id: "123") {
    name
    email
    orders {
      id
      items {
        name
        price
      }
    }
  }
}

1 call, exact data needed, client controls shape.

Differences

RESTGraphQL
EndpointsMultiple (/users, /orders)Single endpoint
Data fetchingOver/under-fetchingExact data
VersioningURL versioning (v1, v2)Schema evolution
CachingHTTP cacheCustom (AppSync built-in)
Real-timeWebSocket / pollingSubscriptions built-in
Learning curveLowerHigher

3. AppSync Schema

Define types và operations

type User {
  id: ID!
  name: String!
  email: String!
  orders: [Order]
}

type Order {
  id: ID!
  total: Float!
  items: [Item]
}

type Query {
  user(id: ID!): User
  orders: [Order]
}

type Mutation {
  createOrder(input: CreateOrderInput!): Order
}

type Subscription {
  onOrderCreated: Order
    @aws_subscribe(mutations: ["createOrder"])
}

4. Resolvers

Định nghĩa

Resolver = function map GraphQL field to data source.

Types

  • VTL templates (Velocity Template Language) - older
  • JavaScript resolvers (newer, recommended)
  • Pipeline resolvers (chain multiple)

Direct integration (no Lambda)

  • DynamoDB: GetItem, Query, Scan
  • Aurora Serverless: SQL via Data API
  • OpenSearch: search queries
  • HTTP: any REST API
  • EventBridge: publish event
  • None: business logic only

Lambda resolver

  • For complex logic
  • Slower than direct integration (cold start)

5. Real-time Subscriptions

Workflow

1. Client subscribes to onOrderCreated
2. AppSync opens WebSocket connection
3. Some other client calls createOrder mutation
4. AppSync auto-publishes event to all subscribers
5. Subscribed client receives Order data

Use cases

  • Chat applications (new message → push to participants)
  • Live dashboards (data updates → refresh UI)
  • Multiplayer games (player state changes → notify others)
  • Collaborative tools (Google Docs-style)

6. Offline Support

Amplify DataStore integration

  • Client SDK caches data locally (IndexedDB, SQLite)
  • Sync to AppSync when online
  • Conflict resolution: optimistic concurrency

Use case

  • Mobile apps in poor connectivity
  • Offline-first design

7. Authentication

5 options (mix and match)

  • API Key: simple key, basic public APIs
  • IAM: AWS SigV4 (backend-to-backend)
  • Cognito User Pool: JWT
  • OIDC: third-party IdP
  • Lambda Authorizer: custom logic

Authorization granularity

  • Field-level: @aws_auth(cognito_groups: ["Admins"])
  • Type-level: certain types only for certain users
  • Multi-auth: combine multiple auth modes per API

8. Caching

Cache layer

  • Built-in caching at resolver level
  • TTL configurable
  • Per-resolver or per-API

Reduces

  • Database load
  • Latency for repeat queries
  • Cost

9. AppSync vs API Gateway

AppSyncAPI Gateway
API styleGraphQLREST, HTTP, WebSocket
Real-timeBuilt-in subscriptionsWebSocket (manual)
OfflineYes (Amplify)No
Data sourcesDirect integration (DynamoDB, etc.)Lambda or HTTP backends
CachingPer-resolverAPI-wide
Use caseComplex apps, mobile, real-timeREST APIs, microservices
CostPer query + subscriptionPer request

Decision

  • REST API, simple: API Gateway HTTP API
  • REST API, advanced: API Gateway REST API
  • GraphQL, real-time, mobile: AppSync
  • WebSocket simple: API Gateway WebSocket

10. Pricing

AppSync

  • $4 per million queries/mutations
  • $2 per million real-time updates
  • $0.08 per million minutes of subscription connection

Free tier (12 months)

  • 250K queries/mutations
  • 250K real-time updates
  • 600K minutes connection

11. Common Patterns

Pattern 1: Mobile app with offline

Mobileapp├──AmplifyDataStore(localSQLite)└──AppSyncAPI(GraphQL)├──DynamoDB(data)└──Cognito(auth)Syncwhenonline

Pattern 2: Real-time dashboard

Backend service → AppSync mutation
                 → AppSync subscription
                 → All connected dashboard clients (WebSocket)

Pattern 3: Multi-source aggregation

GraphQL query:
{
  user(id: "123") {
    profile         # from DynamoDB
    orders          # from Aurora
    recommendations # from Lambda → ML model
  }
}

1 GraphQL query → 3 data sources, parallel.


Câu hỏi ôn tập

  1. Standard và Express workflow khác nhau ở điểm gì?

    Xem đáp án

    Standard: max 1 năm execution, exactly-once execution, audit history trong console, tính phí per state transition ($0.025/1000 transitions). Phù hợp cho long-running business processes. Express: max 5 phút, at-least-once (async) hoặc at-most-once (sync), tính phí per duration + invocations ($1/million invocations). Phù hợp cho high-volume event processing, IoT, streaming. Express rẻ hơn nhiều cho workloads ngắn.

  2. State type nào dùng để branch conditional?

    Xem đáp án

    Choice state — evaluate conditions dựa trên input và route đến state khác nhau (if/else/switch). Không thể timeout hay có retry. Các state types khác: Task (gọi resource), Wait (delay), Pass (transform), Parallel (concurrent branches), Map (iterate array), Succeed, Fail. Choice + Parallel + Map là 3 state quan trọng nhất cho workflow design.

  3. .waitForTaskToken dùng cho use case nào?

    Xem đáp án

    Cho phép pause workflow và đợi external callback. Step Functions generate task token, include trong task input. External system (human approval, 3rd party API, legacy system) xử lý xong gọi SendTaskSuccess hoặc SendTaskFailure với token để resume. Use case điển hình: human approval workflow (gửi email, chờ người approve/reject), kết nối với on-premises systems cần manual step.

  4. Map state dùng để làm gì?

    Xem đáp án

    Map state iterate qua một array và chạy cùng sub-workflow cho mỗi item — parallel (concurrent) hoặc sequential với MaxConcurrency. Ví dụ: process 100 files cùng lúc, send 50 emails, validate array of records. MaxConcurrency=0 = unlimited parallel; MaxConcurrency=1 = sequential. Kết quả trả về array tương ứng. Giảm thời gian xử lý batch đáng kể so với sequential Lambda.

  5. Khi nào nên dùng Step Functions thay Lambda chaining?

    Xem đáp án

    Dùng Step Functions khi: (1) Workflow phức tạp với nhiều states, branches, error handling — Lambda chaining code trở nên unmanageable, (2) Cần visibility/audit trail — xem execution history, debug failed step, (3) Cần retry logic với exponential backoff per step, (4) Workflow dài hơn 15 phút (Lambda limit), (5) Cần human approval step (.waitForTaskToken), (6) Cần parallel + map processing. Lambda chaining phù hợp cho simple 2-3 step linear flows.

  6. 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.

  7. 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.

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

    Xem đáp án

    Cả REST API và HTTP 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.

  9. 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.

  10. 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.

  1. AppSync dùng API style nào?
Xem đáp án

GraphQL — single endpoint, client specify chính xác data structure cần, server trả về đúng đó (không over-fetch hay under-fetch). AppSync là managed GraphQL service của AWS — handle schema, resolvers, authentication, real-time subscriptions, và offline sync cho mobile.

  1. Real-time subscriptions trong AppSync hoạt động qua giao thức gì?
Xem đáp án

WebSocket (AWS-specific sub-protocol). Client subscribe theo GraphQL subscription query, AppSync maintain WebSocket connection, tự động push updates khi data thay đổi (triggered bởi mutations). Amplify DataStore và Amplify GraphQL client handle connection management tự động. Không cần polling — event-driven real-time updates.

  1. AppSync hỗ trợ data sources nào (direct integration)?
Xem đáp án

AppSync có built-in resolvers (không cần Lambda) cho: DynamoDB, Aurora Serverless, OpenSearch, HTTP endpoints, EventBridge, Lambda. Có thể dùng JavaScript resolvers (pipeline resolvers) cho complex business logic. Direct DynamoDB integration phổ biến nhất — giảm latency và cost so với Lambda middleware.

  1. Khác biệt cốt lõi giữa REST và GraphQL về data fetching?
Xem đáp án

REST: nhiều endpoints (GET /users, GET /posts, GET /comments...), server quyết định response structure — client có thể over-fetch (nhận data thừa) hoặc under-fetch (cần multiple requests). GraphQL: 1 endpoint, client define chính xác fields cần trong query — không over/under-fetch. Phù hợp cho mobile (bandwidth sensitive) và complex front-end với nhiều data requirements khác nhau.

  1. Khi nào dùng AppSync vs API Gateway?
Xem đáp án

Dùng AppSync khi: (1) Cần GraphQL API, (2) Real-time subscriptions (chat, notifications), (3) Mobile apps với offline sync, (4) Complex nested queries với multiple data sources. Dùng API Gateway khi: (1) RESTful API, (2) WebSocket API không cần GraphQL, (3) Expose existing microservices/Lambda, (4) Team không quen GraphQL, (5) Cần caching, throttling, usage plans phức tạp của REST API type.

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

Phần 1: AWS Step Functions

  • Tạo Standard workflow: 3-step Lambda chain
  • Add Retry + Catch cho 1 task
  • Tạo Parallel state chạy 2 Lambdas đồng thời
  • Test Map state với 10 items
  • Setup .waitForTaskToken: SNS + Lambda callback
  • Tạo Express workflow, test high-frequency execution

Phần 2: Amazon API Gateway

  • 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

Phần 3: AWS AppSync Intro

  • Tạo AppSync API với DynamoDB data source
  • Define schema: User, Order types
  • Tạo resolver Query getUser → DynamoDB GetItem
  • Test mutation createOrder, subscription onOrderCreated
  • (Optional) Setup Amplify client cho mobile/web

Tài liệu tham khảo


Bài tiếp theo →