devHọc Dev
EN
Bài học

Tuần 5 - Ngày 2: Modernization Patterns và Serverless Patterns

Tuần 5 – Ngày 2

Bài này gộp 2 chủ đề: Modernization Patterns, Serverless Patterns và Best Practices.

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

  • Hiểu modernization spectrum (VMs → managed services → containers → serverless) và trade-off
  • Nắm Strangler Fig pattern để tách monolith an toàn
  • Biết kiến trúc microservices/event-driven trên AWS và các pattern Gen AI (Bedrock, RAG)
  • 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

Phần 1: Modernization Patterns

1. Modernization Paths

┌─────────────────────────────────────────────────────────┐│MODERNIZATIONSPECTRUM││││Lift&Shift──────────────────────►Cloud-Native││││┌──────────┐┌──────────┐┌──────────┐┌──────────┐│││EC2││Managed││Containers││Serverless││││(VMs)││Services││(ECS/EKS)││(Lambda)│││└──────────┘└──────────┘└──────────┘└──────────┘││││LessChange───────────────────────MoreChange││LowerBenefit──────────────────────HigherBenefit│└─────────────────────────────────────────────────────────┘

2. Strangler Fig Pattern

┌─────────────────────────────────────────────────────────┐│STRANGLERFIGPATTERN││││Phase1:Facadeinfrontofmonolith││┌───────────┐┌───────────────────────┐│││Facade│────►│Monolith││││(ALB)│└───────────────────────┘││└───────────┘││││Phase2:Extractservicesgradually││┌───────────┐┌───────────────────────┐│││Facade│────►│Monolith(shrinking)││││(ALB)│└───────────────────────┘││││────►┌───────────┐│││││ServiceA│(newmicroservice)││└───────────┘└───────────┘││││Phase3:Completemigration││┌───────────┐┌───────────┐│││Facade│────►│ServiceA││││(ALB)│────►│ServiceB│││││────►│ServiceC│││└───────────┘└───────────┘│└─────────────────────────────────────────────────────────┘

3. Microservices on AWS

┌─────────────────────────────────────────────────────────┐│MICROSERVICESARCHITECTURE││││┌────────────┐│││APIGateway│││└─────┬──────┘│││││┌──────────────────┼──────────────────┐││▼▼▼││┌─────────┐┌─────────┐┌─────────┐│││ServiceA││ServiceB││ServiceC││││(ECS)││(Lambda)││(EKS)│││└────┬────┘└────┬────┘└────┬────┘│││││││▼▼▼││┌─────────┐┌─────────┐┌─────────┐│││DynamoDB││RDS││S3│││└─────────┘└─────────┘└─────────┘││││Communication:││-Sync:APIGateway,ALB││-Async:SQS,SNS,EventBridge││-ServiceMesh:VPCLattice/ECSServiceConnect││(AppMeshđãEOS30/09/2026)│└─────────────────────────────────────────────────────────┘

4. Event-Driven Architecture

┌─────────────────────────────────────────────────────────┐│EVENT-DRIVENPATTERNS││││Publisher──►EventBridge──►Subscribers││││Benefits:││-Loosecoupling││-Scalability││-Flexibility││││Components:││-EventBridge(eventbus)││-SNS(pub/sub)││-SQS(queue)││-Kinesis(streaming)│└─────────────────────────────────────────────────────────┘

5. Amazon MQ — Re-platform Messaging

Managed message broker cho Apache ActiveMQ và RabbitMQ. Đây là lựa chọn re-platform cho messaging: app on-prem đang dùng message broker với protocol chuẩn công nghiệp — JMS, AMQP 0-9-1, MQTT, OpenWire, STOMP — migrate lên cloud mà không sửa code ứng dụng, chỉ đổi connection endpoint sang broker của Amazon MQ.

┌─────────────────────────────────────────────────────────────┐│AMAZONMQ—MIGRATEWITHOUTCODECHANGE││││On-premAWS││┌──────────┐JMS/AMQP/MQTT┌─────────────────────┐│││App│───────────────►│AmazonMQbroker││││(không│(protocolgiữ│(ActiveMQ/RabbitMQ││││đổicode)│nguyên)│trongVPC)│││└──────────┘└─────────────────────┘││││HAoptions:││-ActiveMQ:active/standbymulti-AZ,sharedstorage││trênAmazonEFS→failovertựđộng,messagekhôngmất││-RabbitMQ:clusterdeployment3nodestrải3AZ│└─────────────────────────────────────────────────────────────┘

Amazon MQ vs SQS/SNS

Tiêu chíAmazon MQSQS/SNS
ProtocolJMS, AMQP 0-9-1, MQTT, OpenWire, STOMP (chuẩn công nghiệp)API riêng của AWS (HTTPS)
Migrate app cũKhông cần sửa codePhải rewrite messaging layer
Throughput/scaleGiới hạn theo instance size của brokerCloud-native, scale gần như vô hạn
NetworkChạy trong VPC (endpoint riêng)Public endpoint (hỗ trợ VPC endpoint)
AuthUsername/password của broker (+ LDAP với ActiveMQ)IAM policies
Operational overheadVẫn phải chọn instance size, quản lý broker configThấp nhất (fully serverless)
Use caseApp cũ dùng ActiveMQ/RabbitMQ/protocol chuẩnApp mới build trên AWS

Nguyên tắc chọn cho exam: app mới → luôn ưu tiên SQS/SNS (scale tốt hơn, rẻ hơn, ít vận hành hơn); app hiện có đang dùng messaging protocol chuẩn và yêu cầu "migrate messaging without rewriting application code" → Amazon MQ. Nếu đề bài cho phép sửa code và nhấn "unlimited scale" / "least operational overhead" thì SQS/SNS mới là đáp án — đừng chọn MQ chỉ vì thấy chữ "message broker".

6. Generative AI Modernization Patterns

AWS đẩy mạnh dịch vụ Gen AI từ 2023-2024. SAP-C02 (post-2024) bắt đầu xuất hiện scenario về kiến trúc AI-augmented application — cần nắm các lựa chọn chính.

Amazon Bedrock (managed Foundation Models)

┌──────────────────────────────────────────────────────────────┐│AMAZONBEDROCK││││FullymanagedserviceforfoundationmodelsviasingleAPI││││Availablemodels:││-AnthropicClaude(Sonnet,Opus,Haiku)││-AmazonTitan(text,embeddings,image)││-MetaLlama3││-Mistral,AI21Jurassic,Cohere,StabilityAI││││Keyfeatures:││-Serverless(noinfratomanage)││-Private—datakhôngdùngđểtrainbasemodel││-VPCendpointsupport(PrivateLink)││-IAM-basedaccess,KMSencryption││││BedrockfeaturesSAP-C02hayhỏi:││-KnowledgeBases(RAG:retrieval-augmentedgeneration)││-Agents(tooluse,multi-stepreasoning)││-Guardrails(contentfiltering,PIIredaction)││-Modelevaluation,fine-tuning,provisionedthroughput│└──────────────────────────────────────────────────────────────┘

Khi nào dùng Bedrock: cần thêm Gen AI vào application mà không muốn quản lý GPU/model serving. Multi-tenant, cross-account access qua IAM Identity Center hoặc resource-based policies.

Bedrock vs SageMaker JumpStart vs Self-managed

Tiêu chíBedrockSageMaker JumpStartSelf-managed (EC2/EKS)
Quản lý infraKhông (serverless)One-click deploy lên endpointToàn bộ tự quản
Customize modelFine-tuning có giới hạnFull fine-tuning, custom trainingToàn quyền
Cost modelPer tokenEndpoint + storageEC2/GPU hours
PrivacyData không leak ra base modelTrong VPC, isolatedFull control
Operational overheadThấp nhấtTrung bìnhCao nhất
Use caseProduction Gen AI app, RAG, agentCustom model, fine-tune sâuCó yêu cầu compliance đặc biệt

Pattern: RAG (Retrieval-Augmented Generation)

┌─────────────────────────────────────────────────────────────┐│RAGARCHITECTURETRÊNAWS││││Userquery│││││▼││┌──────────────┐│││App(Lambda)│││└──────┬───────┘│││1.Embedquery││▼││┌──────────────────┐│││BedrockTitan│←Embeddingsmodel│││Embeddings│││└──────┬───────────┘│││2.Vectorsearch││▼││┌──────────────────┐│││Vectorstore│←OpenSearchServerless,│││(knowledgebase)│Aurorapgvector,Neptune,S3││└──────┬───────────┘│││3.Retrievedcontext+query││▼││┌──────────────────┐│││BedrockClaude/│←LLMgeneratesanswerusingcontext│││Llama/Titan│││└──────┬───────────┘│││4.Generatedresponse││▼││User││││Managedoption:BedrockKnowledgeBasestựđộnghoá││toànbộpipelineembed/store/retrieve.│└─────────────────────────────────────────────────────────────┘

Các dịch vụ AI/ML khác SAP-C02 hay hỏi

  • SageMaker: end-to-end ML platform (train, deploy, monitor models)
  • SageMaker JumpStart: pre-trained models + solution templates
  • Comprehend: NLP (sentiment, entity recognition, language detection)
  • Textract: OCR + form/table extraction
  • Rekognition: image/video analysis (faces, objects, moderation)
  • Transcribe / Polly: speech-to-text / text-to-speech
  • Translate: real-time translation
  • Lex: build chatbot/voice bot với ASR + NLU (intents/slots — cùng công nghệ Alexa); tích hợp Amazon Connect để tự động hoá contact center
  • Kendra: enterprise search bằng ML trên tài liệu nội bộ (connectors: S3, SharePoint, Salesforce...), trả lời câu hỏi ngôn ngữ tự nhiên; hay dùng làm retriever cho RAG với Bedrock
  • Personalize: recommendation engine (rất phù hợp với e-commerce)
  • Q Developer (formerly CodeWhisperer): AI code assistant cho IDE/CLI

Exam keyword cho Gen AI scenario

Yêu cầu trong câu hỏiService phù hợp
"Use foundation models với least operational overhead"Bedrock
"Customize model với enterprise data, không leak data"Bedrock fine-tuning hoặc Knowledge Bases
"Build chatbot với context từ internal docs"Bedrock + Knowledge Bases (RAG)
"Multi-step agent với tool use"Bedrock Agents
"Content moderation, PII redaction"Bedrock Guardrails hoặc Comprehend PII
"Train custom model từ đầu, full control"SageMaker (training jobs)
"Quick deploy pre-trained model"SageMaker JumpStart
"Automated customer service chatbot" (contact center)Lex (+ Amazon Connect)
"Natural language search across company documents"Kendra

Phần 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├──APIGatewayintegrationtimeout:default29seconds│(từ06/2024RESTAPIRegional/privatecóthểrequest│nângquá29s—trade-offgiảmthrottlequota;│HTTPAPItốiđa30s,edge-optimized29s:khôngnângđược;│patternchuẩnchotácvụdàivẫnlàasync+polling)├──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│└─────────────────────────────────────────────────────────────┘

Câu hỏi ôn tập

  1. Strangler Fig pattern hoạt động thế nào và vì sao an toàn hơn big-bang rewrite?

    Xem đáp án

    Đặt facade (ALB/API Gateway) trước monolith, rồi tách dần từng chức năng thành service mới — facade route path đã migrate sang service mới, phần còn lại vẫn vào monolith, đến khi monolith "bị siết" hết. An toàn hơn big-bang vì: mỗi bước nhỏ có thể rollback (đổi routing), business chạy liên tục, học được từ service đầu trước khi tách tiếp, và giảm rủi ro "rewrite 2 năm không release gì". Keyword "gradually migrate monolith with minimal risk" → Strangler Fig.

  2. Chọn sync (API) hay async (event) cho giao tiếp giữa microservices?

    Xem đáp án

    Sync (API Gateway/ALB): khi caller cần kết quả ngay (query, validate) — nhưng tạo temporal coupling, service B chết kéo A chết theo. Async (SQS/SNS/EventBridge): khi xử lý có thể trễ (order processing, notification) — loose coupling, buffer spike, retry tự nhiên; trade-off là eventual consistency và khó debug hơn (cần tracing). Nguyên tắc Professional: mặc định async giữa bounded contexts, sync chỉ trong critical read path — nhiều câu exam thưởng cho việc chèn SQS giữa 2 tier để "decouple and absorb spikes".

  3. Khi nào Bedrock Knowledge Bases là đáp án thay vì fine-tuning?

    Xem đáp án

    Knowledge Bases (RAG): kiến thức nằm trong tài liệu thay đổi thường xuyên (policy nội bộ, docs sản phẩm) — model lấy context lúc query, cập nhật chỉ cần re-index, không train lại, dữ liệu kiểm soát được (citation). Fine-tuning: cần đổi hành vi/giọng điệu/format của model hoặc domain đặc thù mà prompt + RAG không đủ — tốn kém hơn, cập nhật kiến thức chậm. Keyword "chatbot answers from internal documents, always up to date" → Knowledge Bases; "model must follow company-specific style at scale" → fine-tuning.

  4. App2Container phù hợp scenario nào trong modernization?

    Xem đáp án

    App2Container (A2C): CLI phân tích app Java/.NET đang chạy trên VM/on-prem, tự đóng gói thành container image + sinh ECS/EKS artifacts và pipeline — dùng cho bước "containerize without code changes" (giữa Rehost và Refactor). Phù hợp: legacy app không có Dockerfile, team muốn chuẩn hoá lên ECS/EKS nhanh. Không phù hợp: app cần rewrite logic (Refactor thật sự) hoặc COTS app không hỗ trợ.

  5. Công ty migrate app on-prem đang dùng ActiveMQ với JMS lên AWS, yêu cầu không sửa code ứng dụng. Chọn Amazon MQ hay SQS/SNS, và thiết kế HA thế nào?

    Xem đáp án

    Amazon MQ (ActiveMQ engine) — hỗ trợ nguyên protocol JMS/OpenWire nên app chỉ cần đổi endpoint, đúng keyword "migrate messaging without rewriting application code" (re-platform). SQS/SNS bắt buộc rewrite messaging layer sang AWS API nên loại. HA: deploy active/standby multi-AZ với shared storage trên EFS — broker standby ở AZ khác tự động takeover khi active fail, message không mất. (Với RabbitMQ engine thì HA là cluster 3 nodes trải 3 AZ.) Ngược lại, nếu là app mới hoặc đề cho phép sửa code + nhấn "unlimited scale"/"least operational overhead" → SQS/SNS.

  6. Chatbot tự phục vụ khách hàng cần trả lời từ tài liệu nội bộ: khi nào dùng Lex, khi nào dùng Kendra, khi nào kết hợp?

    Xem đáp án

    Lex = giao diện hội thoại (ASR + NLU, intents/slots): nhận yêu cầu người dùng qua voice/text, phù hợp "automated customer service chatbot", tích hợp Amazon Connect cho contact center. Kendra = ML-powered enterprise search: index tài liệu nội bộ (S3, SharePoint, Salesforce...) và trả lời câu hỏi ngôn ngữ tự nhiên — keyword "natural language search across company documents". Kết hợp: Lex nhận intent, fulfillment (Lambda) query Kendra để lấy câu trả lời từ docs; hoặc pattern hiện đại hơn là Kendra làm retriever cho RAG với Bedrock. Lex không tự tìm trong tài liệu, Kendra không tự quản hội thoại — đề hỏi cả hai vế thì đáp án là kiến trúc ghép.

  7. 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.

  8. 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.

  9. 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.

  10. 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 API Regional và private có thể request nâng integration timeout quá 29s (đổi lại có thể bị giảm throttle quota của account); REST API edge-optimized (29s) và HTTP API (tối đa 30s) không nâng được — 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

Phần 1: Modernization Patterns

  1. Strangler Fig mini: dựng "monolith" (1 EC2/container với route /orders và /users), đặt ALB trước; tách /users thành Lambda + target group mới, đổi listener rule để /users đi Lambda — monolith không đổi code.

  2. Event-driven decouple: thay call trực tiếp giữa 2 service demo bằng EventBridge (publisher bắn event OrderCreated, consumer Lambda xử lý); tắt consumer và verify event không mất (archive + DLQ), bật lại xử lý tiếp.

  3. RAG với Bedrock Knowledge Bases: tạo Knowledge Base từ vài file PDF trong S3 (OpenSearch Serverless auto), hỏi qua console/API và kiểm tra citation trỏ đúng tài liệu nguồn.

Phần 2: Serverless Patterns và Best Practices

  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


Bài tiếp theo →