devHọc Dev

Week 5 - Day 2: Modernization Patterns and Serverless Patterns

Week 5 – Day 2

This lesson combines 2 topics: Modernization Patterns, Serverless Patterns and Best Practices.

Learning Objectives

  • Understand the modernization spectrum (VMs → managed services → containers → serverless) and its trade-offs
  • Master the Strangler Fig pattern to break up a monolith safely
  • Know microservices/event-driven architectures on AWS and Gen AI patterns (Bedrock, RAG)
  • Recognize the 6 classic serverless patterns (API backend, event processing, fan-out, load leveling, saga, strangler fig)
  • Master Lambda best practices: cold start, memory/timeout, error handling by invocation type
  • Choose correctly between REST API vs HTTP API vs WebSocket and Standard vs Express Step Functions

Part 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││(AppMeshreachedEOSon09/30/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

A managed message broker for Apache ActiveMQ and RabbitMQ. This is the re-platform option for messaging: on-prem apps that use a message broker with industry-standard protocols — JMS, AMQP 0-9-1, MQTT, OpenWire, STOMP — migrate to the cloud without changing application code, only switching the connection endpoint to the Amazon MQ broker.

┌─────────────────────────────────────────────────────────────┐│AMAZONMQ—MIGRATEWITHOUTCODECHANGE││││On-premAWS││┌──────────┐JMS/AMQP/MQTT┌─────────────────────┐│││App│───────────────►│AmazonMQbroker││││(nocode│(protocol│(ActiveMQ/RabbitMQ││││changes)│unchanged)│inaVPC)│││└──────────┘└─────────────────────┘││││HAoptions:││-ActiveMQ:active/standbymulti-AZ,sharedstorage││onAmazonEFS→automaticfailover,nomessageloss││-RabbitMQ:clusterdeploymentof3nodesacross3AZs│└─────────────────────────────────────────────────────────────┘

Amazon MQ vs SQS/SNS

CriterionAmazon MQSQS/SNS
ProtocolJMS, AMQP 0-9-1, MQTT, OpenWire, STOMP (industry standard)AWS-specific API (HTTPS)
Migrating legacy appsNo code changes neededMust rewrite the messaging layer
Throughput/scaleLimited by the broker instance sizeCloud-native, nearly unlimited scale
NetworkRuns in a VPC (private endpoint)Public endpoint (VPC endpoint supported)
AuthBroker username/password (+ LDAP with ActiveMQ)IAM policies
Operational overheadYou still choose the instance size and manage broker configLowest (fully serverless)
Use caseExisting apps using ActiveMQ/RabbitMQ/standard protocolsNew apps built on AWS

Exam selection rule: for new apps → always prefer SQS/SNS (better scale, cheaper, less operations); for existing apps that use a standard messaging protocol with the requirement "migrate messaging without rewriting application code" → Amazon MQ. If the question allows code changes and emphasizes "unlimited scale" / "least operational overhead", then SQS/SNS is the answer — do not pick MQ just because you see the words "message broker".

6. Generative AI Modernization Patterns

AWS has pushed hard on Gen AI services since 2023-2024. SAP-C02 (post-2024) has started including scenarios about AI-augmented application architectures — you need to know the main options.

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—dataisnotusedtotrainthebasemodel││-VPCendpointsupport(PrivateLink)││-IAM-basedaccess,KMSencryption││││BedrockfeaturesSAP-C02oftenasksabout:││-KnowledgeBases(RAG:retrieval-augmentedgeneration)││-Agents(tooluse,multi-stepreasoning)││-Guardrails(contentfiltering,PIIredaction)││-Modelevaluation,fine-tuning,provisionedthroughput│└──────────────────────────────────────────────────────────────┘

When to use Bedrock: you need to add Gen AI to an application without managing GPUs/model serving. Multi-tenant, cross-account access via IAM Identity Center or resource-based policies.

Bedrock vs SageMaker JumpStart vs Self-managed

CriterionBedrockSageMaker JumpStartSelf-managed (EC2/EKS)
Infra managementNone (serverless)One-click deploy to an endpointFully self-managed
Model customizationLimited fine-tuningFull fine-tuning, custom trainingFull control
Cost modelPer tokenEndpoint + storageEC2/GPU hours
PrivacyData does not leak into the base modelIn a VPC, isolatedFull control
Operational overheadLowestMediumHighest
Use caseProduction Gen AI apps, RAG, agentsCustom models, deep fine-tuningSpecial compliance requirements

Pattern: RAG (Retrieval-Augmented Generation)

┌─────────────────────────────────────────────────────────────┐│RAGARCHITECTUREONAWS││││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:BedrockKnowledgeBasesautomatesthe││entireembed/store/retrievepipeline.│└─────────────────────────────────────────────────────────────┘

Other AI/ML services SAP-C02 often asks about

  • 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 chatbots/voice bots with ASR + NLU (intents/slots — the same technology as Alexa); integrates with Amazon Connect to automate contact centers
  • Kendra: ML-powered enterprise search over internal documents (connectors: S3, SharePoint, Salesforce...), answers natural language questions; often used as the retriever for RAG with Bedrock
  • Personalize: recommendation engine (a great fit for e-commerce)
  • Q Developer (formerly CodeWhisperer): AI code assistant for IDE/CLI

Exam keywords for Gen AI scenarios

Requirement in the questionMatching service
"Use foundation models with least operational overhead"Bedrock
"Customize model with enterprise data, no data leakage"Bedrock fine-tuning or Knowledge Bases
"Build chatbot with context from internal docs"Bedrock + Knowledge Bases (RAG)
"Multi-step agent with tool use"Bedrock Agents
"Content moderation, PII redaction"Bedrock Guardrails or Comprehend PII
"Train custom model from scratch, 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

Part 2: Serverless Patterns and Best Practices

Serverless Architecture Overview

┌─────────────────────────────────────────────────────────────┐│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)

┌────────────────────────────────────────────────────────────┐│SAGAPATTERNwithStepFunctions││││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│(since06/2024,Regional/privateRESTAPIscanrequest│anincreasebeyond29s—trade-off:lowerthrottlequota;│HTTPAPImax30s,edge-optimized29s:notadjustable;│thestandardpatternforlongtasksisstillasync+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│└─────────────────────────────────────────────────────────────┘

Review Questions

  1. How does the Strangler Fig pattern work, and why is it safer than a big-bang rewrite?

    Show answer

    Put a facade (ALB/API Gateway) in front of the monolith, then extract features one at a time into new services — the facade routes migrated paths to the new services while everything else still goes to the monolith, until the monolith is fully "strangled". It is safer than big-bang because: each small step can be rolled back (change the routing), the business keeps running, you learn from the first service before extracting the next, and it reduces the risk of "a 2-year rewrite with no releases". Keyword "gradually migrate monolith with minimal risk" → Strangler Fig.

  2. Should communication between microservices be sync (API) or async (event)?

    Show answer

    Sync (API Gateway/ALB): when the caller needs the result immediately (query, validate) — but it creates temporal coupling: if service B dies, A goes down with it. Async (SQS/SNS/EventBridge): when processing can be delayed (order processing, notifications) — loose coupling, spike buffering, natural retries; the trade-off is eventual consistency and harder debugging (you need tracing). Professional rule: default to async between bounded contexts, sync only on the critical read path — many exam questions reward inserting SQS between 2 tiers to "decouple and absorb spikes".

  3. When is Bedrock Knowledge Bases the answer instead of fine-tuning?

    Show answer

    Knowledge Bases (RAG): the knowledge lives in frequently changing documents (internal policies, product docs) — the model retrieves context at query time, updates only require re-indexing with no retraining, and the data is controllable (citations). Fine-tuning: you need to change the model's behavior/tone/format or handle a specialized domain where prompts + RAG are not enough — more expensive, and knowledge updates are slow. Keyword "chatbot answers from internal documents, always up to date" → Knowledge Bases; "model must follow company-specific style at scale" → fine-tuning.

  4. Which modernization scenario is App2Container suited for?

    Show answer

    App2Container (A2C): a CLI that analyzes running Java/.NET apps on VMs/on-prem, automatically packages them into container images + generates ECS/EKS artifacts and a pipeline — used for the "containerize without code changes" step (between Rehost and Refactor). Good fit: legacy apps without a Dockerfile, teams that want to standardize on ECS/EKS quickly. Not a good fit: apps that need their logic rewritten (true Refactor) or unsupported COTS apps.

  5. A company is migrating an on-prem app that uses ActiveMQ with JMS to AWS, with the requirement of no application code changes. Choose Amazon MQ or SQS/SNS, and how do you design HA?

    Show answer

    Amazon MQ (ActiveMQ engine) — it supports the JMS/OpenWire protocols as-is, so the app only needs to change its endpoint, matching the keyword "migrate messaging without rewriting application code" (re-platform). SQS/SNS requires rewriting the messaging layer to the AWS API, so it is ruled out. HA: deploy active/standby multi-AZ with shared storage on EFS — the standby broker in another AZ takes over automatically when the active one fails, with no message loss. (With the RabbitMQ engine, HA is a 3-node cluster across 3 AZs.) Conversely, for a new app or when the question allows code changes and emphasizes "unlimited scale"/"least operational overhead" → SQS/SNS.

  6. A self-service customer chatbot must answer from internal documents: when do you use Lex, when do you use Kendra, and when do you combine them?

    Show answer

    Lex = the conversational interface (ASR + NLU, intents/slots): receives user requests via voice/text, fits "automated customer service chatbot", and integrates with Amazon Connect for contact centers. Kendra = ML-powered enterprise search: indexes internal documents (S3, SharePoint, Salesforce...) and answers natural language questions — keyword "natural language search across company documents". Combined: Lex captures the intent, and fulfillment (Lambda) queries Kendra to get the answer from the docs; or the more modern pattern is Kendra as the retriever for RAG with Bedrock. Lex does not search documents on its own, and Kendra does not manage conversations — if the question asks for both, the answer is the combined architecture.

  7. What does fan-out with SNS → SQS → Lambda gain over SNS → Lambda directly?

    Show answer

    Inserting SQS between SNS and Lambda gives: (1) a buffer when the consumer is slow/down — messages are not lost (when SNS fails to invoke Lambda it only retries a limited number of times), (2) rate control via batch size + reserved concurrency, (3) a DLQ per consumer with maxReceiveCount, (4) easier replay. Trade-off: extra latency and SQS cost. If you need ordering in fan-out → SNS FIFO + SQS FIFO (message group) — EventBridge does not guarantee ordering.

  8. Standard vs Express Step Functions — which criteria decide?

    Show answer

    Standard: exactly-once, runs up to 1 year, charged per state transition, full history — for business workflows (order saga, human approval, long-running). Express: at-least-once (must be idempotent), up to 5 minutes, charged per execution + duration, much cheaper at high volume — for high-frequency event processing/IoT ingestion. Keyword "high-volume short-lived executions, cost-effective" → Express; "long-running with audit trail" → Standard.

  9. Why must the SQS visibility timeout be greater than the Lambda function timeout?

    Show answer

    Lambda polls a message → the message is hidden for the visibility timeout; if the function is still processing when the visibility timeout expires, the message reappears and another consumer processes it as a duplicate. AWS recommendation: visibility timeout ≥ 6× the function timeout (accounting for retries + batch window). Alongside that: maxReceiveCount → DLQ so bad messages do not loop forever, and enable partial batch failure reporting (ReportBatchItemFailures) to retry only the failed messages in a batch.

  10. How do you correctly handle requests that exceed 29 seconds behind API Gateway?

Show answer

The standard async + polling/callback pattern: API Gateway → Lambda accepts the job, pushes it to SQS/Step Functions, and immediately returns 202 Accepted + a job ID; the client polls a status endpoint (or receives a WebSocket/webhook notification when done). Note the 06/2024 update: Regional and private REST APIs can request an integration timeout increase beyond 29s (possibly in exchange for a lower account throttle quota); edge-optimized REST APIs (29s) and HTTP APIs (30s maximum) cannot be raised — but on the exam, raising the timeout is rarely the "best answer" compared with a proper async design.

Hands-on Exercises

Part 1: Modernization Patterns

  1. Mini Strangler Fig: build a "monolith" (1 EC2/container with /orders and /users routes) behind an ALB; extract /users into a Lambda + new target group, and change the listener rule so /users goes to Lambda — no code changes to the monolith.

  2. Event-driven decoupling: replace a direct call between 2 demo services with EventBridge (the publisher emits an OrderCreated event, a consumer Lambda processes it); turn off the consumer and verify events are not lost (archive + DLQ), then turn it back on to continue processing.

  3. RAG with Bedrock Knowledge Bases: create a Knowledge Base from a few PDF files in S3 (OpenSearch Serverless auto-created), ask questions through the console/API, and check that the citations point to the correct source documents.

Part 2: Serverless Patterns and Best Practices

  1. Queue-based load leveling: build API Gateway → Lambda → SQS → Lambda worker (reserved concurrency 2); fire 500 requests quickly and watch the queue depth rise and then drain — the system does not drop any requests.

  2. Saga with Step Functions: create a 3-step state machine (reserve inventory → charge payment → confirm) with a Catch that transitions to compensation steps (release/refund); run an input that fails at step 2 and watch the rollback branch in the console.

  3. Async API pattern: implement a POST /jobs endpoint that returns 202 + jobId (written to DynamoDB), a worker that processes for 2 minutes, and a GET /jobs/{id} endpoint that returns the status — simulating exactly the "long-running task behind API Gateway" answer.

References


Next lesson →