Skip to content
Visual explainer 4h to learn 4 steps

SQS, SNS, EventBridge & Step Functions

Decouple components with queues, topics and event buses.

By Invicly Tech, , in AWS Solutions Architect – Associate. About 13 minutes to read.

Topic 25 of 34

In short

Decoupling lets components fail or scale independently. SQS queues buffer work between producers and consumers, SNS pushes one message to many subscribers, and EventBridge routes events by pattern. Step Functions orchestrates multi-step workflows with retries and state.

Explained simply

When one part of a system calls another directly and waits for the answer, the two are tightly coupled. If the second part is slow or down, the first part fails too. Decoupling puts a middleman between them, so each side can work at its own speed and fail without taking the other down.

A queue is the simplest middleman. The producer drops a message into Amazon SQS (Simple Queue Service) and moves on. Workers pull messages when they are ready. If 10,000 orders arrive in a minute, they wait safely in the queue while workers process them as fast as they can.

Sometimes one event matters to many systems. Amazon SNS (Simple Notification Service) is a topic: publish one message and SNS pushes a copy to every subscriber. Amazon EventBridge is an event bus with rules: it looks at the content of each event and sends it only to the targets that care about it.

Some jobs are a chain of steps: charge the card, reserve stock, send the email, and undo the charge if stock runs out. AWS Step Functions runs such a workflow as a state machine, keeping track of where each run is, retrying failed steps and branching on results, so your code stays small.

Press Play on a diagram to walk through it one step at a time.

SequenceSNS to SQS fan-out
Order service
SNS topic
Billing queue
Shipping queue
  1. 1Publish OrderPlaced
    Order service to SNS topic: Publish OrderPlaced
  2. 2Deliver copy
    SNS topic to Billing queue: Deliver copy
  3. 3Deliver copy
    SNS topic to Shipping queue: Deliver copy
  4. 4Billing workers poll and process
    Billing queue to Billing queue: Billing workers poll and process
  5. 5Shipping workers poll and process
    Shipping queue to Shipping queue: Shipping workers poll and process
CompareWhich messaging service
SQS
  • Queue, consumers pull
  • Buffers load spikes
  • Standard or FIFO
  • Dead-letter queues
SNS
  • Pub/sub push
  • Fan-out to many
  • SQS, Lambda, HTTP, email
  • Filter policies
EventBridge
  • Event bus with rules
  • Content-based routing
  • SaaS and AWS events
  • Schedules and archive
LayersTightly coupled vs decoupled order flow
  1. 1
    Web tier

    Accepts the order and returns at once

  2. 2
    SNS topic OrderPlaced

    One publish, many copies

  3. 3
    SQS queues per service

    Billing, shipping, analytics buffer work

  4. 4
    Workers or Lambda

    Scale on queue depth, fail independently

  5. 5
    Dead-letter queues

    Bad messages parked for inspection

MapWhich decoupling tool?
What do you need?
  • Buffer work for one consumer type
    • SQS Standard
    • SQS FIFO if order matters
  • Same message to many subscribers
    • SNS, ideally with SQS behind it
  • Route by event content, AWS or SaaS events
    • EventBridge rules
  • Multi-step process with state
    • Step Functions Standard
    • Express for high-volume short flows
  • Run something on a schedule
    • EventBridge Scheduler

In depth

SQS internals: visibility, retries and dead letters

SQS does not delete a message when a consumer receives it. The message becomes invisible for the visibility timeout (default 30 seconds, up to 12 hours). If the consumer finishes, it calls DeleteMessage. If it crashes, the timeout ends and another consumer gets the message again. That is why Standard queues give at-least-once delivery and consumers must be idempotent: handling the same message twice must be safe.

A redrive policy moves a message to a dead-letter queue (DLQ) after it has been received maxReceiveCount times, so one bad message cannot block work forever; after a fix you can redrive it back. Use long polling (WaitTimeSeconds up to 20) to cut empty responses and cost. Messages are kept for 4 days by default, configurable from 1 minute to 14 days, and a delay queue can hide new messages for up to 15 minutes.

SequenceA message that keeps failing
Producer
SQS queue
Worker
Dead-letter queue
  1. 1SendMessage
    Producer to SQS queue: SendMessage
  2. 2ReceiveMessage (now invisible)
    Worker to SQS queue: ReceiveMessage (now invisible)
  3. 3Crashes, never deletes it
    Worker to Worker: Crashes, never deletes it
  4. 4Visibility timeout ends, visible again
    SQS queue to SQS queue: Visibility timeout ends, visible again
  5. 5Receive again: count is now 2, then 3
    Worker to SQS queue: Receive again: count is now 2, then 3
  6. 6maxReceiveCount reached: moved to DLQ
    SQS queue to Dead-letter queue: maxReceiveCount reached: moved to DLQ

Standard vs FIFO queues

Standard queues offer nearly unlimited throughput, but order is best effort and a message can occasionally arrive twice. FIFO queues (names must end in .fifo) keep strict order within a message group and remove duplicates within a 5-minute window, using a deduplication ID or a hash of the body.

The message group ID is the key idea. Order is kept per group, and different groups are processed in parallel. Use the customer ID or order ID as the group, not one fixed value, or the whole queue becomes a single line. FIFO throughput is 300 messages per second per API action, or 3,000 with batches of 10, and high throughput mode raises that much further. Choose FIFO only when order or exactly-once processing is a real requirement, because Standard is simpler and scales further.

  • Standard: at-least-once, best-effort order, nearly unlimited throughput
  • FIFO: ordered per message group, duplicates removed within 5 minutes
  • MessageGroupId decides what must stay in order
  • Consumers should still be idempotent in both types

Scaling consumers and Lambda with SQS

The queue depth tells you if workers keep up. For EC2 or ECS workers, scale on backlog per worker: ApproximateNumberOfMessagesVisible divided by the number of workers, with a target such as the number of messages one worker can finish within your acceptable delay. Plain CPU is a poor signal for queue workers.

With Lambda, an event source mapping polls the queue for you and scales the number of concurrent functions as the backlog grows. Set the queue's visibility timeout to at least six times the function timeout, so messages are not re-delivered while a batch is still running. Turn on ReportBatchItemFailures and return only the failed message IDs; otherwise one bad message makes the whole batch retry. Set a maximum concurrency on the mapping if the downstream database can only take so many connections.

SNS and EventBridge: push and route

SNS pushes each message to every subscription: SQS queues, Lambda functions, HTTPS endpoints, email, SMS and Firehose. A filter policy on a subscription lets it receive only matching messages, by message attributes or by fields in the body. SNS does not keep messages for later readers, so the classic pattern is SNS to several SQS queues: the topic fans out, and each queue stores its copy until its service is ready. The queue's access policy must allow the topic to send to it.

EventBridge receives events from AWS services on the default bus, from your apps on custom buses, and from SaaS partners. Rules match event content with patterns such as prefix, numeric ranges or anything-but, and each rule can send to up to 5 targets, with input transformation. Extras include archive and replay, retries with a DLQ, EventBridge Scheduler for cron-style and one-time schedules, and Pipes to connect a source to a target with filtering and enrichment.

Step Functions: Standard vs Express

A state machine is written in Amazon States Language (JSON). States include Task (call a service), Choice (branch), Parallel, Map (run steps for each item), Wait, Succeed and Fail. Each Task can have Retry rules with exponential backoff and Catch rules that jump to an error-handling state, so retry logic leaves your code. Direct integrations call over 200 AWS services, for example DynamoDB PutItem, without a Lambda in between.

Standard workflows run up to one year, run each step exactly once, keep a visual history of every run, and are priced per state transition. Express workflows run up to five minutes, handle very high event rates, are priced by number of runs and duration, and use at-least-once semantics when started asynchronously. The callback pattern (.waitForTaskToken) pauses a run until an outside system, or a human approval, sends the token back.

FlowOrder workflow with compensation (saga)
  1. 1
    Charge card

    Task with Retry on timeouts

  2. 2
    Reserve stock

    Catch: out of stock goes to Refund

  3. 3
    Ship order

    Waits for warehouse callback token

  4. 4
    Send email

    Direct SNS integration

  5. 5
    Refund (on error)

    Undo the charge, then Fail

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Decouple services with SQS queues~1h
  2. 2
    Fan out with SNS topics~1h
  3. 3
    Route events with EventBridge rules~1h
  4. 4
    Orchestrate workflows with Step Functions~1h

Key points

  • SQS Standard gives at-least-once delivery; FIFO gives ordering and exactly-once processing.
  • Visibility timeout hides a message while a consumer works on it.
  • Messages that fail repeatedly go to a dead-letter queue for inspection.
  • Scale consumers on queue depth with an Auto Scaling target tracking policy.
  • Step Functions Standard suits long workflows; Express suits high-volume short ones.

Key terms

Tap a card to flip it. 0/5 known

Examples

A queue with a dead-letter queue

An image-resizing worker sometimes receives corrupt files and crashes. Step 1: create a DLQ and give it a long retention. Step 2: create the main queue with a redrive policy that moves a message to the DLQ after 5 failed receives, and a visibility timeout longer than the worst processing time. Step 3: alarm on the DLQ's ApproximateNumberOfMessagesVisible so someone looks at bad files, and redrive them after a fix.

bash
aws sqs create-queue --queue-name resize-dlq --attributes MessageRetentionPeriod=1209600
DLQ_ARN=$(aws sqs get-queue-attributes --attribute-names QueueArn \
  --queue-url https://sqs.us-east-1.amazonaws.com/111122223333/resize-dlq \
  --query Attributes.QueueArn --output text)
cat > attrs.json <<EOF
{
  "VisibilityTimeout": "120",
  "ReceiveMessageWaitTimeSeconds": "20",
  "RedrivePolicy": "{\"deadLetterTargetArn\":\"$DLQ_ARN\",\"maxReceiveCount\":\"5\"}"
}
EOF
aws sqs create-queue --queue-name resize --attributes file://attrs.json

Fan-out with filtering

An order service publishes every order to one SNS topic. The fraud team only wants orders over 1,000. Step 1: subscribe the fraud queue to the topic. Step 2: set a filter policy on that subscription that matches a numeric attribute amount greater than 1000. Step 3: the publisher sets amount as a message attribute. Billing and shipping subscriptions have no filter and still get every order, while the fraud queue sees only large ones.

bash
aws sns set-subscription-attributes --subscription-arn FRAUD_SUB_ARN \
  --attribute-name FilterPolicy \
  --attribute-value '{"amount": [{"numeric": [">", 1000]}]}'

aws sns publish --topic-arn arn:aws:sns:us-east-1:111122223333:orders \
  --message '{"orderId": "o-77"}' \
  --message-attributes '{"amount": {"DataType": "Number", "StringValue": "1500"}}'

Quick reference

  • Visibility timeout: default 30 s, max 12 h; set it longer than your processing time
  • SQS retention: default 4 days, 1 minute to 14 days; long polling waits up to 20 s
  • FIFO: 300 msg/s per action, 3,000 with batching; order is per MessageGroupId
  • Lambda with SQS: visibility timeout at least 6 x function timeout; use ReportBatchItemFailures
  • SNS does not store messages; put SQS behind it when consumers can be offline
  • EventBridge rule: content-based pattern, up to 5 targets; archive and replay available
  • Step Functions Standard: up to 1 year, exactly once. Express: up to 5 minutes, high volume
  • Scale queue workers on backlog per instance, not on CPU

Common mistakes

  • Using SNS alone when consumers may be offline; add SQS to persist messages.
  • Setting visibility timeout shorter than processing time, causing duplicates.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A worker takes up to 2 minutes per message, and messages are being processed twice. What is the most likely fix?

Question 2

2In a FIFO queue, all messages use the same MessageGroupId and throughput is poor. Why?

Question 3

3One malformed message makes a Lambda function fail, and the whole batch of 10 retries again and again. What helps most?

Question 4

4Events from many AWS services must be routed to different targets based on fields inside each event. Which service fits best?

Question 5

5A loan approval process waits up to 3 days for a human decision. Which option fits?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a Standard queue, send one message, receive it, and delete it. Then explain what would happen if you did not delete it.

  2. Exercise 2medium

    Subscribe an SQS queue to an SNS topic, publish a message, and read it from the queue.

  3. Exercise 3hard

    Write a Step Functions state machine that calls a Lambda function with retries, and sends failures to a notification state instead of just failing.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

What is the difference between SQS and SNS?
SQS is a queue: messages wait until a consumer pulls and deletes them. SNS is a topic: it pushes each message to all subscribers at once and does not keep it for later.
When should I pick EventBridge over SNS?
Pick EventBridge when you need rich content-based routing, AWS service or SaaS events, schedules, or archive and replay. Pick SNS for simple, very high-throughput fan-out, SMS or email, or ordered fan-out with FIFO topics.
Can SQS guarantee that a message is processed only once?
FIFO queues remove duplicates and keep order, giving exactly-once processing within their rules. Standard queues can deliver a message more than once, so consumers should be idempotent.
How do I send messages larger than the SQS size limit?
Store the payload in S3 and send a small message with a pointer to it. The Amazon SQS Extended Client Library does this for you.
ShareXLinkedInWhatsApp