Project: Build Order Fan-Out with SNS, SQS, Lambda and DynamoDB (Source Code)
One Swiggy order must notify email and inventory at the same time. SNS fans out to two SQS queues; each queue has its own Lambda writing DynamoDB.
In this chapter
- SNS fan-out to two SQS queues
- Publisher API Lambda
- Two worker Lambdas
- Cleanup topic, queues, functions
1. Everyday example
If email code crashes, inventory should still run. Separate queues isolate failures — that is fan-out.
POST /orders → publisher Lambda → SNS topic → email-queue + inventory-queue → email_worker + inventory_worker → DynamoDB.
Download: order-fanout.zip
2. Lab
A. SNS + SQS + table
Fan-out means sending one event to several independent destinations. SNS is the publisher-facing channel. A subscription connects that channel to one SQS queue. Each queue stores its branch’s copy until its own worker is ready. A single shared queue with two competing workers would let either worker take a message, which does not give both jobs their own copy.
For orderId=lab-17, predict one marker from the email branch and one from the inventory branch. Each marker’s key includes both its purpose and the order ID. If both workers wrote the same key, the later write could replace the earlier marker. The table keys let you see independently which branch completed.
- SNS topic
yourname-orders-topic. - SQS queues
yourname-email-qandyourname-inv-q. Subscribe both to the topic. - DynamoDB
yourname-fanout, PKpkString.
B. Workers + publisher
Use the order ID you sent to line up the evidence. A successful publish gives a response from SNS. Next, check the two worker logs for the same order, then check for the two marker rows. If one worker had no input, follow that branch’s SNS subscription and SQS policy. If the worker logged an error with the matching order ID, follow that branch’s message visibility and dead-letter queue instead.
With raw delivery off, SNS puts its message into an envelope of named fields before SQS receives it. The worker first reads the SQS message body, then reads the SNS Message field inside that body. Keep the queue setting and parser in agreement. A JSON format error at this stage can leave one branch failing even though the same SNS publish reached both queues.
- Deploy email_worker.py and inventory_worker.py with SQS triggers. Env TABLE_NAME.
- Publisher.py with TOPIC_ARN. HTTP API POST /orders.
curl -s -X POST "$API_BASE/orders" -H 'content-type: application/json' \
-d '{"sku":"TEE-RED","qty":1}'
# DynamoDB should show EMAIL#... and INV#... rows
Cleanup
- Delete API, publisher, workers, subscriptions, topic, queues, table, roles.
Common errors and fixes
These are synthetic practice situations. Diagnose the signal before changing a resource; no infrastructure changes are needed to read this guide.
Publish succeeds but one subscriber queue stays empty.
A successful SNS Publish does not prove every subscriber received the message. Check the subscription target and the queue policy that permits SNS SendMessage from this topic. Publishing permission on the caller role is not the queue delivery permission. Compare delivery failures with that specific subscription before changing worker code.
Only one worker handles each order after queues were combined.
Two consumers on one SQS queue compete for work; that is not a copy for each business branch. Fan-out uses separate subscribed queues so email and inventory can each receive the order. Extra consumers on a single branch help share that branch workload, not broadcast every record to every consumer.
One branch overwrites the other branch result.
Both workers share a table in this lab, so their complete item keys must distinguish the business branch. A PutItem using the same key replaces the previous item. Keep the intended EMAIL and INV identities separate and stable for a given order. More worker concurrency does not repair a key design that makes the branches collide.
Practical FAQ: decisions during real work
Why must the parser agree with raw message delivery?
With raw delivery off, the SQS body contains the SNS notification wrapper and its Message contains the published business message. With raw delivery on, SNS metadata is stripped. Changing this subscription option changes the contract seen by the worker. Inspect a synthetic event shape before altering parsing; do not guess based on a missing field.
Can a successful inventory branch cancel email retries?
No. The queues and their event-source processing are independent. Email can be retried even after inventory completes, so each branch needs its own safe repeat handling and failure visibility. Track outcomes by order and branch. A single overall success flag would hide which subscriber still needs attention.
When should a DLQ be investigated?
A DLQ contains work that exhausted the configured delivery or processing path, not successfully completed work. Identify whether the DLQ belongs to SNS subscription delivery or an SQS worker redrive policy; those failures occur at different points. Diagnose the cause and duplicate-side-effect risk before any controlled replay. Do not blindly replay a queue into a live business system.
3. Interview
Q. Why not two publishes from the API Lambda?
SNS subscription list grows without redeploying the API.
Q. SNS to SQS wrapper?
Workers parse Message JSON inside the SQS body.
Q. Failure isolation?
Poison email queue does not block inventory queue.
Q. Filter policies?
SNS can route by message attributes later.
Q. Cleanup?
Topic, queues, Lambdas, table.
Try at home
- Add a third analytics queue.
- Use message attributes for VIP orders.
In short
- Fan-out = SNS to many SQS workers.
- One publish, many subscribers.
- Isolate failures per queue.
- Clean up.
Prove both subscribers processed the order
For one synthetic order ID, expect two DynamoDB rows such as EMAIL#order-id and INVENTORY#order-id. Compare the SNS topic subscriptions, each SQS queue and the two workers. The archive writes markers, not a real email or stock change. Match the publisher, email_worker and inventory_worker file names to their lambda_handler functions.
Interview check Why might one subscriber succeed while the other is still retrying?
Each queue has independent delivery, visibility and redrive. Separate queue metrics and dead-letter queues tell you which branch needs attention, and business writes must be idempotent.
For one synthetic order, separate two failures. If SNS cannot deliver to the inventory queue, an SNS subscription dead-letter queue can capture that undelivered notification after SNS applies its delivery policy. If the inventory queue receives it but the worker keeps failing, the source SQS queue’s redrive policy can move that message to its dead-letter queue. Check the first case at the subscription and the second at the worker and source queue.
Practise this chapter
Interview questions and answers
How would you make an inventory outage independent of email delivery?
I would subscribe two separate queues to the topic and use one worker and redrive policy for each branch. I would log the same order ID across both and use branch-specific completion records. That makes inventory retries visible without forcing the email branch to repeat completed work.
Check your understanding
Choose an answer, then compare your reasoning with the explanation.
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 scenarioHyderabad Biryani Hub is a cloud kitchen business in Hyderabad. Syed Imran looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-2 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 / 12
Easy List functions
See which functions exist in this Region.
List the Lambda functions in ap-south-2.
- 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.
Medium Invoke a function
Invoke runs the function now and saves its answer in a file.
Invoke hydbiryani-orders-fn and save the response to out.json.
- 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.
Medium Trust policy for a Lambda role
The trust policy says WHO may take the role.
Write a trust policy that lets lambda.amazonaws.com assume the role.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Medium Put an item
DynamoDB JSON shows the type of each value: S for string, N for number.
Put an item into hydbiryani-orders with orderId "o-101" (string) and amount 2500 (number).
- 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.
Medium Change timeout and memory
More memory also gives more CPU; timeout stops runaway runs.
Set hydbiryani-orders-fn to timeout 30 seconds and memory 512 MB.
- 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 Connect an SQS queue to Lambda
An event source mapping makes Lambda poll the queue and process messages in batches.
Create an event source mapping from queue arn:aws:sqs:ap-south-2:130300927383:hydbiryani-orders to hydbiryani-orders-fn with batch size 10.
- 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 Create a Lambda function
Lambda needs the code zip, a runtime, a handler name and an execution role.
Create function hydbiryani-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::130300927383:role/lambda-basic, code in function.zip.
- 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 Set environment variables
Keep settings like table names out of the code.
Set the environment variable TABLE=hydbiryani-orders on hydbiryani-orders-fn.
- 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 Invoke with a JSON payload
In CLI v2, raw JSON needs --cli-binary-format raw-in-base64-out.
Invoke hydbiryani-orders-fn with payload {"orderId":"o-101"} (raw JSON) and save the reply in out.json.
- 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 Lambda GB-seconds
Lambda bills memory × time.
1,000,000 invocations, 512 MB memory, 200 ms each. How many GB-seconds?
- 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 Read capacity units
Provisioned tables need the right RCU.
Strongly consistent reads of 6 KB items, 10 reads per second. How many RCUs?
- 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 Let S3 call your function
A resource-based permission is needed before S3 can invoke the function.
Add permission statement s3invoke to hydbiryani-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::hydbiryani-uploads.
- 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.
Revision, comparison and interview 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.