Tuần 10 - Ngày 2: Serverless Patterns và Best Practices Tổng quan Serverless Architecture ┌─────────────────────────────────────────────────────────────┐│SERVERLESSARCHITECTURE││││CoreServices:││├──Compute:Lambda,Fargate││├──API:APIGateway,AppSync││├──Storage:S3,DynamoDB││├──Messaging:SQS,SNS,EventBridge││└──Orchestration:StepFunctions││││Benefits:││├──Noservermanagement││├──Auto-scaling││├──Payperuse││└──Highavailabilitybuilt-in│└─────────────────────────────────────────────────────────────┘ Common Serverless Patterns 1. API Backend Pattern ┌────────────────────────────────────────────────────────────┐│RESTAPIBACKEND││││Client→APIGateway→Lambda→DynamoDB│││││├──Cognito(auth)││└──CloudWatch(logs)││││Variations:││├──Lambdaperendpoint││├──Lambdaperresource(monolith)││└──LambdaperHTTPmethod│└────────────────────────────────────────────────────────────┘ GraphQL Variant: Client→AppSync→Lambda/DynamoDB│├──Real-timesubscriptions├──Offlinesupport└──Built-incaching 2. Event Processing Pattern ┌────────────────────────────────────────────────────────────┐│EVENT-DRIVENPROCESSING││││EventSourceProcessorTarget││───────────────────────────││S3Upload→Lambda→DynamoDB││DynamoDBStream→Lambda→SNS/SQS││IoTRule→Lambda→Timestream││CloudWatchEvent→Lambda→Anyservice││││EventBridge:││┌──────────┐┌──────────┐┌──────────┐│││Event│→│Rule│→│Target││││Source││(Filter)││(Lambda)│││└──────────┘└──────────┘└──────────┘│└────────────────────────────────────────────────────────────┘ 3. Fan-Out Pattern ┌────────────────────────────────────────────────────────────┐│FAN-OUTPATTERN││││┌──→Lambda1→ServiceA│││││Event→SNSTopic───┼──→Lambda2→ServiceB│││││└──→SQSQueue→Lambda3││││Usecases:││├──Multi-destinationnotifications││├──Parallelprocessing││└──Cross-accounteventdistribution│└────────────────────────────────────────────────────────────┘ 4. Queue-Based Load Leveling ┌────────────────────────────────────────────────────────────┐│QUEUE-BASEDLOADLEVELING││││┌─────────┐┌─────────────┐┌─────────┐│││Producer│→│SQSQueue│→│Lambda│││└─────────┘└─────────────┘└─────────┘││││Benefits:││├──Decoupleproducer/consumer││├──Buffertrafficspikes││├──Retryfailedprocessing││└──Scaleconsumersindependently││││Lambda+SQSConfiguration:││├──Batchsize:1-10,000││├──Batchwindow:0-300seconds││├──Concurrency:reservedorunreserved││└──DLQforfailedmessages│└────────────────────────────────────────────────────────────┘ 5. Saga Pattern (Distributed Transactions) ┌────────────────────────────────────────────────────────────┐│SAGAPATTERNvớiStepFunctions││││OrderService:││┌────────────────────────────────────────────────────┐│││CreateOrder→ReserveInventory→ProcessPayment│││││││││││▼▼▼││││[Iffail][Iffail][Iffail]││││CancelOrderReleaseInventoryRefundPayment│││└────────────────────────────────────────────────────┘││││StepFunctionsprovides:││├──Visualworkflow││├──Errorhandlingandretry││├──Compensation(rollback)logic││└──Statepersistence│└────────────────────────────────────────────────────────────┘ 6. Strangler Fig Pattern ┌────────────────────────────────────────────────────────────┐│STRANGLERFIGMIGRATION││││Phase1:Proxyalltraffic││┌────────────────────────────────────────────────────┐│││Client→APIGateway→LegacyMonolith│││└────────────────────────────────────────────────────┘││││Phase2:Routesomepathstonewservices││┌────────────────────────────────────────────────────┐│││Client→APIGateway─┬→/users→Lambda││││└→/*→LegacyMonolith│││└────────────────────────────────────────────────────┘││││Phase3:Alltraffictonewservices││┌────────────────────────────────────────────────────┐│││Client→APIGateway─┬→/users→Lambda││││├→/orders→Lambda││││└→/products→Lambda│││└────────────────────────────────────────────────────┘│└────────────────────────────────────────────────────────────┘ Lambda Best Practices 1. Cold Start Optimization ┌─────────────────────────────────────────────────────────────┐│COLDSTARTMITIGATION││││Strategies:││├──ProvisionedConcurrency(guaranteedwarm)││├──Keepfunctionswarm(scheduledinvocation)││├──Minimizepackagesize││├──UseARM(Graviton)-fasterinit││└──Initializeoutsidehandler││││CodePattern:││┌─────────────────────────────────────────────────────┐│││//InitializeOUTSIDEhandler(runsonce)││││constdb=newDynamoDB.DocumentClient();││││││││//Handler(runseveryinvocation)││││exports.handler=async(event)=>{││││//Usepre-initializeddbclient││││returndb.get(...);││││};│││└─────────────────────────────────────────────────────┘│└─────────────────────────────────────────────────────────────┘ 2. Memory and Timeout MemoryConfiguration:├──Morememory=moreCPU├──128MBto10,240MB├──Cost=(memory×duration)├──UseAWSLambdaPowerTuningTimeoutBestPractices:├──Setrealistictimeouts├──APIGatewaymax:29seconds├──ConsiderStepFunctionsforlongtasks└──Handletimeoutsgracefully 3. Error Handling ┌─────────────────────────────────────────────────────────────┐│ERRORHANDLINGPATTERNS││││Sync(APIGateway):││├──ReturnproperHTTPstatuscodes││├──Includeerrordetailsinresponse││└──LogerrorstoCloudWatch││││Async(S3,SNS,etc):││├──Built-inretry(2times)││├──DeadLetterQueue(DLQ)││├──Destinations(success/failure)││└──EventBridgeforfailedevents││││SQSTrigger:││├──Visibilitytimeout>functiontimeout││├──Maxreceivecount→DLQ││└──Partialbatchfailurereporting│└─────────────────────────────────────────────────────────────┘ API Gateway Patterns 1. REST API vs HTTP API ┌─────────────────────────────────────────────────────────────┐│APIGATEWAYTYPES││││RESTAPI:││├──Fullfeatureset││├──Request/Responsevalidation││├──Caching││├──WAFintegration││└──Highercost││││HTTPAPI:││├──70%cheaper││├──Lowerlatency││├──NativeOIDC/OAuth2││├──CORSbuilt-in││└──Limitedfeatures││││WebSocketAPI:││├──Real-time,bidirectional││├──Chat,gaming,IoT││└──$connect,$disconnect,$defaultroutes│└─────────────────────────────────────────────────────────────┘ 2. Caching Strategy APIGatewayCaching:├──Cacheperstage├──TTL:0-3600seconds├──Cachekey:querystring,headers├──Cacheinvalidationviaheaders└──Encryptionatrest Step Functions Patterns 1. State Machine Types ┌─────────────────────────────────────────────────────────────┐│STEPFUNCTIONSTYPES││││Standard:││├──Exactly-onceexecution││├──Upto1yearduration││├──Chargedperstatetransition││└──Fullexecutionhistory││││Express:││├──At-least-onceexecution││├──Upto5minutesduration││├──Chargedperexecution││└──Highvolume,lowlatency│└─────────────────────────────────────────────────────────────┘ 2. Common States States:├──Task-InvokeLambda,ECS,etc.├──Choice-Conditionalbranching├──Parallel-Executebranchesconcurrently├──Map-Processitemsinarray├──Wait-Delayexecution├──Pass-Passinputtooutput├──Succeed/Fail-Terminalstates Exam Scenarios Scenario 1: High-Volume Event Processing Requirement:Process100,000events/secSolution:├──KinesisDataStreams(shards)├──Lambdawithenhancedfan-out├──DynamoDBforstate└──AmazonDataFirehoseforarchival Scenario 2: Async Workflow Requirement:Multi-steporderprocessingSolution:├──APIGateway→Lambda(acceptorder)├──SQS→Lambda(processeachstep)├──StepFunctions(orchestrate)└──SNS(notifications) Scenario 3: Real-time Dashboard Requirement:LiveupdatestowebclientsSolution:├──APIGatewayWebSocket├──Lambdaformessagehandling├──DynamoDBforconnectionstate└──SNSforbroadcasting Quick Reference ┌─────────────────────────────────────────────────────────────┐│SERVERLESSSELECTIONGUIDE││││Pattern│Services││─────────────────────┼─────────────────────────││RESTAPI│APIGateway+Lambda+DynamoDB││GraphQL│AppSync+DynamoDB││EventProcessing│EventBridge+Lambda││QueueProcessing│SQS+Lambda││StreamProcessing│Kinesis+Lambda││Workflow│StepFunctions││FileProcessing│S3+Lambda││ScheduledTasks│EventBridge+Lambda││Real-time│APIGatewayWebSocket││ContainerServerless│Fargate│└─────────────────────────────────────────────────────────────┘ Tài liệu tham khảo chính thức AWS Lambda Developer Guide Amazon API Gateway AWS Step Functions Serverless Land Patterns Tiếp theo: Quiz Tuần 9-10