Serverless API Backend Pattern with API Gateway, Lambda and DynamoDB
A food cart takes one order at the window, writes it on a ticket, and the kitchen cooks. A serverless API backend is that window: API Gateway is the counter, Lambda is the cook for one ticket, DynamoDB is the order book. This chapter shows the pattern end-to-end without pasting the whole shortener project again.
What you'll learn in this chapter
- Map counter/cook/book to API Gateway, Lambda, DynamoDB
- Choose HTTP API vs REST API vs Function URL
- Design request → validate → write → respond with status codes
- Add auth and throttle at the edge
- Link shortener and REST API project chapters
1. Everyday example: the food-cart window
Meera in Pune runs a momo cart. Customers pay at the window; they do not walk into the kitchen. Same for APIs: browsers and mobile apps hit HTTPS at API Gateway. Lambda should not be a public TCP socket. DynamoDB holds the durable ticket (orderId, items, INR total).
You already built variants in URL shortener project and REST API project. Here we name the pattern and the design choices those labs used.
2. Why this pattern?
Why do we need this?
Teams expose EC2 public IPs, forget TLS, or put business logic in the gateway. The API backend pattern keeps edge, compute and data in three clear boxes with clear failure modes.
What is it?
Serverless API backend = HTTPS edge (API Gateway or Function URL) + short-lived compute (Lambda) + managed data (often DynamoDB) + IAM between them.
3. Vertical diagram
4. HTTP API vs REST API vs Function URL
| Option | Use when | Watch out |
|---|---|---|
| HTTP API | Most new APIs; cheaper; JWT authorizers | Fewer features than REST API |
| REST API | API keys, usage plans, heavy WAF habits | Higher request price |
| Function URL | Quick demos; single function | DIY routing/auth/throttle |
Ravindra Bagale's Tip
Default for class and new products: HTTP API in ap-south-1 with JWT or IAM. Grow to REST only when you need a REST-only feature.
5. How: request path step by step
How to do it (step by step)
- Define routes and methods on paper (POST /orders, GET /orders/{id}).
- Create DynamoDB table from access patterns (PK orderId).
- Write Lambda: parse event, validate, PutItem/GetItem, return statusCode+headers+body.
- Attach execution role with least privilege on that table.
- Create HTTP API; integrate routes to Lambda; enable CORS if browser.
- Add JWT authorizer (Cognito) or IAM; set throttle burst/rate.
- curl happy path and 4xx path; check CloudWatch Logs.
- Optional: after PutItem publish SNS for email (link contact-form project).
Create a demo HTTP API (name only shown)
aws apigatewayv2 create-api --name meera-momo-api --protocol-type HTTP --region ap-south-1 \
--query '{Id:ApiId,Ep:ApiEndpoint}'
Meaning: You get an invoke URL. Delete the API after the lab.
Wire a route to Lambda (shape)
aws apigatewayv2 create-integration --api-id $API --integration-type AWS_PROXY \
--integration-uri $LAMBDA_ARN --payload-format-version 2.0 --region ap-south-1
Meaning: AWS_PROXY passes the full HTTP event to Lambda.
6. Status codes that teach clients
| Code | Meaning in this pattern | Client should |
|---|---|---|
| 200 | Read OK | Show body |
| 201 | Created sync resource | Store id |
| 202 | Accepted for async work | Poll or wait for webhook |
| 400 | Validation failed | Fix request |
| 401/403 | Auth/authz failed | Re-login / stop |
| 404 | Missing id | Show not found |
| 429 | Throttled | Backoff |
| 500 | Unhandled server error | Retry with jitter; alert you |
7. Worked mini-examples
Python: API Gateway HTTP API 2.0 response
def ok(body, code=200):
import json
return {"statusCode": code, "headers": {"content-type": "application/json"},
"body": json.dumps(body)}
print(ok({"orderId": "o-1"}, 201)["statusCode"])
Output: 201. Meaning: clients key off statusCode, not only JSON.
Node: reject empty body early
exports.handler = async (event) => {
if (!event.body) return {statusCode: 400, body: '{"error":"empty"}'};
return {statusCode: 200, body: event.body};
};
Meaning: fail fast at the edge of your handler before DynamoDB calls.
Invoke URL smoke test shape
curl -sS -X POST "$API_URL/orders" -H 'content-type: application/json' \
-d '{"sku":"MOMO-STEAM","qty":2,"currency":"INR"}'
Meaning: Expect 201 with orderId, or 400 if validation fails.
8. Lab: sketch + optional one-route API
Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.
How to do it (step by step)
- On paper: routes, table keys, status codes for create and get.
- Optional sandbox: one HTTP API, one Lambda, one on-demand table.
- curl POST and GET; save request ids from logs.
- Enable a simple throttle; curl until you see 429 once.
- Delete API, function, table, role.
Cleanup (stop billing)
- Delete HTTP API first, then Lambda, table, IAM role.
- Remove /aws/lambda/* log group if you created it.
9. Auth and multi-tenant notes
Put JWT validation at API Gateway when you can. See Cognito. For SaaS, put tenantId in the token and in the DynamoDB PK — never trust tenantId only from the JSON body.
10. Per-concept: CORS
Browsers block cross-origin POSTs without CORS headers. Configure API Gateway CORS for your web origin; for mobile native apps CORS is irrelevant.
Show route list
aws apigatewayv2 get-routes --api-id $API --region ap-south-1 --query 'Items[].RouteKey'
Meaning: Confirms POST /orders and GET /orders/{id} exist.
11. 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.
12. 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.
13. Common errors and fixes
Each row is a real mistake students and juniors hit. Read the fix before you panic.
| Error / symptom | Fix |
|---|---|
| Lambda public IP instead of Gateway | Put API Gateway or Function URL in front. |
| REST API by default for a hello | Prefer HTTP API unless you need REST-only features. |
| Returning 200 for create | Use 201 (or 202 if async). |
| IAM * on DynamoDB | Resource-specific ARN + actions. |
| CORS * with credentials | Explicit origin; avoid * with cookies. |
| Business rules only in Gateway mapping | Keep rules in Lambda/tests. |
| No throttle | Set route or stage rate limits. |
| Trust tenantId from body only | Bind to JWT claim. |
| Giant monolith handler | Split by route groups. |
| Forgetting cleanup of HTTP APIs | Delete lab APIs the same day. |
14. FAQ
Q. HTTP API enough for production?
Yes for many apps; add WAF/auth as needed.
Q. Where does Cognito sit?
Authorizer on routes; not inside every line of code.
Q. Function URL vs HTTP API?
URL for single-function demos; HTTP API for routing/auth.
Q. Can I use RDS?
Yes via VPC; cold start+ENI cost — prefer DynamoDB when fits.
Q. How to version APIs?
Stage variables, path prefix /v1, or separate APIs.
Q. Link to shortener lab?
Yes — same pattern, different schema.
15. Interview Q&A (Beginner / Mid / Senior + MNC)
Q. Beginner: three boxes of API backend?
Gateway, Lambda, data store.
Q. Beginner: why not public Lambda URL always?
No routing/throttle/auth features of Gateway.
Q. Mid: 201 vs 202?
201 created; 202 accepted for later processing.
Q. Mid: least privilege for PutItem?
dynamodb:PutItem on table ARN only.
Q. Senior: multi-tenant isolation?
tenantId in PK + JWT claim + optional IAM condition keys.
Q. MNC: edge auth vs app auth?
Prefer JWT at Gateway; app still enforces object-level authz.
16. Tips in English, Marathi and Hindi
Ravindra Bagale's Tip (EN)
Keep the window, the cook, and the order book separate — Gateway, Lambda, DynamoDB.
Ravindra Bagale's Tip (MR)
खिडकी, cook आणि order book वेगळे ठेवा — Gateway, Lambda, DynamoDB.
Tip (HI)
खिड़की, रसोइया और ऑर्डर बुक अलग रखें — Gateway, Lambda, DynamoDB.
Try at home
- Sketch POST/GET for your side project API.
- List status codes you will return.
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.
17. Payload and pagination habits
- Keep request bodies small; put big files in S3 and pass keys.
- Return nextToken for lists; never load unbounded Query into memory.
- Validate content-type; reject unexpected XML if you speak JSON.
- Idempotency-Key header on POSTs that create money rows.
18. Blue/green style with aliases
Publish Lambda versions; point alias live to vN; shift 10% traffic with weighted alias before 100%. API Gateway integration uses the alias ARN, not $LATEST.
Publish version (shape)
aws lambda publish-version --function-name meera-orders --region ap-south-1 --query Version
Meaning: Pin integrations to a version/alias for rollback.
19. Contract tests
Before merging, curl OpenAPI examples against a stage. Assert status codes and required JSON fields. Contract breaks should fail CI, not customers in AED/INR checkout.
20. 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.
21. 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.
22. 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.
23. 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 |
24. Practice: explain out loud
- 60 seconds: everyday story for serverless API backend.
- 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.
25. 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.
26. 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.
27. 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 |
28. 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.
29. 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.
30. 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.
31. 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.
32. 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.
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
Vidarbha Cotton Mills is a textiles business in Nagpur. Ganesh Wankhede looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-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 API Gateway is window — 1
Why: Metaphor.
What to do: Enter 1 if API Gateway is the window/counter in the food-cart metaphor.
- 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 Prefer HTTP API — 1
Why: Default.
What to do: Enter 1 if HTTP API is the preferred default for most new APIs here.
- 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 HTTP 202 accepted — 1
Why: Codes.
What to do: Enter 1 if HTTP 202 means accepted for processing not finished.
- 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 HTTP 201 created — 1
Why: Codes.
What to do: Enter 1 if HTTP 201 means resource created synchronously.
- 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 Get API by name
Why: CLI.
What to do: Get REST API named FoodCart
- 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.
Easy Stack YAML
Why: Parts.
What to do: YAML: edge: apigw, compute: lambda, store: dynamodb.
- 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.
Easy Stages separate env — 1
Why: Ops.
What to do: Enter 1 if API stages help separate environments.
- 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 AWS_PROXY full event — 1
Why: Integration.
What to do: Enter 1 if AWS_PROXY passes the full HTTP event to Lambda.
- 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 Least privilege PutItem — 1
Why: Scope.
What to do: Enter 1 if PutItem should allow dynamodb:PutItem on that table ARN.
- 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 JWT at authorizer — 1
Why: Auth.
What to do: Enter 1 if JWT validation preferably sits at API Gateway authorizer.
- 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 Function URL for demos — 1
Why: Scope.
What to do: Enter 1 if Function URL fits quick single-function demos.
- 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 Status codes YAML
Why: Map.
What to do: YAML: accepted: 202, created: 201.
- 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.
Hard CORS for browsers — 1
Why: Web.
What to do: Enter 1 if CORS mainly matters for browsers making cross-origin calls.
- 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 tenantId in JWT+PK — 1
Why: SaaS.
What to do: Enter 1 if multi-tenant SaaS puts tenantId in JWT claim and DynamoDB PK.
- 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 Body alone not enough — 1
Why: Anti.
What to do: Enter 1 if tenantId in JSON body alone is not enough for tenancy.
- 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 Delete lab same day — 1
Why: Hygiene.
What to do: Enter 1 if lab-spb-api should be deleted same day.
- 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.