TExcelTAD
Home › AWS Cloud › SQS, SNS and EventBridge

SQS, SNS and EventBridge

When one part of a system calls another directly and waits for it, a slow or failed component drags everything down. Messaging decouples them: the sender drops a message and moves on; the receiver processes it when it can. AWS has three core messaging services:

Service Pattern In one sentence
Amazon SQS Queue (point-to-point) Messages wait in a queue until a consumer pulls and deletes them
Amazon SNS Pub/sub (fan-out) A message published to a topic is pushed to every subscriber
Amazon EventBridge Event bus with rules Events are matched by content and routed to targets

Amazon SQS

bash
aws sqs create-queue --queue-name orders
aws sqs send-message --queue-url https://sqs.eu-west-1.amazonaws.com/123456789012/orders \
    --message-body '{"order_id": 42}'
aws sqs receive-message --queue-url https://sqs.eu-west-1.amazonaws.com/123456789012/orders \
    --wait-time-seconds 10 --max-number-of-messages 1

Sample output of receive-message:

text
{
    "Messages": [{
        "MessageId": "5fea7756-0ea4-451a-a703-a558b933e274",
        "ReceiptHandle": "AQEBzWwaftRI0KuVm4tP+/7q1rGgNqicHq...",
        "MD5OfBody": "1f3b8d3e5e0e0f2c0a6c8f2b5d6e7a90",
        "Body": "{\"order_id\": 42}"
    }]
}

Key behaviour:

  • A received message is hidden for the visibility timeout (default 30 s). If the consumer deletes it in time, it's gone; if not (the consumer crashed), it becomes visible again and another consumer retries it.
  • Standard queues: nearly unlimited throughput, at-least-once delivery, best-effort ordering. FIFO queues: exact ordering per message group and exactly-once processing, with lower throughput.
  • After maxReceiveCount failed attempts a message moves to a dead-letter queue (DLQ) for inspection.

Model: visibility timeout and a dead-letter queue

python · try it yourself
from collections import deque

class Queue:
    def __init__(self, visibility=30, max_receives=3):
        self.visible = deque()
        self.in_flight = {}          # message -> (visible_again_at, receive_count)
        self.receives = {}
        self.dlq = []
        self.visibility, self.max_receives = visibility, max_receives

    def send(self, body):
        self.visible.append(body)

    def tick(self, now):
        for msg, (until, _) in list(self.in_flight.items()):
            if now >= until:
                del self.in_flight[msg]
                if self.receives[msg] >= self.max_receives:
                    self.dlq.append(msg)
                else:
                    self.visible.append(msg)

    def receive(self, now):
        self.tick(now)
        if not self.visible:
            return None
        msg = self.visible.popleft()
        self.receives[msg] = self.receives.get(msg, 0) + 1
        self.in_flight[msg] = (now + self.visibility, self.receives[msg])
        return msg

    def delete(self, msg):
        self.in_flight.pop(msg, None)

q = Queue()
q.send("order-41")
q.send("order-42 (corrupt)")

now = 0
while now <= 150:
    msg = q.receive(now)
    if msg:
        if "corrupt" in msg:
            print(f"t={now:>3} received {msg} (attempt {q.receives[msg]}) -> consumer crashes")
        else:
            q.delete(msg)
            print(f"t={now:>3} received {msg} -> processed and deleted")
    now += 10
q.tick(now)
print("dead-letter queue:", q.dlq)
t=  0 received order-41 -> processed and deleted
t= 10 received order-42 (corrupt) (attempt 1) -> consumer crashes
t= 40 received order-42 (corrupt) (attempt 2) -> consumer crashes
t= 70 received order-42 (corrupt) (attempt 3) -> consumer crashes
dead-letter queue: ['order-42 (corrupt)']

The corrupt message comes back every 30 seconds until it has been received three times, then it lands in the DLQ instead of blocking the queue forever. Consumers must also be idempotent: with at-least-once delivery, the same message can occasionally arrive twice.

Amazon SNS

A topic has subscribers: SQS queues, Lambda functions, HTTPS endpoints, email, SMS, mobile push. Publishing once delivers to all of them. The classic fan-out pattern is SNS → several SQS queues, so each service gets its own durable copy:

python · try it yourself
class Topic:
    def __init__(self, name):
        self.name, self.subscriptions = name, []
    def subscribe(self, endpoint, filter_policy=None):
        self.subscriptions.append((endpoint, filter_policy or {}))
    def publish(self, message, attributes):
        delivered = []
        for endpoint, policy in self.subscriptions:
            if all(attributes.get(k) in allowed for k, allowed in policy.items()):
                endpoint.append(message)
                delivered.append(id(endpoint))
        return len(delivered)

billing_q, shipping_q, fraud_q = [], [], []
orders = Topic("order-events")
orders.subscribe(billing_q)
orders.subscribe(shipping_q, {"type": ["placed"]})
orders.subscribe(fraud_q, {"country": ["XX", "YY"]})

print("deliveries:", orders.publish("order 42 placed", {"type": "placed", "country": "DE"}))
print("deliveries:", orders.publish("order 43 placed", {"type": "placed", "country": "XX"}))
print("deliveries:", orders.publish("order 42 refunded", {"type": "refunded", "country": "DE"}))
print("billing :", billing_q)
print("shipping:", shipping_q)
print("fraud   :", fraud_q)
deliveries: 2
deliveries: 3
deliveries: 1
billing : ['order 42 placed', 'order 43 placed', 'order 42 refunded']
shipping: ['order 42 placed', 'order 43 placed']
fraud   : ['order 43 placed']

Subscription filter policies let each subscriber receive only the messages it cares about.

Amazon EventBridge

EventBridge is a serverless event bus. AWS services (an EC2 state change, an S3 upload), SaaS partners and your own applications put JSON events on a bus; rules with event patterns match events and send them to targets (Lambda, SQS, Step Functions, another bus...). EventBridge Scheduler runs targets on cron-like schedules.

json
{
  "source": ["aws.ec2"],
  "detail-type": ["EC2 Instance State-change Notification"],
  "detail": { "state": ["stopped", "terminated"] }
}
python · try it yourself
def matches(pattern, event):
    for key, expected in pattern.items():
        value = event.get(key)
        if isinstance(expected, dict):
            if not isinstance(value, dict) or not matches(expected, value):
                return False
        elif value not in expected:
            return False
    return True

pattern = {"source": ["aws.ec2"], "detail-type": ["EC2 Instance State-change Notification"],
           "detail": {"state": ["stopped", "terminated"]}}
events = [
    {"source": "aws.ec2", "detail-type": "EC2 Instance State-change Notification",
     "detail": {"instance-id": "i-0abc", "state": "terminated"}},
    {"source": "aws.ec2", "detail-type": "EC2 Instance State-change Notification",
     "detail": {"instance-id": "i-0abc", "state": "running"}},
    {"source": "aws.s3", "detail-type": "Object Created", "detail": {"bucket": {"name": "tad-media"}}},
]
for e in events:
    print(f"{e['source']:<7} {str(e['detail'].get('state', '-')):<10} -> {'send to target' if matches(pattern, e) else 'ignored'}")
aws.ec2 terminated -> send to target
aws.ec2 running    -> ignored
aws.s3  -          -> ignored

Which one?

  • Work that must be processed once by one worker, buffered against spikes → SQS.
  • The same message to many subscribers, push delivery → SNS (often SNS + SQS).
  • Routing events by content between many services, AWS service events, schedules → EventBridge.

Test yourself

A consumer receives an SQS message and crashes before deleting it. What happens?

  1. The message is lost
  2. It becomes visible again after the visibility timeout
  3. It goes straight to the DLQ
  4. SQS deletes it automatically

Which pattern delivers one published message to several SQS queues?

  1. SQS long polling
  2. SNS fan-out
  3. A FIFO queue
  4. A DLQ

Why must SQS standard-queue consumers be idempotent?

  1. Messages are encrypted
  2. Delivery is at-least-once, so duplicates can happen
  3. Messages expire after 1 second
  4. Queues are ordered