devHọc Dev

Week 3 - Day 4: Step Functions, API Gateway and AppSync

Week 3 – Day 4

This lesson combines 3 topics: AWS Step Functions, Amazon API Gateway, AWS AppSync Intro.

Learning Objectives

  • Understand Step Functions: serverless workflow orchestration
  • Distinguish Standard vs Express workflows
  • Master state types and error handling
  • Apply them to ETL, ML pipelines, microservices
  • Distinguish REST, HTTP, WebSocket APIs
  • Understand authorization options
  • Master caching, throttling, stages
  • Apply API Gateway with Lambda, VPC integration
  • Understand AppSync: managed GraphQL API
  • Distinguish GraphQL vs REST
  • Master real-time subscriptions
  • Know when to use AppSync vs API Gateway

Part 1: AWS Step Functions

1. Step Functions Overview

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

Key Features

  • 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)

Definition

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

Part 2: Amazon API Gateway

1. API Gateway Overview

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

Key Features

  • 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

Part 3: AWS AppSync Intro

1. AppSync Overview

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

Key Features

  • 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 and 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

Definition

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.


Review Questions

  1. How do Standard and Express workflows differ?

    Show answer

    Standard: max 1 year of execution, exactly-once execution, audit history in the console, billed per state transition ($0.025/1000 transitions). Suited to long-running business processes. Express: max 5 minutes, at-least-once (async) or at-most-once (sync), billed per duration + invocations ($1/million invocations). Suited to high-volume event processing, IoT, streaming. Express is much cheaper for short workloads.

  2. Which state type is used for conditional branching?

    Show answer

    Choice state: evaluates conditions based on the input and routes to different states (if/else/switch). It cannot time out or have a retry. Other state types: Task (call a resource), Wait (delay), Pass (transform), Parallel (concurrent branches), Map (iterate an array), Succeed, Fail. Choice + Parallel + Map are the 3 most important states for workflow design.

  3. What use case is .waitForTaskToken for?

    Show answer

    It lets you pause the workflow and wait for an external callback. Step Functions generates a task token and includes it in the task input. The external system (human approval, 3rd party API, legacy system) finishes processing and calls SendTaskSuccess or SendTaskFailure with the token to resume. Typical use case: human approval workflow (send an email, wait for someone to approve/reject), connecting to on-premises systems that need a manual step.

  4. What is the Map state used for?

    Show answer

    Map state iterates over an array and runs the same sub-workflow for each item, either parallel (concurrent) or sequential with MaxConcurrency. Example: process 100 files at once, send 50 emails, validate an array of records. MaxConcurrency=0 = unlimited parallel; MaxConcurrency=1 = sequential. The result is a corresponding array. It cuts batch processing time significantly compared with sequential Lambda.

  5. When should you use Step Functions instead of Lambda chaining?

    Show answer

    Use Step Functions when: (1) The workflow is complex with many states, branches, error handling, where Lambda chaining code becomes unmanageable, (2) You need visibility/audit trail: view execution history, debug a failed step, (3) You need retry logic with exponential backoff per step, (4) The workflow runs longer than 15 minutes (Lambda limit), (5) You need a human approval step (.waitForTaskToken), (6) You need parallel + map processing. Lambda chaining fits simple 2-3 step linear flows.

  6. REST API vs HTTP API: which is cheaper? When do you use REST?

    Show answer

    HTTP API is cheaper, about 70% less than REST API. Use REST API when you need: API Keys, Usage Plans, Request/Response transformations (mapping templates), Resource Policies, WAF integration, custom domain with mutual TLS, built-in caching. HTTP API for: JWT authorization, OIDC, faster (lower latency), simple, Lambda proxy, private integrations; enough for most modern use cases.

  7. What use cases is the WebSocket API for?

    Show answer

    Persistent bidirectional communication: real-time chat, live notifications, collaborative editing, live dashboards, gaming, trading platforms. The client connects once, and the server can push messages at any time without a client request. API Gateway manages WebSocket connections and routes messages to Lambda/HTTP backends. Use connectionId to identify clients and push messages back through the API Gateway Management API.

  8. Which API types support the Cognito Authorizer?

    Show answer

    Both REST API and HTTP API support a Cognito Authorizer. HTTP API uses the JWT Authorizer (native support for Cognito User Pool JWTs). REST API uses the Cognito User Pool Authorizer (validates the token, checks scopes). The HTTP API JWT Authorizer also supports any OIDC-compliant provider, not just Cognito, so it is more flexible.

  9. What is VPC Link used for?

    Show answer

    VPC Link lets API Gateway access resources in a private VPC (no public IP): internal ALB, NLB, private EC2, ECS services. You do not need to expose the resource to the internet; API Gateway reaches it through a private ENI. VPC Link for HTTP API uses VPC Link v2 (NLB integration); VPC Link for REST API uses v1 (NLB). Suited to microservices running in a private VPC that need to be exposed through API GW.

  10. What are stage variables used for?

Show answer

Stage variables are key-value config per deployment stage (dev, staging, prod). Use them to: (1) Point to different Lambda function aliases/versions per stage: ${stageVariables.lambdaAlias}, (2) Point to different backend URLs per stage, (3) Set environment-specific config without redeploying the API. Similar to environment variables but at the API Gateway level, letting the same API definition deploy with different configurations per stage.

  1. What API style does AppSync use?
Show answer

GraphQL: a single endpoint, the client specifies exactly the data structure it needs, and the server returns exactly that (no over-fetching or under-fetching). AppSync is AWS's managed GraphQL service; it handles schema, resolvers, authentication, real-time subscriptions, and offline sync for mobile.

  1. Which protocol do real-time subscriptions in AppSync run over?
Show answer

WebSocket (AWS-specific sub-protocol). The client subscribes with a GraphQL subscription query, AppSync maintains the WebSocket connection and automatically pushes updates when data changes (triggered by mutations). Amplify DataStore and the Amplify GraphQL client handle connection management automatically. No polling needed: event-driven real-time updates.

  1. Which data sources does AppSync support (direct integration)?
Show answer

AppSync has built-in resolvers (no Lambda needed) for: DynamoDB, Aurora Serverless, OpenSearch, HTTP endpoints, EventBridge, Lambda. You can use JavaScript resolvers (pipeline resolvers) for complex business logic. Direct DynamoDB integration is the most common, reducing latency and cost compared with Lambda middleware.

  1. What is the core difference between REST and GraphQL in data fetching?
Show answer

REST: many endpoints (GET /users, GET /posts, GET /comments...), and the server decides the response structure, so the client may over-fetch (receive extra data) or under-fetch (need multiple requests). GraphQL: 1 endpoint, the client defines exactly the fields it needs in the query, so no over/under-fetching. Suited to mobile (bandwidth sensitive) and complex front-ends with many different data requirements.

  1. When do you use AppSync vs API Gateway?
Show answer

Use AppSync when: (1) You need a GraphQL API, (2) Real-time subscriptions (chat, notifications), (3) Mobile apps with offline sync, (4) Complex nested queries over multiple data sources. Use API Gateway when: (1) RESTful API, (2) WebSocket API without GraphQL, (3) Exposing existing microservices/Lambda, (4) The team is not familiar with GraphQL, (5) You need the caching, throttling, and complex usage plans of the REST API type.

Hands-on Exercises

Part 1: AWS Step Functions

  • Create a Standard workflow: 3-step Lambda chain
  • Add Retry + Catch to 1 task
  • Create a Parallel state running 2 Lambdas concurrently
  • Test the Map state with 10 items
  • Set up .waitForTaskToken: SNS + Lambda callback
  • Create an Express workflow, test high-frequency execution

Part 2: Amazon API Gateway

  • Create a REST API with Lambda proxy integration
  • Set up a Cognito User Pool authorizer
  • Enable 60s caching, observe the performance improvement
  • Create an HTTP API (cheaper alternative), compare cost
  • Set up a custom domain with an ACM cert
  • Create a WebSocket API for a simple chat app

Part 3: AWS AppSync Intro

  • Create an AppSync API with a DynamoDB data source
  • Define the schema: User, Order types
  • Create a resolver Query getUser → DynamoDB GetItem
  • Test mutation createOrder, subscription onOrderCreated
  • (Optional) Set up an Amplify client for mobile/web

References


Next lesson →