AWS from zero · Part 4: Automation and serverless · Lesson 23 of 38 · about 55 minutes

SQS, SNS and EventBridge

Juniper & Rye stops making customers wait while the kitchen works. The shop announces each order on an EventBridge bus; rules send every order to an SNS topic and big ones to the manager; the topic copies orders to the kitchen's queue and members' orders to the loyalty queue; and a Lambda baker works through the kitchen queue, setting aside the one order it can't make. Standard queues didn't keep order, counts were approximate, and the failed order took three tries and two minutes to be set aside. Under 1 cent.

By the end you'll know

  • Why systems pass messages instead of calling each other directly
  • What SQS, SNS and EventBridge each do, and when to pick which
  • How a queue hides a message while it's being worked on, and what a dead-letter queue is for
  • How one message reaches many places with SNS, and how filters narrow that down
  • How EventBridge rules route events by their contents
  • How Lambda works through a queue, and how one bad message is kept from blocking the rest

Before you start

  • You need: the juniper-rye profile, signed in, and Lesson 20's virtual environment. Lesson 21 covers the Lambda function's role and logs.
  • The script: events-lab.py from the practice folder's lesson-23. Everything it creates is named jr-lesson23-* and tagged lesson=23, and its delete step removes it.
  • How the script talks to AWS: only through boto3, as in Lessons 20 to 22.
  • To see every call the script makes that changes something, put SHOW=1 in front of any step. The "By hand" section has the same lab as AWS CLI commands.
  • Where you run things: your own machine, labeled (Your machine).
  • Every output below is from real runs on November 14, 2026.

A message that always fails can bill forever

Without a dead-letter queue, a message your code can't handle goes back on the queue and is tried again, and again, until it expires, up to 14 days later. Each try is a Lambda run and a few SQS requests. Give every queue a dead-letter queue with a small maximum number of tries, as the lab does, and an alarm on the dead-letter queue's length.

The short version

  • SQS is a queue: one message, one worker, and it waits until someone takes it. Workers delete what they finish; what they don't comes back.
  • SNS is a broadcast: one message, copied to every subscriber at once, optionally filtered.
  • EventBridge is a router: events go to a bus, and rules match their contents and send them on.
  • Standard queues don't keep order and can deliver a message twice, so workers must be safe to run twice.
  • A dead-letter queue catches messages that fail too often, so one bad order can't block or bill forever.

What this lesson costs

PartCost, in us-east-2
SQS requests$0.40 per million, after 1 million free a month
SNS publishes$0.50 per million, after 1 million free a month; delivering to SQS is free
EventBridge custom events$1.00 per million, no free allowance
The worker's Lambda runsInside Lambda's free allowance
This lessonA few hundred requests and about 10 events: under 1 cent

The free allowances apply on the free plan too.

Why pass messages?

In Lesson 22, placing an order meant one HTTP request that ran the function, which saved the order, and only then answered the customer. Fine for one step. But a real order sets off several: the kitchen bakes it, the loyalty scheme adds points, the manager hears about big ones. If the website called each in turn, the customer would wait for all of them, and if the loyalty system was down, the order would fail.

Messages fix both. The shop says "order placed" once and answers the customer straight away. Everything that cares about orders hears about it and does its part in its own time. If the kitchen is slow, orders wait in its queue; if the loyalty system is down, its messages wait until it's back. The parts are decoupled: none of them needs to know the others exist, or be up at the same moment.

The shop puts each order on a board (EventBridge), and staff copy the ones meant for them. A runner takes every order and shouts it to the kitchen and the loyalty desk (SNS). The kitchen keeps a spike of order slips (SQS): a baker pulls one off, bakes it, and throws the slip away. If the baker drops a slip half-made, it goes back on the spike. A slip that keeps coming back goes in a box marked "can't make these" (the dead-letter queue), so the bakers can get on.
How an order moves through the labThe shop puts an OrderPlaced event on the event bus. The every-order rule sends it to the SNS topic; the big-orders rule also sends orders of 10 or more to the manager queue. The topic copies each order to the kitchen queue, and orders with member=yes to the loyalty queue. The baker Lambda function takes orders from the kitchen queue; an order that fails three times moves to the dead-letter queue.The shopputs OrderPlacedEvent busEventBridgetwo rulesevery order10 or moreTopicSNSManager queueSQSallmember=yesKitchen queueSQSLoyalty queueSQSBakerLambda3 failuresDead-letterqueue, SQSThe shop sends one event. It doesn't know who's listening, and never waits for them.
One event from the shop reaches four places, chosen by rules and filters, not by the shop.
SQSSNSEventBridge
IsA queueA topic that broadcastsAn event bus with rules
A message goes toOne workerEvery subscriber, at onceEvery rule that matches it
If nobody's thereIt waits, up to 14 daysIt's gone, unless a subscriber is a queueIt's gone, unless archived
Chooses byNothing: first worker to askOptional filter per subscriptionRules matching any part of the event
Use it forWork to be done, at the worker's paceFanning one message out fastRouting events between systems, including AWS's own

They're used together, as in the lab: EventBridge to route, SNS to fan out, SQS to hold work until a worker takes it.

Is it allowed, and what does it cost?

(Your machine)

BASH
cd ~/Apps/aws-practice/lesson-23
source ../lesson-20/.venv/bin/activate
python events-lab.py fence
OUTPUT
== Is this allowed in us-east-2?
  SQS          allowed
  SNS          allowed
  EventBridge  allowed
  Lambda       allowed
  IAM roles    allowed
== What they cost, in us-east-2
  SQS, a request               $0.40 per million
  SNS, a publish               $0.50 per million
  EventBridge, a custom event  $1.00 per million
  free every month, on the free plan too: 1 million SQS requests and 1 million SNS publishes;
  SNS deliveries to SQS queues are free; EventBridge custom events have no free allowance
  this lab: a few hundred requests and about 10 events: under 1 cent

An SQS request is any call, including a receive that comes back empty, which is why long polling, later in the lesson, matters for cost.

Building the plumbing

In the console: SQS > Create queue; SNS > Topics > Create topic, then Create subscription; EventBridge > Event buses > Create event bus, then Rules > Create rule.

BASH
python events-lab.py build
OUTPUT
== Queues
  jr-lesson23-kitchen: hides a taken message for 10 s; after 3 failed tries, moves it to jr-lesson23-kitchen-dlq
  jr-lesson23-loyalty, jr-lesson23-manager: plain queues, messages kept 1 day
== The SNS topic, and who's subscribed
  jr-lesson23-kitchen    <- every message, as sent (raw)
  jr-lesson23-loyalty    <- only messages with the attribute member=yes, wrapped in SNS's envelope
== The event bus, and its rules
  jr-lesson23-every-order on jr-lesson23-bakery
     matches {"source": ["juniperandrye.shop"], "detail-type": ["OrderPlaced"]}
     sends to the topic
  jr-lesson23-big-orders
     matches {"source": ["juniperandrye.shop"], "detail-type": ["OrderPlaced"], "detail": {"qty": [{"numeric": [">=", 10]}]}}
     sends to jr-lesson23-manager
== Who may send to what (resource policies)
  topic: you, and the every-order rule, may publish
  jr-lesson23-kitchen   : only SNS may send, and only from the topic
  jr-lesson23-loyalty   : only SNS may send, and only from the topic
  jr-lesson23-manager   : only EventBridge may send, and only from the big-orders rule
== The worker, jr-lesson23-baker: may read and delete from jr-lesson23-kitchen, and nothing else; not connected yet

Every arrow in the diagram needed a resource policy on the thing it points at. SNS can't put messages in a queue, and EventBridge can't publish to a topic or a queue, until that topic or queue allows it. Each policy here allows one service, and only from one source, with a condition on aws:SourceArn:

JSON
{"Effect": "Allow", "Principal": {"Service": "sns.amazonaws.com"}, "Action": "sqs:SendMessage",
 "Resource": "arn:aws:sqs:us-east-2:111122223333:jr-lesson23-kitchen",
 "Condition": {"ArnEquals": {"aws:SourceArn": "arn:aws:sns:us-east-2:111122223333:jr-lesson23-new-orders"}}}

Without the condition, any SNS topic in any account could fill the kitchen queue. Missing policies are the most common reason messages silently fail to arrive: the sender gets no error, and nothing appears.

A queue, by hand

BASH
python events-lab.py queue
OUTPUT
== Three orders sent to jr-lesson23-kitchen, in order: 3001, 3002, 3003
  each send returns a message ID, like bdc40ab4-120b-4247-af33-41fd9a4ca880
== Take one (receive_message), and don't delete it
  got {"order": 3003, "item": "croissant"}, received 1 time(s)
  the queue's counts, straight away and 5 seconds later (they're approximate):
  jr-lesson23-kitchen    2 waiting, 1 in flight
  jr-lesson23-kitchen    2 waiting, 1 in flight
== Take the others, and delete them
  got 2 in 2 receive call(s), asking for up to 10 each time: {"order": 3001, "item": "sourdough"}, {"order": 3002, "item": "rye"}
  the order taken first never appeared: it's hidden for the 10-second visibility timeout
== Wait until the hidden one comes back
  back: {"order": 3003, "item": "croissant"}, received 2 time(s)
  deleted with delete_message and this receipt's handle: now it's done
== An order nobody can make: taken, never deleted, hidden 2 seconds each time
  try 1: got it, received 1 time(s), and failed
  try 2: got it, received 2 time(s), and failed
  try 3: got it, received 3 time(s), and failed
== The 4th time anything asks for it, SQS moves it to the dead-letter queue instead
  asking jr-lesson23-kitchen again: not there
  in jr-lesson23-kitchen-dlq: {"order": 3004, "item": "burnt toast"}, its receive count now 4
  (deleted from the dead-letter queue, so it doesn't mix with the worker step)

Orders went in as 3001, 3002, 3003, and the first one out was 3003. A standard queue is spread over many servers for speed, so it makes no promise about order, and it can occasionally deliver the same message twice. In an earlier run, 3002 came out first. A FIFO (first in, first out) queue keeps order and removes duplicates, at a lower maximum speed; its name must end in .fifo.

Taking a message doesn't remove it; it hides it. For the visibility timeout, 10 seconds here, nobody else can take it, so two workers don't bake the same order. If the worker finishes, it deletes the message. If the worker crashes and never deletes it, the message comes back, as 3003 did, with its receive count up by one. That's how SQS makes sure every message is worked on at least once, even when workers fail.

SettingDoesDefaultLab
Visibility timeoutHow long a taken message stays hidden30 seconds10 seconds
Message retentionHow long an untaken message is kept, up to 14 days4 days1 day
Redrive policyThe dead-letter queue, and how many receives before a message moves thereNone3 receives
Receive wait timeLong polling: how long a receive waits for a message to arrive before answering empty0 seconds2 seconds, per call

The counts are approximate, and one receive doesn't see everything. "Take the others" asked for up to 10 and needed 2 calls to get 2 messages. In the first run of this step, the counts didn't change at all straight after a message was taken. SQS answers each receive from a sample of its servers; long polling, WaitTimeSeconds, waits and asks more of them, and saves money on empty answers. Never treat one empty receive as "the queue is empty".

The burnt toast was taken 3 times, and the 4th request moved it to the dead-letter queue instead of handing it out. A dead-letter queue is an ordinary queue named in the redrive policy. Messages there wait for a person to look at them, and once the bug is fixed, the console's Start DLQ redrive sends them back to the original queue.

One message, many queues

BASH
python events-lab.py fanout
OUTPUT
== Two orders published to the topic: one from a member, one not
  order 4001, member=yes
  order 4002, member=no
== What each queue got
  jr-lesson23-kitchen: 2 message(s)
    as sent: {"order": 4002, "item": "rye", "member": "no"}
    as sent: {"order": 4001, "item": "rye", "member": "yes"}
  jr-lesson23-loyalty: 1 message(s)
    wrapped by SNS: keys Message, MessageAttributes, MessageId, Signature, SignatureVersion, SigningCertURL, ...
    Message: {"order": 4001, "item": "rye", "member": "yes"}

Two publishes, three deliveries. The kitchen got both orders; the loyalty queue got only the member's, because its subscription has a filter policy, {"member": ["yes"]}, checked against each message's attributes. Filtering in SNS means the loyalty system never sees, or pays to process, messages it would throw away.

The two queues got the same order in two shapes. The kitchen's subscription has raw message delivery on, so it got exactly what was published. The loyalty queue got SNS's envelope: a JSON wrapper with the original in Message, plus the topic, a timestamp and a signature that proves SNS sent it. Raw is simpler for queues you own; the envelope helps when the receiver needs to check where a message came from.

SubscriberUse it for
SQS queueWork that must not be lost: the queue holds it until a worker is ready
Lambda functionShort work that can start straight away
HTTPS endpointAnother system's web address
Email, SMS, mobile pushPeople. The address or number must confirm before it receives anything.
Amazon Data FirehoseStreaming copies into storage, like S3

SNS doesn't store messages. A subscriber that's down misses them, except a queue, which is why "SNS to SQS" is the classic fan-out: SNS for speed, SQS for safety.

Routing events by their contents

BASH
python events-lab.py events
OUTPUT
== Three orders put on the jr-lesson23-bakery bus
  sent 4 (the last from source someone.else), failed: 0
== Where they went
  jr-lesson23-kitchen: 3
    order 5001, sourdough x2  (source juniperandrye.shop, detail-type OrderPlaced)
    order 5002, croissant x24  (source juniperandrye.shop, detail-type OrderPlaced)
    order 5003, rye x1  (source juniperandrye.shop, detail-type OrderPlaced)
  jr-lesson23-manager: 1
    order 5002, croissant x24  (source juniperandrye.shop, detail-type OrderPlaced)
  jr-lesson23-loyalty: 0
== One event, as the kitchen received it: EventBridge's envelope, with your detail inside
  keys: version, id, detail-type, source, account, time, region, resources, detail
  order 5004 matched no rule (wrong source), so EventBridge dropped it, without an error

The shop sends events with put_events, saying where they came from and what kind they are, with the order itself as detail:

PYTHON
ev.put_events(Entries=[{"EventBusName": "jr-lesson23-bakery", "Source": "juniperandrye.shop",
                        "DetailType": "OrderPlaced", "Detail": json.dumps({"order": 5002, "item": "croissant", "qty": 24})}])

Each rule is a pattern, and an event goes to every rule it matches. Every order matched the every-order rule and went to the topic, then on to the kitchen. Order 5002, for 24 croissants, also matched the big-orders rule, whose pattern looks inside detail for qty of 10 or more, so the manager heard about it too. The shop didn't decide any of that; the rules did, and new rules can be added without touching the shop.

Order 5004, from someone.else, matched no rule and was dropped, with no error. put_events reported 0 failed: the bus accepted it, and nothing wanted it. The loyalty queue got nothing either: its filter looks at SNS message attributes, which events arriving through EventBridge don't have. Rules and filters fail quietly, so test them with real events, as the lab does, and check the rule's MatchedEvents and FailedInvocations metrics in CloudWatch.

FeatureDoes
Default busReceives events from AWS services in your account: an EC2 instance stopping, a file landing in S3, a CodePipeline failing
Custom busYour own events, kept apart from AWS's, like the bakery bus
Archive and replayKeeps a bus's events, and sends them again later, for recovery or testing
EventBridge SchedulerRuns a target on a schedule, like cron; Lesson 26 uses it
EventBridge PipesConnects one source, like a queue, to one target, with filtering in between, without code

A worker that keeps up

In the console: the function > Add trigger > SQS, with the kitchen queue, batch size 5, and Report batch item failures on.

BASH
python events-lab.py worker
OUTPUT
== Connecting jr-lesson23-baker to jr-lesson23-kitchen: batches of up to 5, reporting failures per message
  enabled after 16 seconds
== Six orders sent to jr-lesson23-kitchen, one of them burnt toast
== Watching the queues every 5 seconds
    5 s: kitchen 0 waiting, 6 in flight; dead-letter 0
   11 s: kitchen 0 waiting, 0 in flight; dead-letter 0
   16 s: kitchen 0 waiting, 6 in flight; dead-letter 0
   21 s: kitchen 0 waiting, 0 in flight; dead-letter 0
   26 s: kitchen 0 waiting, 0 in flight; dead-letter 0
   31 s: kitchen 0 waiting, 0 in flight; dead-letter 0
   37 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   42 s: kitchen 0 waiting, 6 in flight; dead-letter 0
   47 s: kitchen 0 waiting, 0 in flight; dead-letter 0
   53 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   58 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   63 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   68 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   73 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   79 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   84 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   89 s: kitchen 0 waiting, 1 in flight; dead-letter 0
   95 s: kitchen 0 waiting, 1 in flight; dead-letter 0
  100 s: kitchen 0 waiting, 1 in flight; dead-letter 0
  105 s: kitchen 0 waiting, 1 in flight; dead-letter 0
  110 s: kitchen 0 waiting, 1 in flight; dead-letter 0
  115 s: kitchen 0 waiting, 1 in flight; dead-letter 0
  121 s: kitchen 0 waiting, 0 in flight; dead-letter 1
== What the baker wrote in its log
   20.3 s  baked order 6006: rye x1, try 1
   20.3 s  batch of 1: 1 baked, 0 handed back
   20.3 s  baked order 6001: sourdough x1, try 1
   20.3 s  baked order 6004: croissant x1, try 1
   20.3 s  baked order 6005: baguette x1, try 1
   20.3 s  batch of 3: 3 baked, 0 handed back
   20.4 s  baked order 6002: rye x1, try 1
   20.4 s  batch of 2: 1 baked, 1 handed back
   20.4 s  cannot bake order 6003 (burnt toast), try 1
   56.3 s  batch of 1: 0 baked, 1 handed back
   56.3 s  cannot bake order 6003 (burnt toast), try 2
   82.8 s  batch of 1: 0 baked, 1 handed back
   82.8 s  cannot bake order 6003 (burnt toast), try 3
== In the dead-letter queue: {"order": 6003, "item": "burnt toast"}

Nobody calls the baker. The connection, an event source mapping, is Lambda polling the queue on your behalf: it receives messages, runs the function with a batch of them, and deletes the ones the function finished. The function only sees event["Records"]:

PYTHON
def handler(event, context):
    failures = []
    for r in event["Records"]:
        order = json.loads(r["body"])
        if order.get("item") == "burnt toast":
            failures.append({"itemIdentifier": r["messageId"]})
        else:
            print("baked order %s" % order["order"])
    return {"batchItemFailures": failures}

One bad order in a batch didn't make the others go round again. Order 6002 and the burnt toast arrived in the same batch of 2. The function returned the burnt toast's message ID in batchItemFailures, so Lambda deleted 6002 and handed back only the toast. Without ReportBatchItemFailures, a function has two choices for a batch: succeed, and every message is deleted, including the one it couldn't make; or fail, and every message comes back, including the five it already baked. Workers get messages twice anyway, as standard queues allow, so they must be safe to run twice: baking order 6002 again should be noticed, not done.

What the timings show:

  • The batches were 1, 3 and 2, not 5. Batch size is a maximum. Lambda runs several pollers at once and sends whatever each one has; the batching window, 1 second here, is the most it waits to fill a batch.
  • Everything ran about 20 seconds after sending, on the first try, apart from the toast. The worker had only just been connected, and its first run was also a cold start (Lesson 21).
  • The toast's retries came 36 and 26 seconds apart, not every 10, and the first run of this step saw 36 and 36. The visibility timeout is the shortest wait before a message comes back, not the exact one: Lambda's pollers still have to receive it again.
  • It reached the dead-letter queue at about 2 minutes, after 3 tries, and the five good orders were never held up by it.
  • The in-flight count jumped between 0 and 6 while there was only one message left. The counts are approximate, as the queue step showed; trust the logs and the dead-letter queue more than a single reading.

AWS recommends a visibility timeout of at least six times the function's timeout for a queue Lambda reads from, so a slow run's messages don't reappear while it's still working on them. The lab uses 10 seconds for a 5-second function, to keep the waits short; in production it would be at least 30.

Take it down

In the console: remove the function's SQS trigger, then delete the function, the event bus with its rules, the topic, and the four queues.

BASH
python events-lab.py delete
OUTPUT
== Deleting the worker and its queue connection
== Deleting the rules and the event bus
== Deleting the topic (its subscriptions go with it)
== Deleted the four queues (a deleted queue's name can't be reused for 60 seconds)
== Anything left from Lesson 23
  nothing: all clear

A rule must lose its targets before it can be deleted, and a bus its rules. Deleting a queue deletes any messages still in it, without asking.

By hand: the same lab with the AWS CLI

The core of the lab, without the script. (Your machine) The resource policies are as shown in "Building the plumbing", saved as files with your own account ID.

BASH
export AWS_PROFILE=juniper-rye AWS_REGION=us-east-2
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)

DLQ_URL=$(aws sqs create-queue --queue-name jr-lesson23-kitchen-dlq --query QueueUrl --output text)
KITCHEN_URL=$(aws sqs create-queue --queue-name jr-lesson23-kitchen --query QueueUrl --output text \
  --attributes '{"VisibilityTimeout":"10","RedrivePolicy":"{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-2:'"$ACCOUNT"':jr-lesson23-kitchen-dlq\",\"maxReceiveCount\":\"3\"}"}')

aws sqs send-message --queue-url "$KITCHEN_URL" --message-body '{"order": 3001, "item": "sourdough"}'
RECEIPT=$(aws sqs receive-message --queue-url "$KITCHEN_URL" --wait-time-seconds 20 --query 'Messages[0].ReceiptHandle' --output text)
aws sqs delete-message --queue-url "$KITCHEN_URL" --receipt-handle "$RECEIPT"
aws sqs get-queue-attributes --queue-url "$KITCHEN_URL" --attribute-names ApproximateNumberOfMessages ApproximateNumberOfMessagesNotVisible

TOPIC_ARN=$(aws sns create-topic --name jr-lesson23-new-orders --query TopicArn --output text)
aws sqs set-queue-attributes --queue-url "$KITCHEN_URL" --attributes file://kitchen-policy.json
aws sns subscribe --topic-arn "$TOPIC_ARN" --protocol sqs --attributes RawMessageDelivery=true \
  --notification-endpoint "arn:aws:sqs:us-east-2:$ACCOUNT:jr-lesson23-kitchen"
aws sns publish --topic-arn "$TOPIC_ARN" --message '{"order": 4001, "item": "rye"}'

aws events create-event-bus --name jr-lesson23-bakery
aws events put-rule --name jr-lesson23-every-order --event-bus-name jr-lesson23-bakery \
  --event-pattern '{"source":["juniperandrye.shop"],"detail-type":["OrderPlaced"]}'
aws sns set-topic-attributes --topic-arn "$TOPIC_ARN" --attribute-name Policy --attribute-value file://topic-policy.json
aws events put-targets --rule jr-lesson23-every-order --event-bus-name jr-lesson23-bakery --targets Id=topic,Arn=$TOPIC_ARN
aws events put-events --entries '[{"EventBusName":"jr-lesson23-bakery","Source":"juniperandrye.shop","DetailType":"OrderPlaced","Detail":"{\"order\":5002,\"item\":\"croissant\",\"qty\":24}"}]'

aws lambda create-event-source-mapping --function-name jr-lesson23-baker --batch-size 5 \
  --event-source-arn "arn:aws:sqs:us-east-2:$ACCOUNT:jr-lesson23-kitchen" --function-response-types ReportBatchItemFailures

Taking it down: aws lambda delete-event-source-mapping, aws events remove-targets, aws events delete-rule, aws events delete-event-bus, aws sns delete-topic, and aws sqs delete-queue for each queue.

In real systems

  • Every queue has a dead-letter queue and an alarm on it, and someone whose job is to look when it fires.
  • Workers are safe to run twice, often by recording each order's ID and skipping ones already done, because standard queues and retries both deliver repeats.
  • FIFO queues are used where order matters, like the steps of one customer's account, and standard queues everywhere else.
  • Events have a documented shape, often registered in EventBridge's schema registry, so new consumers know what to expect.
  • Big messages go in S3, with the queue or event carrying only the object's key.
  • Queues, topics, buses, rules and policies are Terraform, reviewed like code (Lesson 28).
  • Queue length and the age of the oldest message are watched in CloudWatch (Lesson 32): a growing queue means the workers can't keep up.

Spot the problem

Work out what's wrong before you read the explanation.

"Every morning, the kitchen bakes some of yesterday's orders twice." The baker reads from a queue in batches of 10. When any order in a batch fails, for example a product that's been discontinued, the function raises an exception. What's wrong? A failed batch puts every message in it back on the queue, including the nine already baked, which are then baked again. The fix: turn on ReportBatchItemFailures and return only the failed message IDs, give the queue a dead-letter queue, and make the baker skip orders it has already baked. Then check: put one bad order in a batch of good ones; are the good ones baked exactly once, and does only the bad one end up in the dead-letter queue?

Keep this

RememberWhy
SQS holds work, SNS broadcasts, EventBridge routesAnd they're often used together
Every arrow needs a resource policyMissing ones fail without an error
Standard queues don't keep order3003 came out first; FIFO if order matters
Taking hides; deleting finishesAn undeleted message comes back after the visibility timeout
Counts are approximate; one empty receive proves nothingUse long polling
A dead-letter queue for every queueThe toast moved after 3 tries, and blocked nothing
Report batch item failuresOr one bad message sends the whole batch round again
Workers must be safe to run twiceRepeats are normal, not rare
Unmatched events vanish quietlyOrder 5004 went nowhere, and nothing complained

Where you are now

The bakery's parts no longer wait on each other. The shop announces an order once; EventBridge rules send every order to the kitchen and big ones to the manager; SNS copies members' orders to the loyalty queue; and a Lambda baker works through the kitchen queue, setting aside the one order it can't make after three tries without holding up the rest. You saw a queue hand out orders in its own order, hide a message and give it back, and count approximately. Next, Lesson 24 handles work with several steps that must happen in order, with retries and a record of each one: Step Functions.

Check yourself

  1. Orders went in as 3001, 3002, 3003. Which came out first?

  2. A worker took an order and crashed before deleting it. What happens?

  3. When did the burnt toast move to the dead-letter queue?

  4. One SNS publish from a non-member reached how many queues?

  5. Why did order 5002 reach both the kitchen and the manager?

  6. What happened to order 5004, from someone.else?

  7. What did returning batchItemFailures change?

Key terms

  • SQS (Simple Queue Service): queues that hold messages until a worker takes and deletes them.
  • SNS (Simple Notification Service): topics that copy each message to every subscriber.
  • EventBridge: event buses with rules that route events by their contents.
  • Decoupling: parts that communicate through messages, without depending on each other being up.
  • Standard and FIFO queues: fast with no order promise and occasional repeats, or ordered and deduplicated.
  • Visibility timeout: how long a taken message stays hidden from other workers.
  • Dead-letter queue (DLQ): where messages go after failing too many times.
  • Redrive policy: a queue's dead-letter queue and maximum receives.
  • Long polling: a receive that waits for messages to arrive before answering.
  • Fan-out: one message delivered to many places, typically SNS to several queues.
  • Filter policy: a subscription's rule for which messages it receives.
  • Event pattern: the JSON a rule matches events against.
  • Event source mapping: Lambda polling a queue and running a function with batches.
  • Partial batch response: a function returning only the messages it failed, with batchItemFailures.

Go deeper