Tuần 7 - Ngày 6: AWS AppSync Intro
Mục tiêu học tập
- 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
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
| REST | GraphQL | |
|---|---|---|
| Endpoints | Multiple (/users, /orders) | Single endpoint |
| Data fetching | Over/under-fetching | Exact data |
| Versioning | URL versioning (v1, v2) | Schema evolution |
| Caching | HTTP cache | Custom (AppSync built-in) |
| Real-time | WebSocket / polling | Subscriptions built-in |
| Learning curve | Lower | Higher |
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
| AppSync | API Gateway | |
|---|---|---|
| API style | GraphQL | REST, HTTP, WebSocket |
| Real-time | Built-in subscriptions | WebSocket (manual) |
| Offline | Yes (Amplify) | No |
| Data sources | Direct integration (DynamoDB, etc.) | Lambda or HTTP backends |
| Caching | Per-resolver | API-wide |
| Use case | Complex apps, mobile, real-time | REST APIs, microservices |
| Cost | Per query + subscription | Per 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
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
-
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.
-
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.
-
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.
-
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.
-
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
- 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 chính thức
Tiếp theo: Quiz Tuần 7