</>Học Dev
Bài học

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

Tuần 10 – Ngày 2

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

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:SetrealistictimeoutsAPIGatewaymax:29secondsConsiderStepFunctionsforlongtasksHandletimeoutsgracefully

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

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


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