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

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

Client -> API Gateway -> Lambda -> DynamoDBOptional: Cognito/JWT at gateway; SNS after write
Do not skip IAM between Lambda and table
Client (web / mobile) API Gateway HTTP APIJWT/IAM auth, throttle, routes Lambda handlerValidate, map status codes DynamoDBPK design from access patterns Optional: SNS / EventBridge after write
API backend pattern — edge, compute, data.

4. HTTP API vs REST API vs Function URL

OptionUse whenWatch out
HTTP APIMost new APIs; cheaper; JWT authorizersFewer features than REST API
REST APIAPI keys, usage plans, heavy WAF habitsHigher request price
Function URLQuick demos; single functionDIY 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)

  1. Define routes and methods on paper (POST /orders, GET /orders/{id}).
  2. Create DynamoDB table from access patterns (PK orderId).
  3. Write Lambda: parse event, validate, PutItem/GetItem, return statusCode+headers+body.
  4. Attach execution role with least privilege on that table.
  5. Create HTTP API; integrate routes to Lambda; enable CORS if browser.
  6. Add JWT authorizer (Cognito) or IAM; set throttle burst/rate.
  7. curl happy path and 4xx path; check CloudWatch Logs.
  8. 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

CodeMeaning in this patternClient should
200Read OKShow body
201Created sync resourceStore id
202Accepted for async workPoll or wait for webhook
400Validation failedFix request
401/403Auth/authz failedRe-login / stop
404Missing idShow not found
429ThrottledBackoff
500Unhandled server errorRetry 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)

  1. On paper: routes, table keys, status codes for create and get.
  2. Optional sandbox: one HTTP API, one Lambda, one on-demand table.
  3. curl POST and GET; save request ids from logs.
  4. Enable a simple throttle; curl until you see 429 once.
  5. Delete API, function, table, role.

Cleanup (stop billing)

  1. Delete HTTP API first, then Lambda, table, IAM role.
  2. 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

  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.

13. Common errors and fixes

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

Error / symptomFix
Lambda public IP instead of GatewayPut API Gateway or Function URL in front.
REST API by default for a helloPrefer HTTP API unless you need REST-only features.
Returning 200 for createUse 201 (or 202 if async).
IAM * on DynamoDBResource-specific ARN + actions.
CORS * with credentialsExplicit origin; avoid * with cookies.
Business rules only in Gateway mappingKeep rules in Lambda/tests.
No throttleSet route or stage rate limits.
Trust tenantId from body onlyBind to JWT claim.
Giant monolith handlerSplit by route groups.
Forgetting cleanup of HTTP APIsDelete 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

  1. Sketch POST/GET for your side project API.
  2. List status codes you will return.

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.

17. Payload and pagination habits

  1. Keep request bodies small; put big files in S3 and pass keys.
  2. Return nextToken for lists; never load unbounded Query into memory.
  3. Validate content-type; reject unexpected XML if you speak JSON.
  4. 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

  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.

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)

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

24. Practice: explain out loud

  1. 60 seconds: everyday story for serverless API backend.
  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.

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.

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

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.

  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.

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)

  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.

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.

Revision card: API + Lambda + DynamoDB. Skipping the edge layer leaves auth and throttling messy. API Gateway (HTTP API) → Lambda → DynamoDB is the default backend shape. Create HTTP API → Lambda proxy → PutItem → return 201 or 202. Sara Patel ships food-cart orders on this three-layer stack.
Revision card: API + Lambda + DynamoDB · Download PNG · Open card page
Revision card: 201 vs 202. Always returning 200 hides whether work finished or was queued. 201 = created sync; 202 = accepted for async processing. Sync create → 201; queue accepted → 202 + Location/id. Omar Hassan teaches status codes before fancy frameworks.
Revision card: 201 vs 202 · Download PNG · Open card page
Comparison: HTTP API vs REST API. HTTP API: Cheaper, simpler JWT/Lambda proxy for most new APIs. REST API: Usage plans, API keys, richer legacy features when required.
Comparison: HTTP API vs REST API · Download PNG · Open card page
Comparison: HTTP 201 vs HTTP 202. HTTP 201: Resource created in this request. HTTP 202: Accepted for processing; not finished yet.
Comparison: HTTP 201 vs HTTP 202 · Download PNG · Open card page
Interview card: HTTP API default. REST API by habit adds cost and knobs you may not need. Prefer HTTP API for most new Lambda backends; REST when you need its features. MNC: two reasons to pick HTTP API over REST for a new service.
Interview card: HTTP API default · Download PNG · Open card page
Interview card: JWT at edge. Validating JWT only in every Lambda duplicates work and misses early reject. Validate at API Gateway JWT/Lambda authorizer; pass claims to function. MNC: where does tenantId live — body alone or JWT+PK?
Interview card: JWT at edge · Download PNG · Open card page
Interview card: AWS_PROXY event. Mapping templates hide the real request shape from juniors. AWS_PROXY passes full HTTP event; parse path/method/body in code. MNC: show where query params land in the proxy event.
Interview card: AWS_PROXY event · Download PNG · Open card page
Interview card: Least-privilege PutItem. dynamodb:* on * fails every security interview. Allow dynamodb:PutItem on table ARN (+ index if needed) only. MNC: write the Resource ARN pattern for one table.
Interview card: Least-privilege PutItem · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

About this scenario

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.

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 Prefer HTTP API — 1

Why: Default.

What to do: Enter 1 if HTTP API is the preferred default for most new APIs here.

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 HTTP 202 accepted — 1

Why: Codes.

What to do: Enter 1 if HTTP 202 means accepted for processing not finished.

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 HTTP 201 created — 1

Why: Codes.

What to do: Enter 1 if HTTP 201 means resource created synchronously.

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 Get API by name

Why: CLI.

What to do: Get REST API named FoodCart

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.

Easy Stack YAML

Why: Parts.

What to do: YAML: edge: apigw, compute: lambda, store: dynamodb.

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.

Easy Stages separate env — 1

Why: Ops.

What to do: Enter 1 if API stages help separate environments.

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 AWS_PROXY full event — 1

Why: Integration.

What to do: Enter 1 if AWS_PROXY passes the full HTTP event to Lambda.

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 Least privilege PutItem — 1

Why: Scope.

What to do: Enter 1 if PutItem should allow dynamodb:PutItem on that table ARN.

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 JWT at authorizer — 1

Why: Auth.

What to do: Enter 1 if JWT validation preferably sits at API Gateway authorizer.

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 Function URL for demos — 1

Why: Scope.

What to do: Enter 1 if Function URL fits quick single-function demos.

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 Status codes YAML

Why: Map.

What to do: YAML: accepted: 202, created: 201.

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.

Hard CORS for browsers — 1

Why: Web.

What to do: Enter 1 if CORS mainly matters for browsers making cross-origin calls.

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 tenantId in JWT+PK — 1

Why: SaaS.

What to do: Enter 1 if multi-tenant SaaS puts tenantId in JWT claim and DynamoDB PK.

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 Body alone not enough — 1

Why: Anti.

What to do: Enter 1 if tenantId in JSON body alone is not enough for tenancy.

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 Delete lab same day — 1

Why: Hygiene.

What to do: Enter 1 if lab-spb-api should be deleted same day.

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.