devHọc Dev
Bài học

Tuần 10 - Ngày 2: Serverless Patterns và Best Practices

Tuần 10 – Ngày 2

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

  • Nhận diện 6 pattern serverless kinh điển (API backend, event processing, fan-out, load leveling, saga, strangler fig)
  • Nắm Lambda best practices: cold start, memory/timeout, error handling theo invocation type
  • Chọn đúng REST API vs HTTP API vs WebSocket và Standard vs Express Step Functions

Tổng quan Serverless Architecture

SERVERLESSARCHITECTURECoreServices:Compute:Lambda,FargateAPI:APIGateway,AppSyncStorage:S3,DynamoDBMessaging:SQS,SNS,EventBridgeOrchestration:StepFunctionsBenefits:NoservermanagementAuto-scalingPayperuseHighavailabilitybuilt-in

Common Serverless Patterns

1. API Backend Pattern

RESTAPIBACKENDClientAPIGatewayLambdaDynamoDBCognito(auth)CloudWatch(logs)Variations:LambdaperendpointLambdaperresource(monolith)LambdaperHTTPmethod

GraphQL Variant:

ClientAppSyncLambda/DynamoDBReal-timesubscriptionsOfflinesupportBuilt-incaching

2. Event Processing Pattern

EVENT-DRIVENPROCESSINGEventSourceProcessorTargetS3UploadLambdaDynamoDBDynamoDBStreamLambdaSNS/SQSIoTRuleLambdaTimestreamCloudWatchEventLambdaAnyserviceEventBridge:EventRuleTargetSource(Filter)(Lambda)

3. Fan-Out Pattern

FAN-OUTPATTERNLambda1ServiceAEventSNSTopicLambda2ServiceBSQSQueueLambda3Usecases:Multi-destinationnotificationsParallelprocessingCross-accounteventdistribution

4. Queue-Based Load Leveling

QUEUE-BASEDLOADLEVELINGProducerSQSQueueLambdaBenefits:Decoupleproducer/consumerBuffertrafficspikesRetryfailedprocessingScaleconsumersindependentlyLambda+SQSConfiguration:Batchsize:1-10,000Batchwindow:0-300secondsConcurrency:reservedorunreservedDLQforfailedmessages

5. Saga Pattern (Distributed Transactions)

SAGAPATTERNviStepFunctionsOrderService:CreateOrderReserveInventoryProcessPayment[Iffail][Iffail][Iffail]CancelOrderReleaseInventoryRefundPaymentStepFunctionsprovides:VisualworkflowErrorhandlingandretryCompensation(rollback)logicStatepersistence

6. Strangler Fig Pattern

STRANGLERFIGMIGRATIONPhase1:ProxyalltrafficClientAPIGatewayLegacyMonolithPhase2:RoutesomepathstonewservicesClientAPIGateway/usersLambda/*LegacyMonolithPhase3:AlltraffictonewservicesClientAPIGateway/usersLambda/ordersLambda/productsLambda

Lambda Best Practices

1. Cold Start Optimization

COLDSTARTMITIGATIONStrategies:ProvisionedConcurrency(guaranteedwarm)Keepfunctionswarm(scheduledinvocation)MinimizepackagesizeUseARM(Graviton)-fasterinitInitializeoutsidehandlerCodePattern://InitializeOUTSIDEhandler(runsonce)constdb=newDynamoDB.DocumentClient();//Handler(runseveryinvocation)exports.handler=async(event)=>{//Usepre-initializeddbclientreturndb.get(...);};

2. Memory and Timeout

MemoryConfiguration:Morememory=moreCPU128MBto10,240MBCost=(memory×duration)UseAWSLambdaPowerTuningTimeoutBestPractices:SetrealistictimeoutsAPIGatewayintegrationtimeout:default29seconds(t06/2024REST/HTTPAPIRegionalcóthrequestnângquá29strade-offgimthrottlequota;patternchunchotácvdàivnlàasync+polling)ConsiderStepFunctionsforlongtasksHandletimeoutsgracefully

3. Error Handling

ERRORHANDLINGPATTERNSSync(APIGateway):ReturnproperHTTPstatuscodesIncludeerrordetailsinresponseLogerrorstoCloudWatchAsync(S3,SNS,etc):Built-inretry(2times)DeadLetterQueue(DLQ)Destinations(success/failure)EventBridgeforfailedeventsSQSTrigger:Visibilitytimeout>functiontimeoutMaxreceivecountDLQPartialbatchfailurereporting

API Gateway Patterns

1. REST API vs HTTP API

APIGATEWAYTYPESRESTAPI:FullfeaturesetRequest/ResponsevalidationCachingWAFintegrationHighercostHTTPAPI:70%cheaperLowerlatencyNativeOIDC/OAuth2CORSbuilt-inLimitedfeaturesWebSocketAPI:Real-time,bidirectionalChat,gaming,IoT$connect,$disconnect,$defaultroutes

2. Caching Strategy

APIGatewayCaching:CacheperstageTTL:0-3600secondsCachekey:querystring,headersCacheinvalidationviaheadersEncryptionatrest

Step Functions Patterns

1. State Machine Types

STEPFUNCTIONSTYPESStandard:Exactly-onceexecutionUpto1yeardurationChargedperstatetransitionFullexecutionhistoryExpress:At-least-onceexecutionUpto5minutesdurationChargedperexecutionHighvolume,lowlatency

2. Common States

States:Task-InvokeLambda,ECS,etc.Choice-ConditionalbranchingParallel-ExecutebranchesconcurrentlyMap-ProcessitemsinarrayWait-DelayexecutionPass-PassinputtooutputSucceed/Fail-Terminalstates

Exam Scenarios

Scenario 1: High-Volume Event Processing

Requirement:Process100,000events/secSolution:KinesisDataStreams(shards)Lambdawithenhancedfan-outDynamoDBforstateAmazonDataFirehoseforarchival

Scenario 2: Async Workflow

Requirement:Multi-steporderprocessingSolution:APIGatewayLambda(acceptorder)SQSLambda(processeachstep)StepFunctions(orchestrate)SNS(notifications)

Scenario 3: Real-time Dashboard

Requirement:LiveupdatestowebclientsSolution:APIGatewayWebSocketLambdaformessagehandlingDynamoDBforconnectionstateSNSforbroadcasting

Quick Reference

SERVERLESSSELECTIONGUIDEPatternServicesRESTAPIAPIGateway+Lambda+DynamoDBGraphQLAppSync+DynamoDBEventProcessingEventBridge+LambdaQueueProcessingSQS+LambdaStreamProcessingKinesis+LambdaWorkflowStepFunctionsFileProcessingS3+LambdaScheduledTasksEventBridge+LambdaReal-timeAPIGatewayWebSocketContainerServerlessFargate

Câu hỏi ôn tập

  1. Fan-out với SNS → SQS → Lambda có lợi gì so với SNS → Lambda trực tiếp?

    Xem đáp án

    Chèn SQS giữa SNS và Lambda cho: (1) buffer khi consumer chậm/chết — message không mất (SNS invoke Lambda fail chỉ retry giới hạn), (2) rate control qua batch size + reserved concurrency, (3) DLQ per consumer với maxReceiveCount, (4) replay dễ hơn. Trade-off: thêm latency và chi phí SQS. Cần ordering trong fan-out → SNS FIFO + SQS FIFO (message group) — EventBridge không đảm bảo ordering.

  2. Standard vs Express Step Functions — chọn theo tiêu chí nào?

    Xem đáp án

    Standard: exactly-once, chạy tới 1 năm, tính phí per state transition, full history — cho workflow nghiệp vụ (order saga, human approval, long-running). Express: at-least-once (phải idempotent), tối đa 5 phút, tính phí per execution + duration, rẻ hơn nhiều ở volume cao — cho event processing/IoT ingestion tần suất lớn. Keyword "high-volume short-lived executions, cost-effective" → Express; "long-running with audit trail" → Standard.

  3. Vì sao visibility timeout của SQS phải lớn hơn function timeout của Lambda?

    Xem đáp án

    Lambda poll message → message ẩn trong visibility timeout; nếu function còn đang xử lý mà visibility timeout hết, message hiện lại và consumer khác xử lý trùng lặp. Khuyến nghị AWS: visibility timeout ≥ 6× function timeout (tính cả retry + batch window). Kèm theo: maxReceiveCount → DLQ để message hỏng không loop vô hạn, và bật partial batch failure reporting (ReportBatchItemFailures) để chỉ retry message fail trong batch.

  4. Xử lý request vượt 29 giây sau API Gateway thế nào cho đúng pattern?

    Xem đáp án

    Pattern chuẩn async + polling/callback: API Gateway → Lambda nhận job, đẩy SQS/Step Functions, trả 202 Accepted + job ID ngay; client poll endpoint status (hoặc nhận WebSocket/webhook khi xong). Lưu ý cập nhật 06/2024: REST/HTTP API Regional có thể request nâng integration timeout quá 29s (đổi lại giảm throttle quota) — nhưng với đề thi, nâng timeout hiếm khi là "best answer" so với thiết kế async đúng nghĩa.

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

  1. Queue-based load leveling: dựng API Gateway → Lambda → SQS → Lambda worker (reserved concurrency 2); bơm 500 request nhanh và quan sát queue depth tăng rồi tiêu dần — hệ thống không rớt request.

  2. Saga với Step Functions: tạo state machine 3 bước (reserve inventory → charge payment → confirm) với Catch chuyển sang bước compensation (release/refund); chạy input gây fail ở bước 2 và xem nhánh rollback trong console.

  3. Async API pattern: implement endpoint POST /jobs trả 202 + jobId (ghi DynamoDB), worker xử lý 2 phút, endpoint GET /jobs/{id} trả status — mô phỏng đúng đáp án "long-running task behind API Gateway".


Tài liệu tham khảo chính thức


Tiếp theo: Quiz Tuần 9-10