Thuta Learning
AWS Advanced
Event-Driven & ServerlessDevOpsAdvanced

SQS and SNS Patterns — Queues, Fan-Out and Idempotent Consumers

AWS AdvancedLesson 1650 min

What you'll walk away with

  • Choose SQS standard or FIFO for a workload and design its message groups
  • Configure visibility timeout, long polling and a DLQ with sound values
  • Write an idempotent consumer with a DynamoDB conditional write
  • Fan out one SNS topic to several SQS queues with filter policies

Explain it simply

Explain it simply

SQS (Simple Queue Service) is like a mailbox. A producer drops a message in and can leave immediately. A consumer picks the message up when it is ready, does the work, and only then deletes it from the box. So if the consumer is down for a while, or traffic suddenly spikes, messages wait safely instead of being lost.

SNS (Simple Notification Service) is like a loudspeaker. Publish to a topic and every subscriber — SQS queues, Lambda functions, email — gets its own copy. Combine the two and you get the fan-out pattern: one event, processed separately by three services, each at its own pace.

Problem → Why → Solution

The problem — a synchronous call chain, and customers charged twice

The order service calls the billing, shipping and analytics services over HTTP, one after another, for every order. On the day analytics slows down, the whole checkout slows down; on the day shipping is down, orders fail. One broken service breaks everything.

The team adds an SQS queue and thinks the problem is solved. A week later, some customers are charged twice. The billing worker's payment call takes 40 seconds, but the queue's visibility timeout is still the default 30 seconds, so the message reappears in the queue and a second worker processes it again.

billing_worker_bad.py
import boto3

sqs = boto3.client("sqs", region_name="us-east-1")
URL = sqs.get_queue_url(QueueName="billing-queue")["QueueUrl"]


def charge_card(body):
    """Calls the payment provider. In production this takes ~40 seconds."""
    # BUG 1: queue visibility timeout is the default 30 s, shorter than this call
    # BUG 2: no idempotency check, so a redelivered message charges again
    return f"charged for {body}"


resp = sqs.receive_message(QueueUrl=URL, MaxNumberOfMessages=10)  # BUG 3: short poll
for msg in resp.get("Messages", []):
    print(charge_card(msg["Body"]))
    sqs.delete_message(QueueUrl=URL, ReceiptHandle=msg["ReceiptHandle"])

Why this happens

When a consumer receives a message, SQS doesn't delete it; it only hides it for the visibility timeout. If it isn't deleted before the timeout ends, the message reappears — by design, so a crashed consumer never loses work. Standard queues are at-least-once, so occasional duplicates arrive even with a correct timeout. The real fix is an idempotent consumer.

Core concept — how queues really behave

Visibility timeout
How long a received message stays hidden from other consumers (default 30 seconds, maximum 12 hours). If it isn't deleted within that window, it becomes visible in the queue again.

A message's life is: send, receive (the visibility timeout starts), process, delete. The visibility timeout must be longer than your longest processing time. When Lambda reads the queue, AWS recommends a queue visibility timeout of about six times the function timeout. If processing time is unpredictable, extend the timeout while working with ChangeMessageVisibility.

Setting WaitTimeSeconds up to 20 on receive enables long polling: instead of returning empty immediately, the call waits until a message arrives. Every request is billed, so fewer empty responses directly lowers cost.

Standard queueFIFO queue
DeliveryAt-least-once (duplicates possible)Duplicates removed within a 5-minute dedup window
OrderingBest effortStrict within each message group
ThroughputNearly unlimitedPer-queue limits (raised by high-throughput mode)

In an SNS fan-out, the topic sends a copy of every published message to each subscription. A subscription with a filter policy receives only matching messages — billing takes only OrderPlaced and OrderRefunded, shipping only OrderPlaced. Each SQS queue buffers its own copy, so when one service is down the others keep working, and the downed service catches up from its queue when it returns.

Know when not to use this pattern too. Once SQS deletes a message it is gone, so 'replay last week's events' is impossible — a log-based stream such as Kinesis Data Streams fits that need better. Work whose caller must wait for the answer (a login check, say) doesn't belong behind a queue either. Queues shine at decoupling work that can safely happen a little later.

text
SNS TO SQS FAN-OUT WITH FILTERS AND DLQS
----------------------------------------
 order     publish  +-------+
 service ---------> |  SNS  |--+--> [Placed|Refunded] --> billing-queue
                    | topic |  |                             |  5 fails
                    +-------+  |                             v
                               |                          billing-dlq
                               +--> [Placed] -----------> shipping-queue
                               |
                               +--> [no filter] --------> analytics-queue

   each queue has its own consumers, pace and DLQ; consumers are idempotent
Mental model
  1. Publish once to SNS
  2. Filter: copy per matching queue
  3. Receive hides msg (visibility)
  4. Process idempotently
  5. Delete, or retry until the DLQ

Assume every message arrives at least once, and write consumers so that a second arrival changes nothing.

A subscription filter policy

billing-filter.json
{
  "eventType": ["OrderPlaced", "OrderRefunded"],
  "amount": [{ "numeric": [">=", 100] }],
  "channel": [{ "anything-but": ["test"] }]
}

Keys are ANDed and values inside one array are ORed: this policy passes only messages whose eventType is OrderPlaced or OrderRefunded, AND whose amount is at least 100, AND whose channel is not test. By default it matches message attributes; set the subscription's FilterPolicyScope to MessageBody to match fields in the JSON body instead. For a numeric match the attribute's DataType must be Number.

Fan-out with idempotent consumers — a working example

This script assumes the order-events topic, three filtered queues (billing, shipping, analytics) and a processed-events DynamoDB table already exist — the CLI script in the next section creates them. It publishes four events (e-1 twice, as a producer retry) and shows what each queue receives and how duplicates are skipped. The idempotency key is 'consumer#eventId', so each consumer handles each event exactly once.

fanout_demo.py
import json

import boto3
from botocore.exceptions import ClientError

sns = boto3.client("sns", region_name="us-east-1")
sqs = boto3.client("sqs", region_name="us-east-1")
ddb = boto3.client("dynamodb", region_name="us-east-1")

# create_topic is idempotent: it returns the existing topic's ARN
TOPIC_ARN = sns.create_topic(Name="order-events")["TopicArn"]


def publish(event_id, event_type, order_id):
    body = {"eventId": event_id, "type": event_type, "orderId": order_id}
    sns.publish(
        TopicArn=TOPIC_ARN,
        Message=json.dumps(body),
        MessageAttributes={
            "eventType": {"DataType": "String", "StringValue": event_type}
        },
    )


def first_time(consumer, event_id):
    """Record the event; return False if this consumer already handled it."""
    try:
        ddb.put_item(
            TableName="processed-events",
            Item={"pk": {"S": f"{consumer}#{event_id}"}},
            ConditionExpression="attribute_not_exists(pk)",
        )
        return True
    except ClientError as err:
        if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return False
        raise


def drain(queue_name):
    url = sqs.get_queue_url(QueueName=queue_name)["QueueUrl"]
    resp = sqs.receive_message(
        QueueUrl=url, MaxNumberOfMessages=10, WaitTimeSeconds=1, VisibilityTimeout=60
    )
    msgs = resp.get("Messages", [])
    print(f"{queue_name}: received {len(msgs)}")
    for msg in sorted(msgs, key=lambda m: json.loads(m["Body"])["eventId"]):
        event = json.loads(msg["Body"])
        if first_time(queue_name, event["eventId"]):
            result = "processed"  # real work (charge, ship, ...) goes here
        else:
            result = "duplicate, skipped"
        print(f"  {event['eventId']} {event['type']} {event['orderId']} -> {result}")
        sqs.delete_message(QueueUrl=url, ReceiptHandle=msg["ReceiptHandle"])


publish("e-1", "OrderPlaced", "o-1001")
publish("e-2", "OrderShipped", "o-1001")
publish("e-3", "OrderRefunded", "o-1002")
publish("e-1", "OrderPlaced", "o-1001")  # producer retry: same event again
print("published 4 messages (e-1 twice)")

for name in ["billing-queue", "shipping-queue", "analytics-queue"]:
    drain(name)

Not runnable in the browser

This code runs against a real AWS account, so it cannot run in the browser playground. Try it in your own terminal or in AWS CloudShell.

Code breakdown

  1. MessageAttributes"eventType": {"DataType": "String", "StringValue": event_type}

    Filter policies match message attributes by default, so eventType is sent as an attribute. If it were only in the body, the filter wouldn't see it unless FilterPolicyScope were MessageBody.

  2. conditional putConditionExpression="attribute_not_exists(pk)"

    The heart of idempotency. The first write succeeds; a second raises ConditionalCheckFailedException, which atomically identifies the duplicate — even if two workers race, only one wins.

  3. receiveWaitTimeSeconds=1, VisibilityTimeout=60

    Use WaitTimeSeconds=20 (long polling) in production; 1 just keeps the demo fast. VisibilityTimeout exceeds the processing time, and the message is deleted only after the work is done.

  4. fan-out resultbilling 3 / shipping 2 / analytics 4

    Thanks to the filters, billing never sees OrderShipped, shipping sees only OrderPlaced, and unfiltered analytics sees everything. e-1 was published twice, so every queue got two copies, yet each processed it once.

You should see
published 4 messages (e-1 twice)
billing-queue: received 3
  e-1 OrderPlaced o-1001 -> processed
  e-1 OrderPlaced o-1001 -> duplicate, skipped
  e-3 OrderRefunded o-1002 -> processed
shipping-queue: received 2
  e-1 OrderPlaced o-1001 -> processed
  e-1 OrderPlaced o-1001 -> duplicate, skipped
analytics-queue: received 4
  e-1 OrderPlaced o-1001 -> processed
  e-1 OrderPlaced o-1001 -> duplicate, skipped
  e-2 OrderShipped o-1001 -> processed
  e-3 OrderRefunded o-1002 -> processed
The life of a message
  1. ReceiveMessage (count +1)
  2. Hidden for visibility timeout
  3. Process + DeleteMessage

Deleted in time

done

Timeout, receive count < maxReceiveCount

visible again -> retry

Receive count > maxReceiveCount

moved to DLQ

Wiring the fan-out with the CLI

For SNS to deliver to an SQS queue, the queue policy (a resource policy) must allow it. Restricting it to this one topic with an aws:SourceArn condition stops any other topic in the account from injecting messages. The script creates the DLQ first, then the main queue with visibility timeout, long polling and a redrive policy, attaches the policy, and subscribes with raw message delivery and a filter policy. SQS attributes are a string map, and RedrivePolicy and Policy must be JSON-encoded strings, so jq does the escaping.

queue-policy.json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowOrderEventsTopic",
      "Effect": "Allow",
      "Principal": { "Service": "sns.amazonaws.com" },
      "Action": "sqs:SendMessage",
      "Resource": "arn:aws:sqs:us-east-1:111122223333:billing-queue",
      "Condition": {
        "ArnEquals": {
          "aws:SourceArn": "arn:aws:sns:us-east-1:111122223333:order-events"
        }
      }
    }
  ]
}
create-fanout.sh
TOPIC_ARN=$(aws sns create-topic --name order-events --query TopicArn --output text)

DLQ_URL=$(aws sqs create-queue --queue-name billing-dlq \
  --attributes MessageRetentionPeriod=1209600 --query QueueUrl --output text)
DLQ_ARN=$(aws sqs get-queue-attributes --queue-url $DLQ_URL \
  --attribute-names QueueArn --query Attributes.QueueArn --output text)

REDRIVE=$(jq -nc --arg arn "$DLQ_ARN" '{deadLetterTargetArn: $arn, maxReceiveCount: "5"}')
jq -n --arg r "$REDRIVE" \
  '{VisibilityTimeout: "180", ReceiveMessageWaitTimeSeconds: "20", RedrivePolicy: $r}' \
  > billing-attrs.json
BILLING_URL=$(aws sqs create-queue --queue-name billing-queue \
  --attributes file://billing-attrs.json --query QueueUrl --output text)
BILLING_ARN=$(aws sqs get-queue-attributes --queue-url $BILLING_URL \
  --attribute-names QueueArn --query Attributes.QueueArn --output text)

jq -n --arg p "$(cat queue-policy.json)" '{Policy: $p}' > policy-attrs.json
aws sqs set-queue-attributes --queue-url $BILLING_URL \
  --attributes file://policy-attrs.json

jq -n --arg f "$(jq -c . billing-filter.json)" \
  '{RawMessageDelivery: "true", FilterPolicy: $f}' > sub-attrs.json
aws sns subscribe --topic-arn $TOPIC_ARN --protocol sqs \
  --notification-endpoint $BILLING_ARN --attributes file://sub-attrs.json

FIFO queues and SNS FIFO

A FIFO queue (its name must end in .fifo) requires a MessageGroupId on every message. Within one group, messages are delivered strictly in order, one after another; different groups are processed in parallel. So choosing the group ID matters: give each entity that needs ordering — an account ID or an order ID — its own group. Use a single group for everything and the whole queue crawls along like one consumer.

Sending a message with the same deduplication ID within 5 minutes is acknowledged as successful but not enqueued again, which absorbs producer retries. With ContentBasedDeduplication on, the SHA-256 of the body becomes the ID. SNS FIFO topics give ordering and dedup at the topic level and fan out to SQS queues — subscribe SQS FIFO queues to keep ordering end to end. Dedup only covers a 5-minute window, so keep consumer-side idempotency even with FIFO.

fifo_demo.py
import boto3

sqs = boto3.client("sqs", region_name="us-east-1")
url = sqs.create_queue(
    QueueName="payments.fifo",
    Attributes={"FifoQueue": "true", "ContentBasedDeduplication": "false"},
)["QueueUrl"]

sends = [
    ("acct-42", "deposit 100", "op-1"),
    ("acct-42", "withdraw 30", "op-2"),
    ("acct-42", "withdraw 30", "op-2"),  # retry with same dedup id: dropped
    ("acct-7", "deposit 50", "op-3"),
]
for group, body, dedup_id in sends:
    sqs.send_message(
        QueueUrl=url,
        MessageBody=body,
        MessageGroupId=group,
        MessageDeduplicationId=dedup_id,
    )

resp = sqs.receive_message(
    QueueUrl=url, MaxNumberOfMessages=10, AttributeNames=["MessageGroupId"]
)
for m in resp["Messages"]:
    print(m["Attributes"]["MessageGroupId"], "->", m["Body"])
# acct-42 -> deposit 100
# acct-42 -> withdraw 30
# acct-7 -> deposit 50

DLQs, redrive and Lambda partial batch failures

A redrive policy's maxReceiveCount sets how many times a message may be received and fail. After that, it moves to the DLQ — so one 'poison message' that can never succeed no longer blocks the queue with endless retries. Once the bug is fixed, StartMessageMoveTask (the console's 'redrive') sends the DLQ messages back to the source queue.

Lambda reads SQS in batches. By default, if one message in a batch fails, the whole batch is retried, and the messages that succeeded are processed again. Turn on ReportBatchItemFailures on the event source mapping and return only the failed message IDs, and only those go back to the queue.

redrive.sh
# how many messages are waiting in the DLQ?
aws sqs get-queue-attributes --queue-url $DLQ_URL \
  --attribute-names ApproximateNumberOfMessages

# after deploying the fix: move them back to the source queue, 50 msg/s
aws sqs start-message-move-task --source-arn $DLQ_ARN \
  --destination-arn $BILLING_ARN --max-number-of-messages-per-second 50
billing_handler.py
import json


def process(order):
    if order.get("amount", 0) <= 0:
        raise ValueError(f"bad amount for {order['orderId']}")


def handler(event, context):
    failures = []
    for record in event["Records"]:
        try:
            process(json.loads(record["body"]))
        except Exception as err:  # noqa: BLE001 - report, don't fail the batch
            print(f"failed {record['messageId']}: {err}")
            failures.append({"itemIdentifier": record["messageId"]})
    # only the failed messages return to the queue; the rest are deleted
    return {"batchItemFailures": failures}


if __name__ == "__main__":
    sample = {
        "Records": [
            {"messageId": "m-1", "body": json.dumps({"orderId": "o-1", "amount": 25})},
            {"messageId": "m-2", "body": json.dumps({"orderId": "o-2", "amount": 0})},
            {"messageId": "m-3", "body": json.dumps({"orderId": "o-3", "amount": 9})},
        ]
    }
    print(handler(sample, None))

In production

How teams run this in production

In event-driven systems, teams own SNS topics along domain lines — one topic per kind of domain event (order-events, payment-events) — and each consuming team owns its own SQS queue and DLQ. The producer doesn't know how many consumers exist: adding a new consumer means adding one subscription, with no change to producer code.

The two most important metrics are ApproximateAgeOfOldestMessage (are consumers falling behind?) and the DLQ's ApproximateNumberOfMessagesVisible (alarm on anything above 0). Scaling ECS workers on queue depth is also common. Messages share an envelope with eventId, eventType, version and timestamp, and bumping the version on schema changes keeps consumers from breaking. When routing needs grow — many-field rules, SaaS events, a schema registry — teams consider EventBridge, covered in a later lesson.

  • To avoid a producer that writes to its database and then crashes before publishing, teams use the transactional outbox pattern (or DynamoDB Streams).
  • Large payloads go to S3 and the message carries only the S3 key (the claim-check pattern).
  • DLQ redrive is a written runbook step, done only after the bug is fixed.

Common mistakes

Common mistakes

Mistake 1 — a visibility timeout shorter than the work

Leave the default 30 seconds, as in the problem section, and slow work gets duplicated while queue depth never seems to drop. With Lambda, the classic version is raising the function timeout but not the queue's visibility timeout. Keep the visibility timeout above the longest processing time — for Lambda, about six times the function timeout.

Mistake 2 — parsing the body without raw message delivery

By default SNS wraps each message in a JSON envelope (Type, MessageId, TopicArn, Message ...) before delivering to SQS. A consumer that reads json.loads(body)['orderId'] gets a KeyError, because the real payload is a string inside body['Message']. Either enable RawMessageDelivery or unwrap the envelope — whichever you choose, keep it consistent across consumers.

Mistake 3 — a short DLQ retention, and the wrong encryption key

For standard queues, a message's age in the DLQ is counted from when it first entered the source queue. If the DLQ's retention matches the source (say 4 days), messages can expire soon after landing in the DLQ — set the DLQ to 14 days. Also, if a queue is encrypted with the AWS managed key (aws/sqs), SNS can't use that key and deliveries silently fail — use SSE-SQS or a customer managed key whose policy allows SNS.

Best practices

Best practices

  • Make every consumer idempotent — use the event ID with a conditional write.
  • Give every queue a DLQ with an alarm, and set maxReceiveCount around 3-5.
  • Use long polling (WaitTimeSeconds=20) and batch APIs (SendMessageBatch, DeleteMessageBatch).
  • In FIFO queues, choose MessageGroupId per entity — never one group for everything.

💰 Cost & Cleanup

SQS and SNS both bill per request, and the monthly free tier includes one million requests each — this lab's handful of requests stays inside it. SQS counts each 64 KB chunk of a payload as one request, and empty receives are requests too, which is why long polling saves money. FIFO requests cost somewhat more than standard. The on-demand DynamoDB table bills per write and also has a free tier. Delete the topic, queues and table after the lab, and check the pricing pages for exact rates.

Clean up when you are done

cleanup.sh
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
aws sns delete-topic --topic-arn arn:aws:sns:us-east-1:$ACCOUNT:order-events
for Q in billing-queue shipping-queue analytics-queue billing-dlq payments.fifo; do
  URL=$(aws sqs get-queue-url --queue-name $Q --query QueueUrl --output text)
  aws sqs delete-queue --queue-url $URL
done
aws dynamodb delete-table --table-name processed-events

Mini challenge

Mini challenge — add an audit queue

The finance team wants to audit only refunds of $100 or more. Subscribe an audit-queue to the order-events topic, publish three events and check which ones arrive.

  • The filter policy must match eventType = OrderRefunded AND amount >= 100
  • Send amount as a message attribute with DataType Number
  • Enable raw message delivery

Expected: Only the $250 refund reaches audit-queue; the $40 refund and the $500 OrderPlaced do not.

Show hint

A numeric filter looks like '"amount": [{"numeric": [">=", 100]}]'. Pass FilterPolicy to subscribe as a string with json.dumps.

Show solution
audit_queue.py
import json

import boto3

sns = boto3.client("sns", region_name="us-east-1")
sqs = boto3.client("sqs", region_name="us-east-1")

topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
url = sqs.create_queue(QueueName="audit-queue")["QueueUrl"]
arn = sqs.get_queue_attributes(QueueUrl=url, AttributeNames=["QueueArn"])[
    "Attributes"]["QueueArn"]
# (in a real account, also attach a queue policy allowing this topic)
audit_filter = {"eventType": ["OrderRefunded"], "amount": [{"numeric": [">=", 100]}]}
sns.subscribe(
    TopicArn=topic_arn,
    Protocol="sqs",
    Endpoint=arn,
    Attributes={"RawMessageDelivery": "true", "FilterPolicy": json.dumps(audit_filter)},
)

for event_type, amount in [("OrderRefunded", 250), ("OrderRefunded", 40),
                           ("OrderPlaced", 500)]:
    sns.publish(
        TopicArn=topic_arn,
        Message=json.dumps({"type": event_type, "amount": amount}),
        MessageAttributes={
            "eventType": {"DataType": "String", "StringValue": event_type},
            "amount": {"DataType": "Number", "StringValue": str(amount)},
        },
    )

msgs = sqs.receive_message(QueueUrl=url, MaxNumberOfMessages=10).get("Messages", [])
for m in msgs:
    print("audit:", m["Body"])
print(f"{len(msgs)} message(s) in audit-queue")

Quick quiz 1 / 3

A worker takes 45 seconds to process a message and the queue's visibility timeout is 30 seconds. What is likely to happen?

Quick quiz 2 / 3

Transactions for each bank account must be processed in order, but different accounts can run in parallel. Which design fits best?

Quick quiz 3 / 3

Every OrderPlaced event must reach all three services: billing, shipping and analytics. Which design is right?

What to remember

  • Keep the visibility timeout above processing time and delete messages only after the work is done.
  • At-least-once delivery means every consumer must be idempotent.
  • FIFO = strict order within a group + 5-minute dedup; pick group IDs per entity.
  • A DLQ with maxReceiveCount isolates poison messages; redrive them with StartMessageMoveTask.
  • SNS-to-SQS fan-out with filter policies lets you add consumers without touching the producer.

Amazon SQS Developer Guide — AWS Documentation

Amazon SNS message filtering — AWS Documentation

Using Lambda with Amazon SQS — AWS Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

SQS and SNS Patterns — Queues, Fan-Out and Idempotent Consumers | Thuta Learning