

# Amazon SNS dead-letter queues
<a name="sns-dead-letter-queues"></a>

A dead-letter queue is an Amazon SQS queue that an Amazon SNS subscription can target for messages that can't be delivered to subscribers successfully. Messages that can't be delivered due to client errors or server errors are held in the dead-letter queue for further analysis or reprocessing. For more information, see [Configuring an Amazon SNS dead-letter queue for a subscription](sns-configure-dead-letter-queue.md) and [Amazon SNS message delivery retries](sns-message-delivery-retries.md).

**Note**  
The Amazon SNS subscription and Amazon SQS queue must be under the same AWS account and Region.
For a [FIFO topic](sns-fifo-topics.md), you can use an Amazon SQS queue as a dead-letter queue for the Amazon SNS subscription. FIFO topic subscriptions use FIFO queues, and standard topic subscriptions use standard queues.
To use an encrypted Amazon SQS queue as a dead-letter queue, you must use a custom KMS with a key policy that grants the Amazon SNS service principal access to AWS KMS API actions. For more information, see [Securing Amazon SNS data with server-side encryption](sns-server-side-encryption.md) in this guide and [Protecting Amazon SQS Data Using Server-Side Encryption (SSE) and AWS KMS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-server-side-encryption.html) in the *Amazon Simple Queue Service Developer Guide*.

## Why do message deliveries fail?
<a name="why-do-message-deliveries-fail"></a>

In general, message delivery fails when Amazon SNS can't access a subscribed endpoint due to a *client-side* or *server-side error*. When Amazon SNS receives a client-side error, or continues to receive a server-side error for a message beyond the number of retries specified by the corresponding retry policy, Amazon SNS discards the message—unless a dead-letter queue is attached to the subscription. Failed deliveries don't change the status of your subscriptions. For more information, see [Amazon SNS message delivery retries](sns-message-delivery-retries.md).

### Client-side errors
<a name="client-side-errors"></a>

Client-side errors can happen when Amazon SNS has stale subscription metadata. These errors commonly occur when an owner deletes the endpoint (for example, a Lambda function subscribed to an Amazon SNS topic) or when an owner changes the policy attached to the subscribed endpoint in a way that prevents Amazon SNS from delivering messages to the endpoint. Amazon SNS doesn't retry the message delivery that fails as a result of a client-side error.

### Server-side errors
<a name="server-side-errors"></a>

Server-side errors can happen when the system responsible for the subscribed endpoint becomes unavailable or returns an exception that indicates that it can't process a valid request from Amazon SNS. When server-side errors occur, Amazon SNS retries the failed deliveries using either a linear or exponential backoff function. For server-side errors caused by AWS managed endpoints backed by Amazon SQS or AWS Lambda, Amazon SNS retries delivery up to 100,015 times, over 23 days.

Customer managed endpoints (such as HTTP, SMTP, SMS, or mobile push) can also cause server-side errors. Amazon SNS retries delivery to these types of endpoints as well. While HTTP endpoints support customer-defined retry policies, Amazon SNS sets an internal delivery retry policy to 50 times over 6 hours, for SMTP, SMS, and mobile push endpoints.

## How do dead-letter queues work?
<a name="how-do-dead-letter-queues-work"></a>

A dead-letter queue is attached to an Amazon SNS subscription (rather than a topic) because message deliveries happen at the subscription level. This lets you identify the original target endpoint for each message more easily.

A dead-letter queue associated with an Amazon SNS subscription is an ordinary Amazon SQS queue. For more information about the message retention period, see [Quotas Related to Messages](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-quotas.html#quotas-messages) in the *Amazon Simple Queue Service Developer Guide*. You can change the message retention period using the Amazon SQS `[SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)` API action. To make your applications more resilient, we recommend setting the maximum retention period for dead-letter queues to 14 days.

## How are messages moved into a dead-letter queue?
<a name="how-messages-moved-into-dead-letter-queue"></a>

Your messages are moved into a dead-letter queue using a *redrive policy*. A redrive policy is a JSON object that refers to the ARN of the dead-letter queue. The `deadLetterTargetArn` attribute specifies the ARN. The ARN must point to an Amazon SQS queue in the same AWS account and Region as your Amazon SNS subscription. For more information, see [Configuring an Amazon SNS dead-letter queue for a subscription](sns-configure-dead-letter-queue.md). 

The following JSON object is a sample redrive policy, attached to an SNS subscription.

```
{
  "deadLetterTargetArn": "arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue"
}
```

## How can I move messages out of a dead-letter queue?
<a name="how-to-move-messages-out-of-dead-letter-queue"></a>

You can move messages out of a dead-letter queue in two ways:
+ **Avoid writing Amazon SQS consumer logic** – Set your dead-letter queue as an event source to the Lambda function to drain your dead-letter queue.
+ **Write Amazon SQS consumer logic** – Use the Amazon SQS API, AWS SDK, or AWS CLI to write custom consumer logic for polling, processing, and deleting the messages in the dead-letter queue.

## How can I monitor and log dead-letter queues?
<a name="how-to-monitor-log-dead-letter-queues"></a>

You can use Amazon CloudWatch metrics to monitor dead-letter queues associated with your Amazon SNS subscriptions. All Amazon SQS queues emit CloudWatch metrics at one-minute intervals. For more information, see [Available CloudWatch metrics for Amazon SQS](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-available-cloudwatch-metrics.html) in the *Amazon Simple Queue Service Developer Guide*. All Amazon SNS subscriptions with dead-letter queues also emit CloudWatch metrics. For more information, see [Monitoring Amazon SNS topics using CloudWatch](sns-monitoring-using-cloudwatch.md).

To be notified of activity in your dead-letter queues, you can use CloudWatch metrics and alarms. Setting up an alarm for the `NumberOfMessagesSent` metric is not suitable because this metric does not capture messages sent to a DLQ as a result of failed processing attempts. Instead, use the `ApproximateNumberOfMessagesVisible` metric, which captures all messages currently available in the DLQ, including those moved due to processing failures.

**Example CloudWatch alarm setup**

1. Create a [CloudWatch alarm](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ConsoleAlarms.html) for the `ApproximateNumberOfMessagesVisible` metric.

1. Set the alarm threshold to **1** (or another appropriate value based on your expectations and DLQ traffic).

1. Specify an Amazon SNS **topic** to be notified when the alarm goes off. This Amazon SNS topic can deliver your alarm notification to any endpoint type (such as an email address, phone number, or mobile pager app).

You can use CloudWatch Logs to investigate the exceptions that cause any Amazon SNS deliveries to fail and for messages to be sent to dead-letter queues. Amazon SNS can log both successful and failed deliveries in CloudWatch. For more information, see [Amazon SNS mobile app attributes](sns-msg-status.md).

# Configuring an Amazon SNS dead-letter queue for a subscription
<a name="sns-configure-dead-letter-queue"></a>

A dead-letter queue is an Amazon SQS queue that an Amazon SNS subscription can target for messages that can't be delivered to subscribers successfully. Messages that can't be delivered due to client errors or server errors are held in the dead-letter queue for further analysis or reprocessing. For more information, see [Amazon SNS dead-letter queues](sns-dead-letter-queues.md) and [Amazon SNS message delivery retries](sns-message-delivery-retries.md).

This page shows how you can use the AWS Management Console, an AWS SDK, the AWS CLI, and CloudFormation to configure a dead-letter queue for an Amazon SNS subscription.

**Note**  
For a [FIFO topic](sns-fifo-topics.md), you can use an Amazon SQS queue as a dead-letter queue for the Amazon SNS subscription. FIFO topic subscriptions use FIFO queues, and standard topic subscriptions use standard queues.

## Prerequisites
<a name="dead-letter-queue-prerequisites"></a>

Before you configure a dead-letter queue, complete the following prerequisites:

1. [Create an Amazon SNS topic](sns-create-topic.md) named `MyTopic`.

1. [Create an Amazon SQS queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-create-queue.html) named `MyEndpoint`, to be used as the endpoint for the Amazon SNS subscription.

1. (Skip for CloudFormation) [Subscribe the queue to the topic](sns-sqs-as-subscriber.md).

1. [Create another Amazon SQS queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-create-queue.html) named `MyDeadLetterQueue`, to be used as the dead-letter queue for the Amazon SNS subscription.

1. To give Amazon SNS principal access to the Amazon SQS API action, set the following queue policy for `MyDeadLetterQueue`.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Allow",
         "Principal": {
           "Service": "sns.amazonaws.com"
         },
         "Action": "SQS:SendMessage",
         "Resource": "arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue",
         "Condition": {
           "ArnEquals": {
             "aws:SourceArn": "arn:aws:sns:us-east-2:123456789012:MyTopic"
           }
         }
       }
     ]
   }
   ```

------

## To configure a dead-letter queue for an Amazon SNS subscription using the AWS Management Console
<a name="configure-dead-letter-queue-aws-console"></a>

Before your begin this tutorial, make sure you complete the [prerequisites](#dead-letter-queue-prerequisites).

1. Sign in to the [Amazon SQS console](https://console.aws.amazon.com/sqs/).

1. [Create an Amazon SQS queue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-create-queue.html) or use an existing queue and note the ARN of the queue on the **Details** tab of the queue, for example:

   ```
   arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue
   ```

1. Sign in to the [Amazon SNS console](https://console.aws.amazon.com/sns/home).

1. On the navigation panel, choose **Subscriptions**.

1. On the **Subscriptions** page, select an existing subscription and then choose **Edit**.

1. On the **Edit *1234a567-bc89-012d-3e45-6fg7h890123i*** page, expand the **Redrive policy (dead-letter queue)** section, and then do the following:

   1. Choose **Enabled**.

   1. Specify the ARN of an Amazon SQS queue.

1. Choose **Save changes**.

   Your subscription is configured to use a dead-letter queue.

## To configure a dead-letter queue for an Amazon SNS subscription using an AWS SDK
<a name="configure-dead-letter-queue-aws-sdk"></a>

Before you run this example, make sure that you complete the [prerequisites](#dead-letter-queue-prerequisites).

To use an AWS SDK, you must configure it with your credentials. For more information, see [The shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html) in the *AWS SDKs and Tools Reference Guide*.

The following code example shows how to use `SetSubscriptionAttributesRedrivePolicy`.

------
#### [ Java ]

**SDK for Java 1.x**  
 There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/java/example_code/sns#code-examples). 

```
// Specify the ARN of the Amazon SNS subscription.
String subscriptionArn =
    "arn:aws:sns:us-east-2:123456789012:MyEndpoint:1234a567-bc89-012d-3e45-6fg7h890123i";

// Specify the ARN of the Amazon SQS queue to use as a dead-letter queue.
String redrivePolicy =
    "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue\"}";

// Set the specified Amazon SQS queue as a dead-letter queue
// of the specified Amazon SNS subscription by setting the RedrivePolicy attribute.
SetSubscriptionAttributesRequest request = new SetSubscriptionAttributesRequest()
    .withSubscriptionArn(subscriptionArn)
    .withAttributeName("RedrivePolicy")
    .withAttributeValue(redrivePolicy);
sns.setSubscriptionAttributes(request);
```

------

## To configure a dead-letter queue for an Amazon SNS subscription using the AWS CLI
<a name="configure-dead-letter-queue-aws-cli"></a>

Before your begin this tutorial, make sure you complete the [prerequisites](#dead-letter-queue-prerequisites).

1. Install and configure the AWS CLI. For more information, see the [https://docs.aws.amazon.com/cli/latest/userguide/](https://docs.aws.amazon.com/cli/latest/userguide/).

1. Use the following command.

   ```
   aws sns set-subscription-attributes \
   --subscription-arn arn:aws:sns:us-east-2:123456789012:MyEndpoint:1234a567-bc89-012d-3e45-6fg7h890123i
   --attribute-name RedrivePolicy
   --attribute-value "{\"deadLetterTargetArn\": \"arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue\"}"
   ```

## To configure a dead-letter queue for an Amazon SNS subscription using CloudFormation
<a name="configure-dead-letter-queue-aws-cloudformation"></a>

Before your begin this tutorial, make sure you complete the [prerequisites](#dead-letter-queue-prerequisites).

1. Copy the following JSON code to a file named `MyDeadLetterQueue.json`.

   ```
   {
     "Resources": {
       "mySubscription": {
         "Type" : "AWS::SNS::Subscription",
         "Properties" : {
           "Protocol": "sqs",
           "Endpoint": "arn:aws:sqs:us-east-2:123456789012:MyEndpoint",
           "TopicArn": "arn:aws:sns:us-east-2:123456789012:MyTopic",
           "RedrivePolicy": {
             "deadLetterTargetArn":
               "arn:aws:sqs:us-east-2:123456789012:MyDeadLetterQueue"
           }
         }
       }
     }
   }
   ```

1. Sign in to the [CloudFormation console](https://console.aws.amazon.com/cloudformation/).

1. On the **Select Template** page, choose **Upload a template to Amazon S3**, choose your `MyDeadLetterQueue.json` file, and then choose **Next**. 

1. On the **Specify Details** page, enter `MyDeadLetterQueue` for **Stack Name**, and then choose **Next**. 

1. On the **Options** page, choose **Next**.

1. On the **Review** page, choose **Create**.

   CloudFormation begins to create the `MyDeadLetterQueue` stack and displays the **CREATE\$1IN\$1PROGRESS** status. When the process is complete, CloudFormation displays the **CREATE\$1COMPLETE** status.