Ravindra BagaleCourses & study guides मराठी Track your progress

Serverless IaC: SAM vs Serverless Framework vs CDK Compared

Three toolboxes ship the same Lambda+API stack: AWS SAM (CloudFormation-shaped templates + sam local), Serverless Framework (plugins + multi-cloud history), and AWS CDK (TypeScript/Python that synthesizes CloudFormation). Pick for team skill and CI shape — not blog fashion.

What you'll learn in this chapter

  • Contrast SAM, Serverless Framework, CDK for Lambda apps
  • Run a read-only sam/cdk inspect habit
  • Map local start-api vs unit tests
  • Choose CI deploy path
  • Link the live CDK deep chapter

1. Everyday example: three kitchens, one thali

Priya in Bengaluru (INR) must ship a checkout API. Her teammate knows YAML; another loves TypeScript. Same thali (API Gateway + Lambda + DynamoDB) — different kitchens. Wrong kitchen slows the sprint.

Deep CDK: AWS CDK. Templates under the hood: CloudFormation. Compute: Lambda.

2. Why compare IaC tools?

Why do we need this?

Serverless apps are many small resources. Hand-click console drifts. IaC makes review, rollback, and multi-env possible. Choosing the wrong tool for your team creates glue scripts and abandoned plugins.

What is it?

SAM = AWS-native serverless macros on CloudFormation + sam CLI. Serverless Framework = serverless.yml + plugins. CDK = imperative constructs to CloudFormation.

3. Vertical diagram

App code -> IaC tool -> CloudFormation/API -> AWS resourcesOne source of truth per env
Promote via pipeline not laptop
Same app: API + Lambda + DynamoDB SAMtemplate.yaml Serverlessserverless.yml CDKTS/Python CloudFormation change sets / deploy Dev to staging to prod pipelines Pick by team skills + plugin needs
Three front-doors, one AWS account.

4. How: decision table

How to do it (step by step)

LensSAMServerless FrameworkCDK
Learning curveLow if YAML okMedium + pluginsHigher; code skills
AWS-native fitExcellentGood; extras via pluginsExcellent via L2/L3
Local APIsam local start-apiserverless-offline pluginUnit test constructs; local limited
Multi-cloud storyAWS firstHistorically broaderAWS-first
Best whenTeam already CFN/SAMNeed rich plugin ecosystemComplex apps, shared constructs

5. Per-concept commands

Validate a SAM template (read-only shape)

sam validate --template template.yaml --region ap-south-1

Meaning: Catches obvious template mistakes before deploy.

List CloudFormation stacks (see what IaC owns)

aws cloudformation list-stacks --region ap-south-1 \
  --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE \
  --query 'StackSummaries[].{N:StackName,T:TemplateDescription}' --output table

Meaning: Inventory before you add another tool.

CDK list stacks in app (if cdk installed)

cdk ls --app "npx ts-node bin/app.ts" 2>/dev/null || echo "install cdk in project first" 

Meaning: Shows stacks the app would synthesize — no deploy.

Diff a change set mindset

aws cloudformation describe-stacks --region ap-south-1 \
  --stack-name checkout-api --query 'Stacks[0].{S:StackStatus,U:LastUpdatedTime}' 

Meaning: Always know last update time before touching prod.

6. CI patterns

  • Build then unit test then sam build / cdk synth then deploy to staging then smoke then prod with approval.
  • Never deploy from a laptop to prod; use OIDC roles.
  • Pin plugin and CDK versions; lockfiles matter.
  • Secrets via SSM/Secrets Manager refs — not plaintext in yml.

7. Industries

  • Fintech (Aisha, Lagos, NGN): CDK shared banking constructs; auditors love reviews.
  • Ecommerce (Rohan, Pune, INR): SAM for small checkout; speed.
  • SaaS (Priya, Bengaluru, INR): Serverless Framework plugins for custom domains historically.
  • Gov (Omar, Amman, JOD): CloudFormation/SAM for approved patterns.
  • Media (Kenji, Osaka, JPY): CDK pipelines for many Lambda image jobs.

8. Lab

9. Lab - inspect, do not invent a fourth tool

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

How to do it (step by step)

  1. List stacks in ap-south-1; note which look SAM/CDK named.
  2. Open the linked CDK chapter; skim construct idea.
  3. Write 5 lines: which tool your team would pick and why.
  4. sam validate on a sample template if you have one.

Cleanup (stop billing)

  1. Do not leave experimental stacks.
  2. Delete any lab stack you create.

10. Same pattern across industries

  • Fintech (Aisha, Lagos): payment webhooks → SQS → Lambda; never block the bank callback thread.
  • Ecommerce (Rohan, Pune): checkout API on API Gateway+Lambda; inventory fan-out on SNS.
  • Healthcare (Mei, Singapore): appointment SMS via SNS; PHI stays in DynamoDB with fine-grained IAM.
  • EdTech (Diego, São Paulo): nightly cleanup EventBridge → Lambda on student drafts.
  • Logistics (Fatima, Casablanca): package scan events on EventBridge bus; Step Functions for customs saga.
  • Media (Kenji, Osaka): S3 upload → Lambda thumbnails; fan-out to moderation + CDN invalidate.
  • SaaS multi-tenant (Priya, Bengaluru): Cognito groups + DynamoDB partition per tenant.
  • Gov portal (Omar, Amman): strangler fig — peel one PDF form route per sprint to Lambda.

11. Troubleshooting checklist

  1. Confirm region (ap-south-1 vs us-east-1 for CloudFront/ACM quirks).
  2. Check CloudWatch Logs for the function name and request id.
  3. Verify IAM execution role allows the API you call.
  4. For async: check DLQ depth and SQS age of oldest message.
  5. For APIs: curl -v and compare status, CORS headers, body.
  6. For workflows: open Step Functions execution event history.
  7. Re-read the linked deep chapter before reinventing a service.
  8. If cost spikes: check concurrency, retries, and provisioned capacity.

12. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Two tools fight over one stackOne owner tool per stack; migrate deliberately.
Plugins abandon youPrefer AWS-native path for core resources.
Laptop-only deployMove to CI with approval gates.
Huge template no modulesSplit nested stacks / CDK constructs.
Drift from console clicksRe-import or stop clicking; IaC only.
Wrong region in samconfigSet ap-south-1 explicitly.
CDK synth differs per machineLock Node/Python; CI is source of truth.
Secrets in gitUse dynamic refs; scan CI.
sam local not equal prod VPCDocument gaps; integration test in AWS.

13. FAQ

Q. Is SAM dead?

No — AWS-supported; excellent for serverless CFN.

Q. Must I learn CDK?

If complex apps/shared libs — yes eventually.

Q. Serverless Framework v3 vs v4?

Check license/plugin status for your org before upgrade.

Q. Can I mix?

Possible but costly; prefer one per domain.

Q. Link CDK chapter?

what-is-aws-cdk-cloud-development-kit-typescript-python-explained.

14. Interview Q&A (Beginner / Mid / Senior + MNC)

Q. Beginner: what is IaC?

Define infra in files reviewed like code.

Q. Beginner: SAM vs raw CFN?

SAM adds serverless shortcuts/macros.

Q. Mid: when CDK over SAM?

Reuse, typing, complex graphs.

Q. Mid: local testing limits?

Local misses IAM/VPC/service quirks.

Q. Senior: multi-account?

Pipeline + StackSets/CDK pipelines; least privilege.

Q. MNC: evidence?

Change sets, approvals, immutable artifacts.

15. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

Same thali, pick one kitchen your team can review — then automate promotions.

Ravindra Bagale's Tip (MR)

एक kitchen निवडा — मग promote automate.

Tip (HI)

एक kitchen चुनें — फिर promote automate करें।

Try at home

  1. Name your team's IaC tool in one sentence.
  2. List stacks in ap-south-1.

In short

  1. Start from a real story, then name the AWS services.
  2. Link existing chapters — do not copy their labs.
  3. Design for failure: retries, DLQ, idempotency, rollback.
  4. Measure before you buy provisioned concurrency or multi-region.

16. Architecture decision checklist

  1. Write the user journey in five bullets with no AWS names.
  2. Mark each step sync (user waits) or async.
  3. Name failure mode: retry, DLQ, compensate, or alert-only.
  4. Name the idempotency key for every write.
  5. Pick data store from access patterns (link DynamoDB modeling).
  6. Estimate monthly cost at 1x and 10x traffic (USD and INR).
  7. Confirm account concurrency and service quotas in ap-south-1.
  8. Decide auth: Cognito, IAM, Lambda authorizer, or none.
  9. Name on-call and which CloudWatch alarm pages them.
  10. Link the deep chapter you will not rewrite.
  11. Only then open console or IaC.

17. Copy-paste quick commands (read-only first)

# Region and identity
aws configure get region
aws sts get-caller-identity

# Lambda landscape
aws lambda list-functions --region ap-south-1 --max-items 20 \
  --query 'Functions[].{N:FunctionName,R:Runtime,T:Timeout,M:MemorySize}' --output table
aws lambda get-account-settings --region ap-south-1

# API Gateway (HTTP APIs)
aws apigatewayv2 get-apis --region ap-south-1 --query 'Items[].{N:Name,Id:ApiId,Ep:ProtocolType}' --output table

# Queues and topics
aws sqs list-queues --region ap-south-1
aws sns list-topics --region ap-south-1 --query 'Topics[].TopicArn'

# Event buses and state machines
aws events list-event-buses --region ap-south-1
aws stepfunctions list-state-machines --region ap-south-1 --query 'stateMachines[].name'

# DynamoDB tables (names only)
aws dynamodb list-tables --region ap-south-1

Run these in a sandbox account. Prefer read-only IAM while learning.

18. More industry and stack stories

  • Fintech (Aisha, Lagos, NGN): bank webhooks must return 200 fast — SQS absorbs spikes; ledger Lambda is idempotent on paymentId.
  • Ecommerce (Rohan, Pune, INR): Black Friday — API Gateway throttle + SQS order intake; SNS fans inventory, email, analytics.
  • Healthcare (Mei, Singapore, SGD): appointment reminders via SNS SMS; PHI only in DynamoDB with condition keys.
  • EdTech (Diego, São Paulo, BRL): EventBridge nightly cleanup of draft quizzes; Lambda timeout 30s, not 15 min.
  • Logistics (Fatima, Casablanca, MAD): package scans on custom EventBridge bus; Step Functions customs saga.
  • Media (Kenji, Osaka, JPY): S3 → Lambda thumbnails; never write thumbs to the watched prefix.
  • SaaS (Priya, Bengaluru, INR): Cognito groups + DynamoDB PK tenantId; one Lambda authorizer for all routes.
  • Gov (Omar, Amman, JOD): strangler — peel one PDF form route per sprint from the monolith.
  • Startup (Sofia, Sofia, EUR): start with Function URL for demos; move to HTTP API when partners need JWT.
  • Retail (Luis, Mexico City, MXN): store POS sync via SQS FIFO when order matters; Standard when it does not.
  • Python: handlers thin; put domain logic in plain modules for unit tests without Lambda.
  • Node: prefer async/await; never block the event loop on sync DNS.
  • Java: SnapStart for cold starts; keep dependencies lean.
  • .NET: AspNetCoreServer for low-traffic tenants; watch package size.
  • Go: single static binary; great for SQS workers.
  • PHP: keep Laravel queues on ECS; Lambda for S3/webhooks glue.

19. Glossary (short)

TermMeaning
Cold startFirst invoke pays init; later invokes reuse the env
IdempotencySame request twice → same effect
DLQDead-letter queue for failed messages
ChoreographyServices react to events; no central conductor
OrchestrationCentral workflow (Step Functions) directs steps
Fan-outOne event → many consumers
Fan-inMany branches join before next step
Strangler figPeel routes from monolith gradually
SagaDistributed tx via steps + compensations
Provisioned concurrencyKeep N envs warm; you pay for ready capacity

20. Practice: explain out loud

  1. 60 seconds: everyday story for serverless IaC tools.
  2. 60 seconds: sync vs async with a checkout example.
  3. 60 seconds: when you refuse Lambda.
  4. 60 seconds: DLQ + idempotency in one breath.
  5. Record once; cut fillers; record again.

21. Safe lab hygiene

  • Tag every lab resource with owner and expiry date.
  • Set a monthly AWS Budget alarm in INR or USD before experiments.
  • Prefer read-only commands first; mutate in a sandbox account.
  • Delete queues, APIs, tables you created — DynamoDB and APIGW leave footprints.
  • Never put production secrets in env vars or screenshots.
  • Do not enable provisioned concurrency for a hello-world.

23. Myths to drop

MythReality
Serverless means zero serversServers exist; you do not manage them
Always cheaper than EC2Steady high load can favor EC2/Savings Plans
No Ops neededYou own IAM, data, alarms, cost, incidents
One Lambda per app is fineBounded contexts scale better
Queues are optional decorationQueues are the load leveler and blast-radius wall

24. Error budget thinking for serverless

If your monthly error budget is 0.1% on checkout, a fan-out that retries aggressively can burn the budget with duplicate emails while money stays correct. Separate business correctness SLOs from notification SLOs.

  1. Write two SLOs: money-correct and notify-delivered.
  2. Retries on money path: bounded + idempotent.
  3. Retries on notify path: best-effort + DLQ.
  4. Page humans on money DLQ; ticket on notify DLQ.

25. Regional notes (ap-south-1)

  • Build labs in Mumbai (ap-south-1) unless your org mandates elsewhere.
  • Some services launch first in us-east-1 — check feature availability.
  • Data residency for INR fintech may require in-region only.
  • Latency to end users in India usually favors ap-south-1.

26. Naming conventions that save incidents

# Suggested prefixes
# Lambda:  pay-intake-prod, pay-worker-prod
# SQS:     pay-orders.fifo / pay-orders-dlq
# SNS:     pay-order-events
# EB bus:  pay.domain
# SFN:     pay-refund-saga
# DDB:     pay-orders-prod

Include env (dev/stage/prod) and domain. Future you grepping CloudWatch will thank present you.

27. Pre-mortems (ten minutes)

  1. Imagine tomorrow headline: double charge in AED. What broke?
  2. Imagine DLQ depth 50,000 after a bad deploy. How do you drain?
  3. Imagine Cognito outage. Do APIs fail closed or serve read-only?
  4. Write answers in the runbook before go-live.

28. Currency and locale in examples

Rotate currencies in designs: INR, USD, EUR, AED, NGN, BRL, JPY, SGD. Rotate names: Aisha, Rohan, Mei, Diego, Fatima, Kenji, Priya, Omar, Sofia, Luis. This keeps mental models global — not one-country samples.

29. Worked story: Priya chooses CDK (INR)

  1. Three microservices share auth and table grants.
  2. YAML copy-paste drifts.
  3. CDK construct library centralizes IAM.
  4. Pipeline synth+diff catches sneaky IAM widen.

30. Anti-patterns

  • New tool every sprint.
  • Deploying with admin keys from laptops.
  • Ignoring change set review.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: Three IaC kitchens. Console clicks drift; you need reviewed files. SAM, Serverless Framework, and CDK ship the same Lambda stack differently. Pick by team skill → pin versions → CI promote with change sets. Priya chooses CDK when three services share IAM constructs.
Revision card: Three IaC kitchens · Download PNG · Open card page
Revision card: CI not laptop prod. Laptop admin deploys skip reviews and leave keys around. Build, synth/validate, staging smoke, then approved prod. OIDC roles + least privilege beat long-lived access keys. Rohan blocks merge until sam validate / cdk diff is green.
Revision card: CI not laptop prod · Download PNG · Open card page
Comparison: AWS SAM vs AWS CDK. AWS SAM: CloudFormation macros + sam CLI; fast for classic serverless. AWS CDK: TypeScript/Python constructs synthesize CFN; best for shared libs.
Comparison: AWS SAM vs AWS CDK · Download PNG · Open card page
Comparison: Serverless Framework vs AWS SAM. Serverless Framework: serverless.yml + rich plugins; multi-cloud history. AWS SAM: AWS-native SAM macros on CFN.
Comparison: Serverless Framework vs AWS SAM · Download PNG · Open card page
Interview card: What is SAM?. AWS-native macros on CloudFormation plus the sam CLI. Great when the team already thinks in templates. MNC: name one local and one deploy command.
Interview card: What is SAM? · Download PNG · Open card page
Interview card: When prefer CDK?. Complex apps needing typed reusable constructs. Synthesizes CloudFormation; CI is source of truth. MNC: how do you catch sneaky IAM widens?
Interview card: When prefer CDK? · Download PNG · Open card page
Interview card: Mixing IaC tools?. Two tools on one stack fight and drift. Prefer one owner tool per domain; migrate deliberately. MNC: describe a migration checklist.
Interview card: Mixing IaC tools? · Download PNG · Open card page
Interview card: Secrets in YAML?. Plaintext in git is a breach waiting to happen. Reference Secrets Manager/SSM; scan CI. MNC: where do auditors look first?
Interview card: Secrets in YAML? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

About this scenario

Maple Leaf Books is a bookselling business in Toronto. Emily Tremblay looks after its IT and cloud work. They count money in CAD and run their AWS resources in the ca-central-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy SAM uses CFN macros — 1

Why: Idea.

What to do: Enter 1 if SAM builds on CloudFormation macros.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy serverless.yml — 1

Why: Idea.

What to do: Enter 1 if Serverless Framework commonly uses serverless.yml.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy CDK synthesizes CFN — 1

Why: Idea.

What to do: Enter 1 if CDK typically synthesizes CloudFormation.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy One owner tool — 1

Why: Idea.

What to do: Enter 1 if one IaC tool should own a given stack.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy CI not laptop prod — 1

Why: Idea.

What to do: Enter 1 if prod deploys should use CI not laptop admin keys.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Pin versions — 1

Why: Idea.

What to do: Enter 1 if pinning CDK/plugin versions aids reproducibility.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Console drift bad — 1

Why: Idea.

What to do: Enter 1 if console clicks cause IaC drift.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Region explicit — 1

Why: Idea.

What to do: Enter 1 if Mumbai apps should set ap-south-1 explicitly.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium No plaintext secrets — 1

Why: Idea.

What to do: Enter 1 if secrets must not sit plaintext in templates.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium sam local approx — 1

Why: Idea.

What to do: Enter 1 if sam local only approximates prod.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Change sets preview — 1

Why: Idea.

What to do: Enter 1 if change sets preview infra before apply.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Mixing tools costly — 1

Why: Idea.

What to do: Enter 1 if mixing IaC tools on one domain is costly.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium SAM Transform line

Why: Shape.

What to do: Include Transform AWS::Serverless-2016-10-31 and a Resources key.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium List stacks read-only

Why: Inventory.

What to do: List CloudFormation stacks

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard OIDC deploy roles — 1

Why: Idea.

What to do: Enter 1 if CI should assume OIDC roles not long-lived keys.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Split huge templates — 1

Why: Idea.

What to do: Enter 1 if huge templates should split nested stacks/constructs.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.