# Messaging: SES, SNS and SQS

Send email, fan out notifications and decouple services with queues.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 14. About 20 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/14-messaging

## What you will learn

- Choose a standard or FIFO SQS queue for a workload
- Explain visibility timeout, acknowledgement and at-least-once delivery
- Configure a dead-letter queue without losing the original message
- Explain SNS topics, subscriptions and fan-out
- Recognise SES sandbox limits and EventBridge’s event-bus model

## Queues protect the worker

Before a queue, a web request might do the whole job itself: resize an image, send email, and wait for a report
to finish. A slow dependency kept the user waiting; a burst of requests could overwhelm the worker. Amazon SQS
separates that request from the work. The producer stores a message and continues; a worker receives it, does
the job, then deletes the message after success. In this lesson, you'll compare queues, topics and event routing,
and build a small message path that can be cleaned up.

SQS standard queues are the default choice. They scale broadly and provide at-least-once delivery. That means a
message can appear again, so the handler must be safe to run twice. FIFO queues add ordering and exactly-once
processing support for workloads that need it, with different throughput and naming rules.

```sh
$ aws sqs create-queue \
    --queue-name academy-messaging-demo \
    --attributes '{"VisibilityTimeout":"30"}'
$ aws sqs get-queue-url --queue-name academy-messaging-demo
```

The queue URL is not the ARN. Ask for the ARN when a policy or another service needs it:

```sh
$ aws sqs get-queue-attributes \
    --queue-url "$QUEUE_URL" \
    --attribute-names QueueArn VisibilityTimeout \
    --query 'Attributes'
```

A receive does not acknowledge. The message is hidden for the visibility timeout. Delete is the acknowledgement:

```sh
$ aws sqs send-message --queue-url "$QUEUE_URL" --message-body '{"job":"rebuild-index","attempt":1}'
$ MESSAGE=$(aws sqs receive-message --queue-url "$QUEUE_URL" --wait-time-seconds 10 --query 'Messages[0].{Body:Body,Receipt:ReceiptHandle}' --output json)
$ aws sqs delete-message --queue-url "$QUEUE_URL" --receipt-handle "$RECEIPT_HANDLE"
```

Do not copy the last command until the worker has completed the job. If the worker crashes before deleting, SQS makes
the message visible again. That is a useful failure mode, not a duplicate bug to hide.

This is why a consumer should be idempotent: processing the same message twice must not charge a customer twice
or create two copies of the same record. A worker receives a receipt handle for that delivery. After successful
processing, it deletes the message with that handle. If it fails or never deletes, the visibility timeout ends and
another receive can return the message. Set that timeout long enough for normal processing, but not so long that
failed work sits hidden for too long. For sustained tasks, extend visibility while the job is still running.

> **Figure.** Three panels. Queue, SQS: a producer sends messages to the queue academy-messaging-demo; one worker pulls each message, and a message that fails too many times moves to the dead-letter queue academy-messaging-demo-dlq. Topic, SNS: one published message is copied to every subscriber, for example email, an SQS queue and a Lambda function. Event bus, EventBridge: services publish events; rules match event patterns and route each matching event to its targets.
>
> Queue: one worker does each job. Topic: every subscriber gets a copy. Event bus: rules route events by their content.

## Poison messages go to a DLQ

Some messages fail every time: invalid JSON, a missing object or a code path nobody tested. Retrying them forever
keeps a worker busy. A dead-letter queue stores messages after the source queue reaches maxReceiveCount.

```sh
$ aws sqs create-queue --queue-name academy-messaging-demo-dlq
$ DLQ_ARN=$(aws sqs get-queue-attributes --queue-url "$DLQ_URL" --attribute-names QueueArn --query 'Attributes.QueueArn' --output text)
$ aws sqs set-queue-attributes \
    --queue-url "$QUEUE_URL" \
    --attributes "{\"RedrivePolicy\":\"{\\\"deadLetterTargetArn\\\":\\\"$DLQ_ARN\\\",\\\"maxReceiveCount\\\":\\\"3\\\"}\"}"
```

Inspect the policy before relying on it:

```sh
$ aws sqs get-queue-attributes --queue-url "$QUEUE_URL" --attribute-names RedrivePolicy
```

A DLQ is not a trash can. Give it an owner, longer retention than the source queue, an alert and a repair or
replay process. Redrive only after you understand why the message failed.

The redrive policy connects a source queue to its dead-letter queue and sets how many receives are allowed before
SQS moves a message. That count is a signal that repeated attempts did not solve the problem. Inspect the body,
attributes and consumer logs to find the cause before redriving. Fix the bad data or code first, then move messages
back in a controlled batch. If nobody watches the DLQ or owns replay, it only hides failed work from the main
queue. Keep its retention longer than the source so investigation time is not shorter than normal processing.

> **Delete means acknowledged.** SQS does not know whether your application really finished. It only knows that you deleted the receipt handle. Delete after the side effect succeeds, make the side effect idempotent, and keep the current receipt handle.

> **Video.** [SQS: How to easily create a standard dead letter queue using AWS SQS service - Step by Step tutorial](https://www.youtube.com/watch?v=odrHiZOzhBo) (The Tek Show)

## Topics fan out notifications

SNS is a publish-subscribe service. A publisher sends one notification to a topic. SNS delivers it to each confirmed
subscription. Email is good for a human notification. An SQS subscription is good for durable, retriable work.

```sh
$ TOPIC_ARN=$(aws sns create-topic --name academy-messaging-demo --query TopicArn --output text)
$ aws sns subscribe \
    --topic-arn "$TOPIC_ARN" \
    --protocol email \
    --notification-endpoint elonerajeev@gmail.com
```

The email subscription starts as PendingConfirmation. The recipient must use the link in AWS’s confirmation
message before SNS will deliver notifications. Do not publish a test message to a real address unless you intend to
send it.

For SQS fan-out, the queue policy must allow this topic to call sqs:SendMessage, with a condition limiting the
source ARN to this topic. That policy is permission, not another queue or topic.

> **Video.** [SQS vs SNS: Queue or Topic? Fan-Out Explained (SAA-C03)](https://www.youtube.com/watch?v=9ZjHauArAAY&t=151s) (Lunar Academy)

## Email has a sending contract

SES sends email, but it is not a general-purpose notification queue. In the sandbox, the sender and recipient usually
need verification and the account has low sending limits. DKIM proves domain alignment; it does not make an
unverified recipient safe to mail.

```sh
$ aws sesv2 get-account --query '{Production:ProductionAccessEnabled,SendQuota:SendQuota}'
$ aws sesv2 list-email-identities --query 'EmailIdentities[].IdentityName'
```

Treat bounces and complaints as feedback that changes whether you may keep sending. Store no raw email content in
logs unless there is a clear reason and retention policy.

Think of SES as the delivery service for an email, not a durable work queue. Your application still decides when
to send, handles API errors, and records a safe delivery status. Account verification and sending limits are
separate from DKIM: domain authentication helps receivers verify the sender, but it does not grant permission to
send to an unverified sandbox recipient. A bounce means the destination could not accept the message; a complaint
means a recipient reported it as unwanted. Track these outcomes and stop sending to addresses that should no longer
receive mail. Keep message bodies and personal data out of routine logs.

> **Video.** [AWS SNS Explained: Send Notifications & Trigger Lambda](https://www.youtube.com/watch?v=6RiogPIMrdU&t=523s) (AWS with Jaymit)

## Events need a router

EventBridge is for events that describe something that happened: an object was uploaded, a deployment completed or
an instance changed state. An event bus receives events; rules match their shape and route them to targets.

That is different from SQS, which holds work until a consumer pulls it, and SNS, which pushes a notification to
subscriptions. A system can use all three: EventBridge detects the event, SNS notifies, and SQS protects a worker.

An event bus is the landing place for events. A rule tests selected fields, such as the source and event type, then
sends matching events to one or more targets. This is useful when the producer should report what happened without
knowing every consumer. It is not a replacement for a queue when a worker needs durable backlog and pull-based
processing, or for SNS when a simple topic should fan one notification out to subscribers. Choose the router that
matches the delivery contract, and make sure the target has permission to receive the event and a way to handle
failed delivery.

> **In production.** Set queue encryption and least-privilege policies, use long polling, size visibility timeout for the real work, and alarm on age of the oldest message and DLQ depth. Subscribe email only for human action. Keep retries bounded and idempotent.

> **Video.** [Amazon EventBridge Event Patterns Demo | Custom EventBus](https://www.youtube.com/watch?v=ih61Ia1b7fM) (Cloud With Raj)

## Mission: Build and remove a message path

Create one standard queue, one dead-letter queue and one SNS topic with an email subscription. Inspect the queue ARN, visibility timeout and redrive policy. Do not publish to the email subscription. Delete the subscription, topic and both queues, then verify that each lookup is empty.

- You need: An AWS account, the AWS CLI configured with the anythinkx profile, ap-south-1 and permission to receive one confirmation email
- You'll have: Queue URLs and ARNs, a pending email subscription, a redrive policy, and empty lookups after cleanup

```sh
$ REGION=ap-south-1
$ PROFILE=anythinkx
$ DLQ_URL=$(aws sqs create-queue --profile $PROFILE --region $REGION --queue-name academy-messaging-demo-dlq --query QueueUrl --output text)
$ DLQ_ARN=$(aws sqs get-queue-attributes --profile $PROFILE --region $REGION --queue-url "$DLQ_URL" --attribute-names QueueArn --query 'Attributes.QueueArn' --output text)
$ QUEUE_URL=$(aws sqs create-queue --profile $PROFILE --region $REGION --queue-name academy-messaging-demo --attributes '{"VisibilityTimeout":"30","RedrivePolicy":"{\"deadLetterTargetArn\":\"'$DLQ_ARN'\",\"maxReceiveCount\":\"2\"}"}' --query QueueUrl --output text)
$ TOPIC_ARN=$(aws sns create-topic --profile $PROFILE --region $REGION --name academy-messaging-demo --query TopicArn --output text)
$ SUB_ARN=$(aws sns subscribe --profile $PROFILE --region $REGION --topic-arn "$TOPIC_ARN" --protocol email --notification-endpoint elonerajeev@gmail.com --query SubscriptionArn --output text)
$ aws sqs get-queue-attributes --profile $PROFILE --region $REGION --queue-url "$QUEUE_URL" --attribute-names QueueArn VisibilityTimeout RedrivePolicy --query 'Attributes'
$ aws sns list-subscriptions-by-topic --profile $PROFILE --region $REGION --topic-arn "$TOPIC_ARN" --query 'Subscriptions[].{Protocol:Protocol,Endpoint:Endpoint,Status:SubscriptionArn}'
$ aws sns unsubscribe --profile $PROFILE --region $REGION --subscription-arn "$SUB_ARN" 2>/dev/null || true
$ aws sns delete-topic --profile $PROFILE --region $REGION --topic-arn "$TOPIC_ARN"
$ aws sqs delete-queue --profile $PROFILE --region $REGION --queue-url "$QUEUE_URL"
$ aws sqs delete-queue --profile $PROFILE --region $REGION --queue-url "$DLQ_URL"
$ aws sns list-topics --profile $PROFILE --region $REGION --query "Topics[?contains(TopicArn, 'academy-messaging-demo')]"
$ aws sqs get-queue-url --profile $PROFILE --region $REGION --queue-name academy-messaging-demo
```

The final SQS lookup should return a non-zero error because the queue no longer exists. That is expected cleanup
verification; do not hide errors in a production script.

## Try it

- Create a standard SQS queue and read its URL and ARN.
- Send one JSON message, receive it, and delete it only after processing succeeds.
- Inspect the queue’s visibility timeout and redrive policy.
- Open SNS and inspect a topic’s subscriptions without publishing a test email.
- Check SES identities and whether the account is still in the sandbox.
- Create a DLQ for a short practice queue, then remove both queues.

## Quiz

1. What does SQS visibility timeout prevent?
   - It encrypts the message body
   - **Other consumers immediately receiving a message while one consumer is processing it** (answer)
   - The queue from accepting more messages
   Why: Receive makes a message temporarily invisible. Delete is the acknowledgement after successful processing.

2. Why is SQS described as at-least-once delivery?
   - **A message can be delivered again, so consumers must be idempotent** (answer)
   - Every message is delivered exactly once by default
   - Messages are never retried
   Why: A timeout, network error or failed delete can make a message visible again.

3. What is a dead-letter queue for?
   - Permanently deleting every failed message
   - **Holding messages that exceeded the source queue’s receive limit for inspection or repair** (answer)
   - Making SNS email delivery faster
   Why: A DLQ keeps poison messages from blocking normal work while preserving evidence for diagnosis.

4. What does an SNS topic provide?
   - A durable pull queue for one consumer
   - **A fan-out point that delivers a notification to its subscriptions** (answer)
   - A replacement for IAM policies
   Why: Publishers send once to the topic; SNS delivers to subscribed endpoints such as email, SQS or Lambda.

5. What should you expect from SES in a new AWS account?
   - Production sending to any address immediately
   - **Sandbox limits, verified identities and sending quotas until production access is granted** (answer)
   - A built-in SQS queue for every email
   Why: SES protects new accounts from abuse. Verify identities and request production access deliberately.

## Resources

- [Amazon SQS developer guide](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) (AWS Docs)
- [Amazon SNS developer guide](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) (AWS Docs)
- [Amazon SES developer guide](https://docs.aws.amazon.com/ses/latest/dg/Welcome.html) (AWS Docs)
- [SQS visibility timeout](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) (AWS Docs)
- [EventBridge event buses](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-bus.html) (AWS Docs)
