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.
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?
Calling three Lambdas sync from one handler couples timeouts and permissions. Fan-out lets each consumer scale, fail and retry alone.
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
- Create topic shop-order-placed.
- Create three subscriber queues, each with a redrive policy and a processing DLQ. Subscribe the queues to the topic. In each subscriber queue policy, allow the SNS service to call sqs:SendMessage only from the intended topic ARN. Confirm the subscriptions before testing delivery.
- Raw message delivery off/on consciously (JSON envelope).
- Event source mapping from each queue to its Lambda.
- IAM: the producer needs permission to publish to the topic. Each Lambda execution role needs the SQS receive, delete and attribute permissions for its source queue. Automatic queue redrive is separate from a consumer that explicitly reads or sends to a 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.
- 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
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioAmravati 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 Name one-to-many message delivery
One order event must independently reach inventory, invoices and analytics. What messaging pattern is that?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy Name the join across branches
The workflow can dispatch three parallel checks, but it can ship only after all finish. What is the join pattern called?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy Give each subscriber its own retry buffer
SNS publishes to three consumers. Each needs to queue a backlog and absorb temporary worker outages separately. Which AWS service should sit between the topic and each Lambda worker?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy Run a fixed set of checks concurrently
A Step Functions definition always runs exactly three distinct checks and must wait for them all. Which Step Functions state type represents the fixed branches?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Easy List SNS topics
CLI.
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
Map.
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 Run the same checks for a list
The workflow receives a list of an unknown length. It should run the same branch for every item in that list. Name the Step Functions state type.
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium Limit simultaneous iterations
A Step Functions Map state sends too many requests to the database. Which state setting limits the number of concurrent iterations?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium Prevent repeat invoices from redelivery
The invoice consumer may receive the same order event again. Which processing property ensures a repeated event has the same business result as the first?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium Separate a large object from its event
A message is too large for the queue limit. In the pattern taught here, store the object then publish its reference. Which AWS storage service should hold the object?
- Read the situation and identify what you need to decide.
- Work through the relevant concept or calculation.
- Enter only the requested term or number.
- Check your answer, then read the explanation.
Medium Keep one subscriber’s poison job separate
An invoice message repeatedly fails, while inventory consumes its copies successfully. Where should the invoice source queue send this failed message after its receive threshold?
- Enter the term or setting requested.
- Check your answer, then compare your reasoning with the solution.
Medium Buffer YAML
Why.
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 Choose ordering within a message group
Events for one order must be queued in order, while other orders can use different message groups. What SQS queue type supports this design?
- Enter the term or setting requested.
- Check your answer, then compare your reasoning with the solution.
Hard Remove synchronous coupling between subscribers
One request currently waits for inventory, invoice and analytics Lambda calls in a loop. Which AWS pub/sub service lets it publish one event to multiple independent subscribers?
- Enter the term or setting requested.
- Check your answer, then compare your reasoning with the solution.
Hard Choose a queue when strict ordering is unnecessary
A telemetry worker needs a high-throughput queue and can handle occasional duplicates and best-effort ordering. Which SQS queue type suits this requirement?
- Enter the term or setting requested.
- Check your answer, then compare your reasoning with the solution.
Hard Verify a temporary broadcast topic was removed
The class removed its disposable SNS topic. Which read-only SNS CLI operation lists remaining topics in the test Region?
- Enter the term or setting requested.
- Check your answer, then compare your reasoning with the solution.