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
4. How: decision table
How to do it (step by step)
| Lens | SAM | Serverless Framework | CDK |
|---|---|---|---|
| Learning curve | Low if YAML ok | Medium + plugins | Higher; code skills |
| AWS-native fit | Excellent | Good; extras via plugins | Excellent via L2/L3 |
| Local API | sam local start-api | serverless-offline plugin | Unit test constructs; local limited |
| Multi-cloud story | AWS first | Historically broader | AWS-first |
| Best when | Team already CFN/SAM | Need rich plugin ecosystem | Complex 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)
- List stacks in ap-south-1; note which look SAM/CDK named.
- Open the linked CDK chapter; skim construct idea.
- Write 5 lines: which tool your team would pick and why.
- sam validate on a sample template if you have one.
Cleanup (stop billing)
- Do not leave experimental stacks.
- 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
- Confirm region (ap-south-1 vs us-east-1 for CloudFront/ACM quirks).
- Check CloudWatch Logs for the function name and request id.
- Verify IAM execution role allows the API you call.
- For async: check DLQ depth and SQS age of oldest message.
- For APIs: curl -v and compare status, CORS headers, body.
- For workflows: open Step Functions execution event history.
- Re-read the linked deep chapter before reinventing a service.
- 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 / symptom | Fix |
|---|---|
| Two tools fight over one stack | One owner tool per stack; migrate deliberately. |
| Plugins abandon you | Prefer AWS-native path for core resources. |
| Laptop-only deploy | Move to CI with approval gates. |
| Huge template no modules | Split nested stacks / CDK constructs. |
| Drift from console clicks | Re-import or stop clicking; IaC only. |
| Wrong region in samconfig | Set ap-south-1 explicitly. |
| CDK synth differs per machine | Lock Node/Python; CI is source of truth. |
| Secrets in git | Use dynamic refs; scan CI. |
| sam local not equal prod VPC | Document 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
- Name your team's IaC tool in one sentence.
- List stacks in ap-south-1.
In short
- Start from a real story, then name the AWS services.
- Link existing chapters — do not copy their labs.
- Design for failure: retries, DLQ, idempotency, rollback.
- Measure before you buy provisioned concurrency or multi-region.
16. Architecture decision checklist
- Write the user journey in five bullets with no AWS names.
- Mark each step sync (user waits) or async.
- Name failure mode: retry, DLQ, compensate, or alert-only.
- Name the idempotency key for every write.
- Pick data store from access patterns (link DynamoDB modeling).
- Estimate monthly cost at 1x and 10x traffic (USD and INR).
- Confirm account concurrency and service quotas in ap-south-1.
- Decide auth: Cognito, IAM, Lambda authorizer, or none.
- Name on-call and which CloudWatch alarm pages them.
- Link the deep chapter you will not rewrite.
- 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)
| Term | Meaning |
|---|---|
| Cold start | First invoke pays init; later invokes reuse the env |
| Idempotency | Same request twice → same effect |
| DLQ | Dead-letter queue for failed messages |
| Choreography | Services react to events; no central conductor |
| Orchestration | Central workflow (Step Functions) directs steps |
| Fan-out | One event → many consumers |
| Fan-in | Many branches join before next step |
| Strangler fig | Peel routes from monolith gradually |
| Saga | Distributed tx via steps + compensations |
| Provisioned concurrency | Keep N envs warm; you pay for ready capacity |
20. Practice: explain out loud
- 60 seconds: everyday story for serverless IaC tools.
- 60 seconds: sync vs async with a checkout example.
- 60 seconds: when you refuse Lambda.
- 60 seconds: DLQ + idempotency in one breath.
- 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.
22. How this chapter links others
- Compute depth: Lambda.
- HTTP edge: API Gateway.
- Data modeling: DynamoDB.
- Messaging: SQS/SNS.
- Events: EventBridge.
- Workflows: Step Functions.
- Project chapters (build-*): worked assemblies — link, do not paste.
23. Myths to drop
| Myth | Reality |
|---|---|
| Serverless means zero servers | Servers exist; you do not manage them |
| Always cheaper than EC2 | Steady high load can favor EC2/Savings Plans |
| No Ops needed | You own IAM, data, alarms, cost, incidents |
| One Lambda per app is fine | Bounded contexts scale better |
| Queues are optional decoration | Queues 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.
- Write two SLOs: money-correct and notify-delivered.
- Retries on money path: bounded + idempotent.
- Retries on notify path: best-effort + DLQ.
- 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)
- Imagine tomorrow headline: double charge in AED. What broke?
- Imagine DLQ depth 50,000 after a bad deploy. How do you drain?
- Imagine Cognito outage. Do APIs fail closed or serve read-only?
- 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)
- Three microservices share auth and table grants.
- YAML copy-paste drifts.
- CDK construct library centralizes IAM.
- 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.








More cards: Ravi Sir's Cards.
Practice Tasks
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.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy serverless.yml — 1
Why: Idea.
What to do: Enter 1 if Serverless Framework commonly uses serverless.yml.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy CDK synthesizes CFN — 1
Why: Idea.
What to do: Enter 1 if CDK typically synthesizes CloudFormation.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy One owner tool — 1
Why: Idea.
What to do: Enter 1 if one IaC tool should own a given stack.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- 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.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy Pin versions — 1
Why: Idea.
What to do: Enter 1 if pinning CDK/plugin versions aids reproducibility.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy Console drift bad — 1
Why: Idea.
What to do: Enter 1 if console clicks cause IaC drift.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Easy Region explicit — 1
Why: Idea.
What to do: Enter 1 if Mumbai apps should set ap-south-1 explicitly.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium No plaintext secrets — 1
Why: Idea.
What to do: Enter 1 if secrets must not sit plaintext in templates.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium sam local approx — 1
Why: Idea.
What to do: Enter 1 if sam local only approximates prod.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium Change sets preview — 1
Why: Idea.
What to do: Enter 1 if change sets preview infra before apply.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium Mixing tools costly — 1
Why: Idea.
What to do: Enter 1 if mixing IaC tools on one domain is costly.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Medium SAM Transform line
Why: Shape.
What to do: Include Transform AWS::Serverless-2016-10-31 and a Resources key.
- Start from the top-level keys the task names.
- Indent child keys with 2 spaces (no tabs).
- Fill in each property with the value from the task.
- Click Check answer. Key order does not matter.
Medium List stacks read-only
Why: Inventory.
What to do: List CloudFormation stacks
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- 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.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Hard Split huge templates — 1
Why: Idea.
What to do: Enter 1 if huge templates should split nested stacks/constructs.
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.