123DevOps··12 min read

AWS SNS, SQS, and EventBridge: when to use each one, with queues, fan-out, and events in practice

Compare SQS, SNS, and EventBridge, understand FIFO, visibility timeout, DLQs, fair queues, subscription filters, Scheduler, Pipes, and replay, and build an order-events flow with boto3, the AWS CLI, and Terraform, tested with moto.

Cloud

Almost every system on AWS reaches the same point: one service needs to tell others that something happened, without waiting for them and without going down when one of them does. AWS offers three building blocks for this, and they get mixed up all the time: SQS (queue), SNS (publish and subscribe), and EventBridge (event bus). In this guide we look at when to use each one, the features that matter in production, and a complete order-events flow with boto3, the AWS CLI, and Terraform.

About testing: the commands were checked against the offline help of AWS CLI 2.42.1 and executed against a local mock (moto 5.2.6), without an AWS account. The Python code ran end to end on moto. The Terraform passed terraform validate with the hashicorp/aws 6.74.0 provider, without plan or apply.

When to use each one

SQS SNS EventBridge
Model Queue (the consumer pulls) Pub/sub (the service pushes) Bus with content-based routing
Consumers One group of workers per queue Many subscribers per topic Up to 5 targets per rule, many rules per bus
Filtering None: the queue is the filter Filter policy per subscription Event patterns (prefix, numeric, exists, anything-but, wildcard)
Stores messages Yes, up to 14 days No, delivers and moves on Only with an archive
Ordering FIFO per MessageGroupId FIFO topics No ordering guarantee
Typical sources Your application Your application and AWS services Application, AWS services, SaaS partners, schedules
Use it for Buffering, work queues, absorbing spikes Fan-out, SMS, email, mobile push Cross-domain integration, AWS events, replay

In practice, the three combine. The most common pattern is EventBridge or SNS at the entrance and an SQS queue in front of each consumer. The queue gives the consumer retries, a DLQ, and flow control.

Message size: 1 MiB on all three

The 256 KB limit lasted for years and is now gone on all three services, on different dates. Check the current docs for your Region:

  • SQS: 1 MiB (1,048,576 bytes) since August 2025, on both standard and FIFO queues. The MaximumMessageSize default is already 1 MiB.
  • EventBridge: events up to 1 MB since early 2026, in most commercial Regions, with a few exceptions.
  • SNS: up to 1 MiB since September 2026, but not by default. The topic’s MaximumMessageSize attribute still starts at 256 KiB. Above that, the topic can have at most 100 subscriptions, all of them SQS, Data Firehose, or Lambda.

Large messages also cost more. All three services bill per request, in 64 KB chunks, so a 1 MiB message counts as 16 requests. To think about cost per event, see FinOps to cut AWS costs.

SQS: the queue

Standard or FIFO

A standard queue has nearly unlimited throughput, at-least-once delivery, and only best-effort ordering. A FIFO queue (name ending in .fifo) guarantees ordering within each MessageGroupId and deduplicates by MessageDeduplicationId or by a content hash, within a 5-minute window.

Visibility timeout and long polling

When a consumer receives a message, the message stays invisible for the visibility timeout (30 s by default, 12 h at most). If the consumer does not delete the message within that time, it goes back to the queue and another worker receives it. So set the timeout above the real processing time. With Lambda, a common recommendation is six times the function timeout; see the AWS Lambda guide.

Long polling (ReceiveMessageWaitTimeSeconds or --wait-time-seconds, up to 20 s) makes the call wait for messages instead of returning empty. The result: fewer billed requests and lower latency.

DLQ and redrive

After maxReceiveCount attempts, the message moves to the dead-letter queue. Once the bug is fixed, redrive returns the messages to the source queue with start-message-move-task. On the DLQ, RedriveAllowPolicy controls which queues may use it.

Fair queues

New in 2025: on standard queues, when the producer sends a MessageGroupId (for example, the customer ID), SQS treats the queue as a fair queue. If one noisy customer dumps thousands of messages, the dwell time for the other customers stays stable. Nothing changes on the consumer side, and messages from the same group are still processed in parallel.

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

Q_URL=$(aws sqs create-queue --queue-name billing --query QueueUrl --output text \
  --attributes "$(jq -nc --arg dlq "$DLQ_ARN" '{
      VisibilityTimeout: "180",
      ReceiveMessageWaitTimeSeconds: "20",
      RedrivePolicy: ({deadLetterTargetArn: $dlq, maxReceiveCount: "5"} | tojson)}')")

aws sqs create-queue --queue-name payments.fifo \
  --attributes FifoQueue=true,ContentBasedDeduplication=true

aws sqs send-message --queue-url "$Q_URL" --message-body '{"order_id":"o-1"}' \
  --message-group-id customer-42         # fair queue: one group per customer
aws sqs receive-message --queue-url "$Q_URL" --wait-time-seconds 20 --max-number-of-messages 10
aws sqs start-message-move-task --source-arn "$DLQ_ARN"   # redrive back to the source

start-message-move-task was checked only against the offline help; moto does not implement it.

SNS: fan-out and filters

SNS delivers each publication to every subscription on the topic. The classic fan-out is a topic with several subscribed SQS queues, one per consumer. Turn on raw message delivery so the queue receives only the body, without the SNS JSON envelope, and grant the topic write access in the queue policy.

The filter policy decides, per subscription, what gets through. The scope comes from FilterPolicyScope:

  • MessageAttributes (default): filters on the attributes sent with publish.
  • MessageBody: filters on the JSON content of the message. It is the only one that works with events coming from EventBridge, S3, and other services, which do not send attributes.
TOPIC_ARN=$(aws sns create-topic --name orders-fanout \
  --attributes MaximumMessageSize=1048576 --query TopicArn --output text)

aws sns subscribe --topic-arn "$TOPIC_ARN" --protocol sqs --notification-endpoint "$VIP_ARN" \
  --attributes '{"RawMessageDelivery":"true","FilterPolicyScope":"MessageBody",
    "FilterPolicy":"{\"detail\":{\"total\":[{\"numeric\":[\">=\",1000]}]}}"}'

aws sns publish --topic-arn "$TOPIC_ARN" --message '{"order_id":"o-3"}' \
  --message-attributes '{"channel":{"DataType":"String","StringValue":"app"}}'

EventBridge: buses, rules, and more

Rules and event patterns

An event bus receives events: the default bus (events from AWS services), custom buses for your application, and SaaS partner buses. Each rule has an event pattern and up to 5 targets. The pattern matches fields such as source, detail-type, and any path inside detail.

aws events create-event-bus --name orders
aws events put-rule --name order-created --event-bus-name orders \
  --event-pattern '{"source":["shop.orders"],"detail-type":["OrderCreated"],"detail":{"total":[{"numeric":[">",0]}]}}'
aws events put-targets --rule order-created --event-bus-name orders \
  --targets Id=billing,Arn="$Q_ARN" Id=fanout,Arn="$TOPIC_ARN"
aws events put-events --entries '[{"Source":"shop.orders","DetailType":"OrderCreated",
  "Detail":"{\"order_id\":\"o-1\",\"total\":250}","EventBusName":"orders"}]'

Scheduler and Pipes

EventBridge Scheduler is a separate service (the scheduler CLI) for one-time, rate(), or cron() schedules, with time zones, flexible windows, and groups. With --action-after-completion DELETE, a one-time schedule deletes itself after it runs. EventBridge Pipes, in turn, connects one source to one target, point to point, with optional filtering and enrichment. For example, SQS, Kinesis, or DynamoDB Streams into Step Functions, with no glue code.

aws scheduler create-schedule --name daily-close \
  --schedule-expression 'cron(0 3 * * ? *)' --schedule-expression-timezone America/New_York \
  --flexible-time-window Mode=FLEXIBLE,MaximumWindowInMinutes=15 \
  --target '{"Arn":"arn:aws:sqs:us-east-1:123456789012:billing",
    "RoleArn":"arn:aws:iam::123456789012:role/scheduler-sqs","Input":"{\"type\":\"daily-close\"}"}'

aws pipes create-pipe --name orders-to-sfn --source "$Q_ARN" \
  --target arn:aws:states:us-east-1:123456789012:stateMachine:invoice \
  --role-arn arn:aws:iam::123456789012:role/pipes-billing

Archive and replay

An archive stores a bus’s events (all of them, or only those matching a pattern), with configurable retention. After you fix a consumer, replay resends a time range to the same bus:

aws events create-archive --archive-name orders-90d --retention-days 90 \
  --event-source-arn arn:aws:events:us-east-1:123456789012:event-bus/orders
aws events start-replay --replay-name reprocess-20261124 \
  --event-source-arn arn:aws:events:us-east-1:123456789012:archive/orders-90d \
  --event-start-time 2026-11-24T00:00:00Z --event-end-time 2026-11-25T00:00:00Z \
  --destination Arn=arn:aws:events:us-east-1:123456789012:event-bus/orders

Replayed events reach the consumers again, one more reason for the idempotency covered in the last section.

Example: order events with boto3

The flow: the orders service publishes OrderCreated to the orders bus. The rule delivers the event to the billing queue and to the orders-fanout topic. The topic distributes to inventory (everything) and orders-vip (payload filter: total >= 1000).

orders service ──put_events──> bus "orders" ──rule order-created──┬──> SQS billing (+ DLQ)
                                                                  └──> SNS orders-fanout ──┬──> SQS inventory
                                                                                           └──> SQS orders-vip (total >= 1000)
"""Order event publisher and consumer (EventBridge -> SQS/SNS)."""
import json
import os

import boto3
from botocore.exceptions import ClientError

events = boto3.client("events")
sqs = boto3.client("sqs")
dynamodb = boto3.client("dynamodb")

BUS = os.environ.get("EVENT_BUS", "orders")
TABLE = os.environ.get("IDEMPOTENCY_TABLE", "processed-orders")


def publish_order_created(order: dict) -> str:
    resp = events.put_events(Entries=[{
        "Source": "shop.orders",
        "DetailType": "OrderCreated",
        "Detail": json.dumps(order),
        "EventBusName": BUS,
    }])
    if resp["FailedEntryCount"]:
        raise RuntimeError(f"publish failed: {resp['Entries']}")
    return resp["Entries"][0]["EventId"]


def already_processed(consumer: str, order_id: str) -> bool:
    """Writes the idempotency key; returns True if it already existed."""
    try:
        dynamodb.put_item(
            TableName=TABLE,
            Item={"pk": {"S": f"{consumer}#{order_id}"}},
            ConditionExpression="attribute_not_exists(pk)",
        )
        return False
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            return True
        raise


def consume(queue_url: str, consumer: str, handle, wait: int = 20) -> int:
    resp = sqs.receive_message(
        QueueUrl=queue_url, MaxNumberOfMessages=10, WaitTimeSeconds=wait
    )
    processed = 0
    for msg in resp.get("Messages", []):
        event = json.loads(msg["Body"])
        order = event["detail"]
        if not already_processed(consumer, order["order_id"]):
            handle(order)
            processed += 1
        sqs.delete_message(QueueUrl=queue_url, ReceiptHandle=msg["ReceiptHandle"])
    return processed

Note that put_events can accept the call and still reject entries: always check FailedEntryCount. In the moto test (boto3 1.44.11), we published three events, one of them a duplicate. Billing processed 2, inventory processed 2, and only the 4,200 order reached orders-vip. An honest caveat: moto 5.2.6 does not deliver EventBridge events to SNS targets. So for that hop the test forwarded to the topic the same envelope that EventBridge delivered to a queue, and put_targets with the SNS target was validated separately with botocore’s Stubber. Consumers usually run on Lambda (see the AWS Lambda guide), and the terminal recipes are in how to manage AWS with the AWS CLI.

Terraform

The same design in Terraform: a queue with a DLQ and redrive_policy, a topic with a filtered subscription, a bus, a rule, targets, and the policies that allow EventBridge and SNS to write to the destinations. To choose between Terraform and OpenTofu, see Terraform or OpenTofu.

resource "aws_sqs_queue" "billing_dlq" {
  name                      = "billing-dlq"
  message_retention_seconds = 1209600 # 14 days
}

resource "aws_sqs_queue" "billing" {
  name                       = "billing"
  visibility_timeout_seconds = 180 # longer than the processing time
  receive_wait_time_seconds  = 20  # long polling
  redrive_policy = jsonencode({
    deadLetterTargetArn = aws_sqs_queue.billing_dlq.arn
    maxReceiveCount     = 5
  })
}

resource "aws_sqs_queue" "vip" {
  name = "orders-vip"
}

resource "aws_sns_topic" "orders" {
  name = "orders-fanout"
}

resource "aws_sns_topic_subscription" "vip" {
  topic_arn            = aws_sns_topic.orders.arn
  protocol             = "sqs"
  endpoint             = aws_sqs_queue.vip.arn
  raw_message_delivery = true
  filter_policy_scope  = "MessageBody"
  filter_policy = jsonencode({
    detail = { total = [{ numeric = [">=", 1000] }] }
  })
}

resource "aws_cloudwatch_event_bus" "orders" {
  name = "orders"
}

resource "aws_cloudwatch_event_rule" "order_created" {
  name           = "order-created"
  event_bus_name = aws_cloudwatch_event_bus.orders.name
  event_pattern = jsonencode({
    source        = ["shop.orders"]
    "detail-type" = ["OrderCreated"]
  })
}

resource "aws_cloudwatch_event_target" "targets" {
  for_each = {
    billing = aws_sqs_queue.billing.arn
    fanout  = aws_sns_topic.orders.arn
  }
  rule           = aws_cloudwatch_event_rule.order_created.name
  event_bus_name = aws_cloudwatch_event_bus.orders.name
  target_id      = each.key
  arn            = each.value
}

# Who may write to each destination (EventBridge -> SQS/SNS, SNS -> SQS)
resource "aws_sqs_queue_policy" "billing" {
  queue_url = aws_sqs_queue.billing.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "events.amazonaws.com" }
      Action    = "sqs:SendMessage"
      Resource  = aws_sqs_queue.billing.arn
      Condition = { ArnEquals = { "aws:SourceArn" = aws_cloudwatch_event_rule.order_created.arn } }
    }]
  })
}

resource "aws_sqs_queue_policy" "vip" {
  queue_url = aws_sqs_queue.vip.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "sns.amazonaws.com" }
      Action    = "sqs:SendMessage"
      Resource  = aws_sqs_queue.vip.arn
      Condition = { ArnEquals = { "aws:SourceArn" = aws_sns_topic.orders.arn } }
    }]
  })
}

resource "aws_sns_topic_policy" "orders" {
  arn = aws_sns_topic.orders.arn
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "events.amazonaws.com" }
      Action    = "sns:Publish"
      Resource  = aws_sns_topic.orders.arn
      Condition = { ArnEquals = { "aws:SourceArn" = aws_cloudwatch_event_rule.order_created.arn } }
    }]
  })
}

The inventory queue follows the same model as vip, without a filter. To close the DLQ loop, add an aws_sqs_queue_redrive_allow_policy with redrivePermission = "byQueue" pointing to the source queue.

Idempotency and at-least-once delivery

SQS standard, SNS, and EventBridge deliver at least once. Duplicates are rare, but they happen: producer retries, a visibility timeout that expires mid-processing, an archive replay. FIFO deduplicates only within its 5-minute window. So the consumer must be idempotent:

  1. Use a business key (order_id), not the message ID. A replay or a new publication generates a different ID for the same order.
  2. Write the key with a conditional write (like the attribute_not_exists in the example) before the side effect, or in the same transaction. For Lambda in Python, the idempotency utility in Powertools for AWS Lambda does this with DynamoDB.
  3. Delete the message only after processing. With Lambda and SQS, use ReportBatchItemFailures to return only the messages that failed.
  4. Monitor the DLQ. A message sitting there is a bug waiting for someone to look. An alarm on the DLQ’s ApproximateNumberOfMessagesVisible metric takes care of it.

Checklist

  • A deliberate choice: SQS for buffering, SNS for fan-out, EventBridge for content-based routing
  • Every consumer queue with a DLQ, maxReceiveCount, and an alarm
  • Visibility timeout longer than the processing time, and 20 s long polling
  • MessageGroupId per customer on multi-tenant standard queues (fair queues)
  • Filter policies with FilterPolicyScope = MessageBody for service events
  • An archive on the bus and a documented replay procedure
  • Idempotent consumers with a business key and a conditional write

Queues, topics, and buses deliver at least once; your code decides whether to process only once.

Get updates on new posts and stay in the loop!