devHọc Dev
EN
Bài học

Tuần 4 - Ngày 3: Decoupled Architectures và Serverless Patterns

Tuần 4 – Ngày 3

Bài này gộp 2 chủ đề: Decoupled Architectures, Serverless Patterns.

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

  • Hiểu coupling vs decoupling
  • Apply SQS/SNS/EventBridge cho decouple
  • Microservices patterns
  • Async vs sync trade-offs
  • Hiểu serverless ecosystem trên AWS
  • Apply common serverless patterns
  • Compare serverless vs container vs EC2

Phần 1: Decoupled Architectures

1. Coupling Concepts

Tightly Coupled (bad)

  • Components depend on each other directly
  • 1 fails → others fail
  • Hard to scale, change, deploy

Loosely Coupled (good)

  • Components communicate via interfaces (API, queue, event)
  • Failures isolated
  • Independent scaling, deployment
  • More resilient

Example

TIGHTLY COUPLED:
Web Server → calls Order Processor (synchronous HTTP)
   ↓
If Order Processor down → Web Server can't respond → User error

LOOSELY COUPLED:
Web Server → SQS Queue → Order Processor (async)
   ↓
Web Server returns 202 (accepted), Order Processor down → message waits in queue

2. Decoupling Strategies

Sync to Async (via Queue)

BEFORE: Client → Service A → Service B → Service C (sync chain)
AFTER:  Client → Service A → Queue → Service B → Queue → Service C

Service mesh / Event-driven

Service A publishes event → Event Bus
                          → Service B subscribes
                          → Service C subscribes
                          → Service D subscribes

Benefits

  • Independent scaling (Service B slow, Service A unaffected)
  • Buffer for spikes (queue absorbs)
  • Easier to add/remove services
  • Independent deploys
  • Better testability

3. AWS Decoupling Tools

ToolPatternUse case
SQSQueuePoint-to-point async
SNSPub/Sub1-to-many fanout
EventBridgeEvent BusRouting với filtering
KinesisStreamingReal-time data pipeline
Step FunctionsOrchestrationWorkflow coordination
API GatewayAPI layerHTTP decoupling
MSK (Managed Kafka)StreamingEvent streaming

4. SQS-based Decoupling

Pattern: Producer-Consumer

Web App (producer)
   ↓ (send message)
SQS Queue
   ↓ (poll)
ASG of Workers (consumers)

Benefits

  • Web App scales independently from Workers
  • Buffer (sudden spike → queue grows, workers catch up)
  • Workers can be EC2, Lambda, Fargate
  • DLQ for failed messages

Example: Order processing

User submits order → API Gateway → Lambda
                                    ↓
                            SQS Queue (orders)
                                    ↓
                            ASG of Order Processors
                                    ↓
                            Update DynamoDB + send email via SES

5. SNS-based Fanout

Pattern: 1 event → N consumers

OrderServicepublishes"OrderPlaced"event→SNSTopic↓┌─────────────────┼─────────────────┐▼▼▼SQSQueueSQSQueueSQSQueue↓↓▼InventorySvcEmailSvcAnalyticsSvc

Each consumer independent. Add new consumer? Just add SQS + service.

6. Event-Driven với EventBridge

Pattern: Multiple sources, smart routing

Source1:S3uploadeventSource2:CloudWatchalarmSource3:Customappevent↓EventBridgeBus↓Ruleswithfilters↓┌────────────┼────────────┐▼▼▼LambdaSQSStepFunctions

Use case: Multi-team SaaS

  • Each team subscribes to events they need
  • Centralized event hub
  • Schema Registry for governance

7. Microservices Decoupling

Architecture

APIGateway│┌─────────────────┼─────────────────┐▼▼▼UserServiceOrderServicePaymentService│││▼▼▼UserDBOrderDBPaymentDB│▼EventBus(EventBridge)│├──NotificationService(Email)├──AnalyticsService(Kinesis)└──SearchService(OpenSearchupdate)

Communication patterns

Synchronous (HTTP/REST)
  • Use case: real-time response needed
  • Trade-off: tight coupling
Asynchronous (events)
  • Use case: eventual consistency OK
  • Trade-off: complexity but resilient

Best practice

  • Sync between services where response immediate needed
  • Async for side effects (notification, analytics)

8. Saga Pattern (Distributed Transactions)

Vấn đề

  • Microservices each own database
  • Distributed transaction (e.g., book trip = hotel + flight + payment)
  • No 2-phase commit in distributed systems

Saga solution

  • Series of local transactions
  • If 1 fails → compensating actions for previous

Example

Book Trip:
1. Reserve Hotel → success
2. Book Flight → success
3. Charge Payment → FAILED!

Compensating:
3. (no-op)
2. Cancel Flight booking
1. Cancel Hotel reservation

Implementation

  • Step Functions: orchestrate saga (centralized)
  • Choreography (Events): each service listens, reacts (decentralized)

9. CQRS Pattern (Command Query Responsibility Segregation)

Định nghĩa

Separate write model (commands) from read model (queries).

Architecture

Write Path:
Client → Command → Aurora (writes)
                    ↓
              DynamoDB Streams / CDC
                    ↓
              Update read model

Read Path:
Client → Query → OpenSearch / DynamoDB / Cache (optimized reads)

Benefits

  • Read + Write scale independently
  • Use right tool for each (Aurora for writes, OpenSearch for searches)
  • Read model can be denormalized for speed

10. Event Sourcing

Định nghĩa

Store events (not just current state). Replay events to reconstruct state.

Example

Bank account events:
1. AccountCreated(id=123)
2. Deposit($100)
3. Withdraw($30)
4. Deposit($50)

Current balance = sum of events = $120

Store all events in DynamoDB Streams or Kinesis

Benefits

  • Full audit trail
  • Time travel debugging
  • Replay for new consumers
  • Eventual consistency natural

AWS Implementation

  • Events: DynamoDB / Kinesis / EventBridge
  • Replay: Step Functions with Distributed Map

11. Async API Pattern

Vấn đề

  • Long-running task (image processing, ML inference)
  • Sync HTTP times out

Solution: Async API

1. Client → POST /jobs → API Gateway
2. API Gateway → SQS Queue
3. Lambda invoked, returns job_id (202 Accepted)
4. Worker processes job → updates status
5. Client polls GET /jobs/{id} or
   Client uses WebSocket / SNS notification when done

12. Common Patterns

Pattern 1: Image processing pipeline

User uploads image → S3
                      ↓ (event)
                    Lambda thumbnail generator
                      ↓
                    Save thumbnail → S3
                      ↓ (event)
                    EventBridge → Notification + Search index update

Pattern 2: E-commerce order

User→APIGateway→OrderLambda↓DynamoDB(persistence)↓(Streams)SNSTopic├──SQS→InventoryService├──SQS→EmailService└──SQS→Analytics

Pattern 3: IoT data

Devices→IoTCore↓KinesisDataStreams↓├──Lambdareal-timeanalytics├──KinesisFirehose→S3→Athena└──Lambda→DynamoDBdevicestate

Pattern 4: Workflow orchestration

Trigger→StepFunctions├──Lambda1├──Choice(success/fail)├──Parallel(Lambda2+Lambda3)└──Errorhandler

Phần 2: Serverless Patterns

1. Serverless Definition

Đặc điểm

  • No server management (you don't see EC2)
  • Auto-scaling (0 → millions)
  • Pay per use (per request/invocation)
  • High availability built-in

AWS Serverless Services

  • Compute: Lambda, Fargate
  • Storage: S3
  • Database: DynamoDB, Aurora Serverless v2
  • Messaging: SQS, SNS, EventBridge
  • API: API Gateway, AppSync
  • Orchestration: Step Functions
  • Streaming: Kinesis (somewhat)
  • Other: SES (email), Cognito, AWS Glue

2. Serverless vs Other

Serverless (Lambda + DynamoDB)

  • Pros: No infra, pay per use, auto-scale, fast deploy
  • Cons: Cold start, 15-min limit, less control

Containers (Fargate + ECS)

  • Pros: Containerized, more control, longer-running
  • Cons: More config, cost may be higher

EC2

  • Pros: Full control, all OS access, longest run
  • Cons: Manage infra, scaling, patches

Decision

  • Event-driven, short tasks: Lambda
  • Long-running web apps: Fargate
  • Specific OS, GPU, high control: EC2

3. Pattern 1: Simple REST API

Architecture

Client → API Gateway → Lambda → DynamoDB

Components

  • API Gateway: HTTP routing, auth
  • Lambda: business logic
  • DynamoDB: data persistence

Cost (low traffic)

  • 1M requests/month:
  • Lambda: ~$0 (free tier)
  • API Gateway: $1 (HTTP API)
  • DynamoDB On-Demand: ~$1
  • Total: ~$2/month for 1M requests

Scale to millions

  • Auto-scale Lambda + DynamoDB
  • Linear cost (no overhead)

4. Pattern 2: File Processing Pipeline

Architecture

User uploads file → S3
                    ↓ (S3 event)
                  Lambda
                    ↓
                Process (transcode, OCR, etc.)
                    ↓
                  S3 (output)
                    ↓ (event)
                  SNS → Notify user

Use case

  • Image thumbnail generation
  • PDF text extraction
  • Video transcoding (with AWS Elemental MediaConvert)
  • File virus scanning

Lambda limitations

  • 15-min execution → use Step Functions or ECS for longer
  • 10 GB memory max → use ECS/Batch for heavy compute

5. Pattern 3: Real-time Analytics

Architecture

Sources(weblogs,IoT)→KinesisDataStreams↓Lambda(real-time)├──DynamoDB(state)├──ElastiCache(cache)└──CloudWatch(metrics)KinesisFirehose↓S3(datalake)↓Athena(ad-hoc)/QuickSight(dashboards)

Use case

  • Click stream analytics
  • IoT sensor data
  • Real-time fraud detection

6. Pattern 4: GraphQL Backend

Architecture

Mobile/WebApp→AppSync├──DynamoDB(data)├──Lambda(customlogic)└──RDS/OpenSearch(othersources)Real-timesubscriptionsviaWebSocket

Use case

  • Mobile app with complex data needs
  • Real-time features (chat, dashboards)
  • Offline support (Amplify)

7. Pattern 5: Workflow Orchestration

Architecture

Trigger(APIcall,event,schedule)↓StepFunctionsStateMachine├──Lambdatask1(validateinput)├──Choice(whichpath?)├──Parallel:│├──LambdataskA│└──LambdataskB├──Waitstate(delay)├──Lambdatask3(final)└──End/Failurehandler

Use case

  • ETL pipelines
  • Saga (distributed transactions)
  • ML training pipelines
  • Multi-step business processes

8. Pattern 6: Event-Driven Microservices

Architecture

EventBridge│┌────────────────┼────────────────┐│││UserServiceOrderServicePaymentService(Lambda)(Lambda)(Lambda)│││DynamoDBDynamoDBDynamoDB│││└────►Events──┴────►Events────┘publishedtoEventBridge

Communication

  • Sync: API calls between services (avoid as much as possible)
  • Async: events via EventBridge

9. Pattern 7: Static Website + CDN

Architecture

Developer → CI/CD → S3 (static files)
                     ↓
                   CloudFront (CDN + cache)
                     ↓
                   Route 53 (DNS)
                     ↓
                   User

Use case

  • Marketing sites
  • Single-page apps (React, Vue, Angular)
  • Documentation sites

Cost

  • S3: cents
  • CloudFront: $0.085/GB after free tier
  • Route 53: $0.50/zone
  • Total: < $5/month for moderate traffic

10. Pattern 8: Cron / Scheduled Jobs

Architecture

EventBridgeScheduler(cron02**?*)↓Lambda(dailytask)├──ReadS3,process├──UpdateDynamoDB└──Sendnotification

Use case

  • Daily reports
  • Database cleanup
  • Backup automation
  • Periodic health checks

vs Cron on EC2

  • No EC2 instance idle 99% of time
  • Pay per execution
  • Auto-scale (multiple schedules → multiple Lambdas)

11. Patterns 9: Async HTTP API

Vấn đề

  • HTTP request timeout (29 sec on API Gateway, 30 sec ALB)
  • Long-running tasks need async pattern

Architecture

1. Client → POST /jobs → API Gateway → Lambda
2. Lambda creates job_id in DynamoDB, sends to SQS
3. API returns 202 Accepted + job_id
4. Worker (Lambda/ECS) processes from SQS
5. Worker updates job status in DynamoDB
6. Client polls GET /jobs/{id} OR
   Client uses WebSocket for push notification

12. Cost Optimization

Lambda

  • Right-size memory (1769 MB = 1 vCPU)
  • Provisioned Concurrency only when needed
  • ARM (Graviton2) Lambda: 20% cheaper
  • Lambda Power Tuning tool: find optimal memory

DynamoDB

  • On-Demand for unpredictable (no minimum)
  • Provisioned + Auto Scaling for known load (cheaper at scale)
  • Reserved capacity for steady workload

API Gateway

  • HTTP API ($1/M) instead of REST API ($3.50/M) when features OK

S3 + CloudFront

  • CloudFront caching reduces S3 requests
  • Use S3 Transfer Acceleration only when needed

13. Common Mistakes

Anti-patterns

  1. Long-running Lambda (close to 15 min) — use Step Functions/ECS
  2. Lambda + RDS without RDS Proxy — connection storms
  3. Synchronous chain of Lambdas — use Step Functions
  4. No DLQ for async invocations — losing failed events
  5. Lambda in VPC unnecessarily — adds cold start, NAT cost
  6. Cold start critical paths — use Provisioned Concurrency

Câu hỏi ôn tập

  1. Tightly coupled vs loosely coupled khác nhau ở điểm gì?

    Xem đáp án

    Tightly coupled: services gọi nhau trực tiếp synchronously — failure của 1 service cascade đến services khác, scaling của 1 service bị ràng buộc bởi service khác. Loosely coupled: services communicate qua message broker (SQS, SNS, EventBridge) — sender không biết receiver, receiver scale độc lập, failure của 1 service không crash caller. Loose coupling tăng resilience, scalability, và maintainability.

  2. Khi nào dùng SNS thay vì SQS?

    Xem đáp án

    SNS khi cần broadcast same message đến nhiều consumers (fanout) — SNS push đến tất cả subscribers cùng lúc. SQS khi chỉ 1 consumer nhận mỗi message, hoặc cần queue buffer, hoặc cần persistence/retry. Pattern phổ biến: SNS + SQS fanout — SNS broadcast → nhiều SQS queues, mỗi queue cho một consumer service — kết hợp ưu điểm cả hai. Khi cần email/SMS/HTTP webhook: dùng SNS.

  3. Saga Pattern giải quyết vấn đề gì?

    Xem đáp án

    Saga Pattern giải quyết distributed transactions trong microservices — không thể dùng 2-phase commit across services. Saga chia transaction lớn thành chuỗi local transactions với compensating transactions để rollback nếu step nào fail. Hai loại: Choreography (services tự react đến events, không có central coordinator) và Orchestration (Step Functions điều phối sequence). Đảm bảo eventual consistency thay vì ACID transactions.

  4. CQRS giải quyết vấn đề gì?

    Xem đáp án

    Command Query Responsibility Segregation tách write model (Commands) khỏi read model (Queries). Giải quyết: (1) Write và read có performance requirements khác nhau — scale độc lập, (2) Read model có thể được optimize riêng (denormalized, pre-computed views), (3) Complex queries không ảnh hưởng write throughput. Ví dụ: DynamoDB cho writes + Elasticsearch cho search, hoặc RDS cho writes + read replicas được cache.

  5. Async API pattern dùng cho use case nào?

    Xem đáp án

    Async API phù hợp cho long-running operations (> 10 giây) mà không muốn client đợi: video processing, image resize, report generation, ML inference, email sending. Pattern: (1) Client gửi request → API GW → SQS/Lambda → trả 202 Accepted với jobId, (2) Client poll status endpoint hoặc nhận webhook callback khi xong. Tránh HTTP timeout, giảm resource hold, cho phép retry và DLQ.

  6. Khi nào dùng Step Functions thay vì Lambda chain?

    Xem đáp án

    Step Functions khi: (1) Workflow có retry/error handling phức tạp per step, (2) Cần audit trail và visibility vào execution state, (3) Cần parallel hoặc conditional branching dễ manage, (4) Workflow dài > 15 phút (vượt Lambda timeout), (5) Cần human approval step. Lambda chain (gọi Lambda từ Lambda) phù hợp cho simple linear 2-3 step flows — rẻ hơn và đơn giản hơn nhưng khó debug và không có built-in retry per step.

  7. API Gateway HTTP vs REST: cái nào rẻ hơn?

    Xem đáp án

    HTTP API rẻ hơn ~70%: $1/million requests vs ~$3.5/million cho REST API. HTTP API cũng có lower latency. REST API cần khi muốn: API Keys/Usage Plans, request transformation (mapping templates), WAF integration, access logging chi tiết, edge-optimized endpoint, caching tích hợp. HTTP API đủ cho hầu hết modern serverless APIs với JWT authorization.

  8. Lambda + RDS có vấn đề gì? Cách giải quyết?

    Xem đáp án

    Lambda scale horizontally (nhiều concurrent executions) — mỗi execution mở DB connection → connection exhaustion khi hàng nghìn Lambda concurrent (RDS max connections: 1,000-16,000 tùy instance). Cũng slow cold start khi mở new connection. Giải pháp: RDS Proxy — pool và reuse DB connections, giảm từ N Lambda connections xuống còn ~connections cần thiết thực sự. Hoặc dùng Aurora Serverless v2 với connection pooling tích hợp.

  9. Async HTTP API pattern dùng services nào?

    Xem đáp án

    Pattern: API Gateway → SQS → Lambda (hoặc Step Functions). Flow: (1) API GW nhận request → ghi vào SQS, trả 202 Accepted + requestId, (2) Lambda consume từ SQS xử lý async, (3) Client poll /status/{requestId} hoặc nhận webhook. SQS buffer giúp: retry khi Lambda fail (DLQ), scale Lambda theo queue depth, không mất requests khi Lambda overloaded. EventBridge cũng có thể thay SQS cho event-driven scenarios.

  10. Static website serverless dùng services gì?

Xem đáp án

Standard pattern: S3 (lưu HTML/CSS/JS, enable static website hosting) + CloudFront (CDN + HTTPS với ACM cert + custom domain + cache) + Route 53 (DNS ALIAS record trỏ vào CloudFront). Optional: Lambda@Edge hoặc CloudFront Functions cho URL rewrite, auth headers. Cost gần như zero cho low-traffic sites (S3 storage rẻ, CloudFront free tier 1 TB/month 12 tháng đầu). Không cần server, không cần EC2.

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

Phần 1: Decoupled Architectures

  • Build pipeline: API Gateway → SQS → Lambda → DynamoDB
  • Add SNS fanout: API → SQS + Lambda + email
  • Implement Step Functions saga: 3 steps with error handlers
  • Setup async API: submit job → return job_id → poll status
  • Vẽ architecture diagram cho 1 microservices app

Phần 2: Serverless Patterns

  • Build REST API serverless: API Gateway + Lambda + DynamoDB
  • Build file processing: S3 → Lambda → S3
  • Build scheduled cron job: EventBridge → Lambda
  • Build async API: submit job → poll status
  • Build static site: S3 + CloudFront + Route 53

Tài liệu tham khảo


Bài tiếp theo →