Fan-Out and Fan-In Patterns with SNS, SQS and Step Functions
One school bell rings; every class stands up (fan-out). After sports day, scores from many tracks meet on one board (fan-in). Serverless does the same with SNS, SQS and Step Functions Parallel/Map. This chapter wires the pattern safely — without recursive storms.
What you'll learn in this chapter
- Explain fan-out and fan-in with school stories
- Choose SNS vs EventBridge vs SFN Parallel
- Buffer each subscriber with SQS when needed
- Join results safely (fan-in)
- Link order-fanout project chapter
1. Everyday example: school bell and sports board
Rohan in Pune rings one SNS topic OrderPlaced; inventory, invoice (INR) and analytics each get a copy. Later, three fraud checks must all finish before ship — Step Functions Parallel then join. That join is fan-in.
Hands-on: order fanout project. Messaging depth: SQS/SNS. Orchestration depth: Step Functions.
2. Why fan-out?
Why do we need this?
Calling three Lambdas sync from one handler couples timeouts and permissions. Fan-out lets each consumer scale, fail and retry alone.
What is it?
Fan-out: one signal → many consumers. Fan-in: many branches complete → one next step.
3. Vertical diagrams
4. SNS vs EventBridge vs SFN Parallel
| Tool | Fan-out style | Pick when |
|---|---|---|
| SNS topic | Push to SQS/Lambda/HTTP/SMS | Simple pub/sub |
| EventBridge | Filtered rules to many targets | Rich filters, buses, archive |
| SFN Parallel/Map | Known branches then join | Need fan-in + timeline |
5. How: safe SNS → SQS → Lambda fan-out
How to do it (step by step)
- Create topic shop-order-placed.
- Create three queues + DLQs; subscribe queues to topic.
- Raw message delivery off/on consciously (JSON envelope).
- Event source mapping from each queue to its Lambda.
- IAM: producer Publish; consumers Consume+DLQ.
- Publish one test; confirm three processing paths.
- Alarm on each DLQ depth.
List topic subscriptions
aws sns list-subscriptions-by-topic --topic-arn $TOPIC --region ap-south-1
Meaning: Confirm three SQS subscriptions before load test.
Publish a test JSON
aws sns publish --topic-arn $TOPIC --region ap-south-1 \
--message '{"orderId":"o-42","currency":"INR","total":499}'
Meaning: Watch three queues receive a copy (ApproximateNumberOfMessages).
6. Fan-in patterns
- Step Functions Parallel: fixed branches, automatic join.
- Map state: dynamic array, capped concurrency, then continue.
- DynamoDB counter/condition: advanced; easy to get wrong — prefer SFN.
- Never busy-poll three APIs from a user-facing Lambda without timeout math.
Python: decide buffer or direct
def needs_queue(consumer_slow, spike_expected):
return consumer_slow or spike_expected
print(needs_queue(True, False))
print(needs_queue(False, False))
Output: True / False. Meaning: slow or spiky consumers get SQS.
7. Failure isolation
If invoice Lambda fails, inventory must still succeed. That is why you fan-out through a topic/bus instead of a for-loop of sync invokes. Luis in Mexico City learned this when MXN invoicing outage blocked stock reserve.
8. Lab: paper fan-out + optional SNS lab
Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.
How to do it (step by step)
- Draw OrderPlaced → three consumers with DLQs.
- Mark which consumer needs FIFO vs Standard.
- Optional: create topic+2 queues subscription in sandbox.
- Publish once; verify two receives.
- Delete topic, queues, subscriptions.
Cleanup (stop billing)
- Unsubscribe then delete queues/topic.
- Remove lab Lambdas/log groups.
9. Map state concurrency
Map over 10,000 items with concurrency 1,000 can melt downstream. Set MaxConcurrency; prefer SQS between Map and fragile APIs.
Approximate queue depth
aws sqs get-queue-attributes --queue-url $Q --attribute-names ApproximateNumberOfMessages ApproximateNumberOfMessagesNotVisible --region ap-south-1
Meaning: Depth rising while API healthy → consumer lag, not producer loss.
10. Idempotency under fan-out
SNS/SQS can deliver duplicates. Consumers must treat orderId as idempotent key (DynamoDB conditional put). Kenji in Osaka double-sent JPY invoices until the condition key landed.
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 |
|---|---|
| Sync for-loop fan-out in one Lambda | SNS/EB/SFN Parallel instead. |
| One shared DLQ for all consumers | Per-consumer DLQ. |
| No filter policies — every consumer wakes | SNS filter / EB filter. |
| Fan-in with sleep loops | SFN Parallel/Map. |
| Map concurrency unbounded | Set MaxConcurrency. |
| Raw message surprise parsing bugs | Decide raw delivery; test. |
| FIFO everywhere | FIFO only when order matters. |
| Missing idempotency on consumers | Conditional writes. |
| Publishing huge payloads to SNS | Put blob in S3; publish key. |
| Forgetting subscription IAM on SQS | sqs:SendMessage from SNS principal. |
14. FAQ
Q. SNS or EventBridge?
SNS simple + SMS; EB filters/buses/archive.
Q. Need fan-in without SFN?
Possible with DDB counters — fragile; prefer SFN.
Q. SQS between SNS and Lambda?
Yes for isolation and batching.
Q. Order of consumers?
Not guaranteed on Standard; use FIFO or SFN.
Q. Where is fanout project?
build-order-fanout-with-sns-sqs-lambda-dynamodb.
Q. Poison message?
DLQ after maxReceiveCount; fix then redrive.
15. Interview Q&A (Beginner / Mid / Senior + MNC)
Q. Beginner: fan-out?
One event delivered to many consumers.
Q. Beginner: fan-in?
Many branches join before next step.
Q. Mid: why SQS after SNS?
Buffer, retry isolation, batching.
Q. Mid: Parallel vs Map?
Parallel fixed branches; Map over array.
Q. Senior: blast radius?
Per-consumer IAM, DLQ, concurrency caps.
Q. MNC: duplicate emails?
Idempotent consumer + dedupe table.
16. Tips in English, Marathi and Hindi
Ravindra Bagale's Tip (EN)
Fan-out for independence; fan-in with a real join — not a sleep loop.
Ravindra Bagale's Tip (MR)
Fan-out = independence; fan-in = खरा join — sleep loop नको.
Tip (HI)
Fan-out से स्वतंत्रता; fan-in के लिए असली join — sleep loop नहीं।
Try at home
- List three consumers for one event at work.
- Mark who needs FIFO.
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. Poison and redrive under fan-out
- Each consumer queue has its own DLQ.
- Alarm text names the consumer team.
- Fix code; redrive only that DLQ.
- Never redrive blindly during an outage without a sample inspect.
18. Security notes
- Topic policy: who can Publish.
- Queue policy: allow SNS source ARN only.
- Lambda role: one queue consume, not *.
- Encrypt queues with SSE (SQS managed or KMS).
19. Cost notes
SNS + SQS + Lambda for three consumers costs more than one sync Lambda — you buy isolation. At low volume free tier often covers labs. At Black Friday INR scale, watch SQS request units and Lambda concurrency.
Filter policy example (concept)
# Subscription attribute FilterPolicyJSON
# {"currency":["INR","AED"],"type":["OrderPlaced"]}
Meaning: Consumer wakes only for matching currencies.
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 fan-out and fan-in.
- 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
Amravati Agro Market is a agriculture business in Amravati. Anjali Thakre 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 Fan-out one to many — 1
Why: Shape.
What to do: Enter 1 if fan-out means one signal to many consumers.
- 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 Fan-in many join — 1
Why: Shape.
What to do: Enter 1 if fan-in means many branches join before next step.
- 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 SQS after SNS — 1
Why: Why.
What to do: Enter 1 if SQS after SNS buffers, isolates retries, and batches.
- 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 SFN Parallel join — 1
Why: Tool.
What to do: Enter 1 if Step Functions Parallel fits known branches that must join.
- 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 List SNS topics
Why: CLI.
What to do: List SNS topics
- 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 Fan shapes YAML
Why: Map.
What to do: YAML: fan_out: sns, fan_in: sfn.
- 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 Map for dynamic fan — 1
Why: SFN.
What to do: Enter 1 if Step Functions Map helps dynamic fan-out over a list.
- 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 Map MaxConcurrency — 1
Why: Protect.
What to do: Enter 1 if Map MaxConcurrency protects downstream from stampedes.
- 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 Consumers idempotent — 1
Why: Dupes.
What to do: Enter 1 if duplicate SNS deliveries require idempotent consumers.
- 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 Big payload via S3 — 1
Why: Size.
What to do: Enter 1 if huge payloads should store the blob in S3 and publish the key.
- 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 Per-consumer DLQ — 1
Why: Isolate.
What to do: Enter 1 if per-consumer DLQ keeps invoice failures from poisoning inventory.
- 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 Buffer YAML
Why: Why.
What to do: YAML: after_sns: sqs, reason: isolate.
- 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 FIFO when order matters — 1
Why: Order.
What to do: Enter 1 if FIFO is for when order per group matters.
- 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 Sync for-loop anti — 1
Why: Smell.
What to do: Enter 1 if a sync for-loop of Lambda invokes for fan-out is an anti-pattern.
- 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 Standard for throughput — 1
Why: Tradeoff.
What to do: Enter 1 if Standard SNS/SQS favors max throughput over strict order.
- 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-spd-fan 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.