devHọc Dev

Week 4 - Day 3: Decoupled Architectures and Serverless Patterns

Week 4 – Day 3

This lesson combines 2 topics: Decoupled Architectures, Serverless Patterns.

Learning Objectives

  • Understand coupling vs decoupling
  • Apply SQS/SNS/EventBridge for decoupling
  • Microservices patterns
  • Async vs sync trade-offs
  • Understand the serverless ecosystem on AWS
  • Apply common serverless patterns
  • Compare serverless vs container vs EC2

Part 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 with 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 with 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)

Problem

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

Definition

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

Definition

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

Problem

  • 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

Part 2: Serverless Patterns

1. Serverless Definition

Characteristics

  • 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

Problem

  • 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

Review Questions

  1. How do tightly coupled and loosely coupled differ?

    Show answer

    Tightly coupled: services call each other directly and synchronously — the failure of 1 service cascades to other services, and the scaling of 1 service is constrained by another. Loosely coupled: services communicate through a message broker (SQS, SNS, EventBridge) — the sender doesn't know the receiver, the receiver scales independently, and the failure of 1 service doesn't crash the caller. Loose coupling increases resilience, scalability, and maintainability.

  2. When do you use SNS instead of SQS?

    Show answer

    SNS when you need to broadcast the same message to many consumers (fanout) — SNS pushes to all subscribers at once. SQS when only 1 consumer receives each message, or you need a queue buffer, or you need persistence/retry. Common pattern: SNS + SQS fanout — SNS broadcasts → many SQS queues, one queue per consumer service — combining the strengths of both. When you need email/SMS/HTTP webhook: use SNS.

  3. What problem does the Saga Pattern solve?

    Show answer

    The Saga Pattern solves distributed transactions in microservices — you can't use 2-phase commit across services. A saga splits a large transaction into a chain of local transactions with compensating transactions to roll back if any step fails. Two types: Choreography (services react to events on their own, no central coordinator) and Orchestration (Step Functions coordinates the sequence). It guarantees eventual consistency instead of ACID transactions.

  4. What problem does CQRS solve?

    Show answer

    Command Query Responsibility Segregation separates the write model (Commands) from the read model (Queries). It solves: (1) Writes and reads have different performance requirements — scale independently, (2) The read model can be optimized separately (denormalized, pre-computed views), (3) Complex queries don't affect write throughput. Example: DynamoDB for writes + Elasticsearch for search, or RDS for writes + cached read replicas.

  5. Which use cases is the Async API pattern for?

    Show answer

    Async API suits long-running operations (> 10 seconds) where you don't want the client to wait: video processing, image resize, report generation, ML inference, email sending. Pattern: (1) Client sends request → API GW → SQS/Lambda → returns 202 Accepted with jobId, (2) Client polls a status endpoint or receives a webhook callback when done. It avoids HTTP timeouts, reduces resource hold, and allows retry and DLQ.

  6. When do you use Step Functions instead of a Lambda chain?

    Show answer

    Step Functions when: (1) The workflow has complex per-step retry/error handling, (2) You need an audit trail and visibility into execution state, (3) You need parallel or conditional branching that is easy to manage, (4) The workflow runs > 15 minutes (exceeds the Lambda timeout), (5) You need a human approval step. A Lambda chain (calling Lambda from Lambda) suits simple linear 2-3 step flows — cheaper and simpler but hard to debug and with no built-in per-step retry.

  7. API Gateway HTTP vs REST: which is cheaper?

    Show answer

    HTTP API is ~70% cheaper: $1/million requests vs ~$3.5/million for REST API. HTTP API also has lower latency. You need REST API when you want: API Keys/Usage Plans, request transformation (mapping templates), WAF integration, detailed access logging, edge-optimized endpoint, built-in caching. HTTP API is enough for most modern serverless APIs with JWT authorization.

  8. What is the problem with Lambda + RDS? How do you solve it?

    Show answer

    Lambda scales horizontally (many concurrent executions) — each execution opens a DB connection → connection exhaustion with thousands of concurrent Lambdas (RDS max connections: 1,000-16,000 depending on instance). Cold starts are also slow when opening a new connection. Solution: RDS Proxy — pools and reuses DB connections, reducing N Lambda connections to only the connections actually needed. Or use Aurora Serverless v2 with built-in connection pooling.

  9. Which services does the Async HTTP API pattern use?

    Show answer

    Pattern: API Gateway → SQS → Lambda (or Step Functions). Flow: (1) API GW receives the request → writes to SQS, returns 202 Accepted + requestId, (2) Lambda consumes from SQS and processes asynchronously, (3) Client polls /status/{requestId} or receives a webhook. The SQS buffer helps: retry when Lambda fails (DLQ), scale Lambda by queue depth, no lost requests when Lambda is overloaded. EventBridge can also replace SQS for event-driven scenarios.

  10. Which services does a serverless static website use?

Show answer

Standard pattern: S3 (stores HTML/CSS/JS, enable static website hosting) + CloudFront (CDN + HTTPS with ACM cert + custom domain + cache) + Route 53 (DNS ALIAS record pointing to CloudFront). Optional: Lambda@Edge or CloudFront Functions for URL rewrites, auth headers. Cost is almost zero for low-traffic sites (cheap S3 storage, CloudFront free tier 1 TB/month for the first 12 months). No server, no EC2 needed.

Hands-on Exercises

Part 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
  • Draw an architecture diagram for 1 microservices app

Part 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

References


Next lesson →