Sub topic 17
SNS delivery retries and subscription dead-letter queues
This chapter assumes you can create SNS topics and subscriptions, you know how an SQS queue access policy works, and you have read the earlier chapters on SQS dead-letter queues and fan-out. The examples use Python with boto3.
Two kinds of failure, two kinds of dead-letter queue
A message in an SNS-to-SQS design can fail in two places.
- SNS cannot deliver the message to the subscribed endpoint. A subscription dead-letter queue (DLQ) handles this case.
- A consumer receives the message from the queue but cannot process it. An SQS redrive policy handles this case, as covered earlier.
The two mechanisms are independent. A subscription DLQ never sees a message that reached the queue, however many times the consumer fails on it.
| Row | SQS DLQ | SNS subscription DLQ |
|---|---|---|
| Attached to | A source queue | One subscription |
| Trigger | `maxReceiveCount` exceeded | SNS stops trying to deliver |
| Configured by | `RedrivePolicy` queue attribute | `RedrivePolicy` subscription attribute |
| Typical cause | Bad payload, consumer bug | Missing permission, deleted endpoint, endpoint outage |
How SNS retries
SNS applies a delivery policy to each subscription. The policy depends on the protocol.
- SQS, Lambda, and Firehose are AWS-managed endpoints. SNS uses a fixed policy that retries for up to 23 days. You cannot change it.
- HTTP/S endpoints use a policy you can customize. The default makes only a few attempts over a short time.
- Email and SMS deliveries are not retried the same way. Do not rely on a DLQ for them.
SNS separates failures into two groups.
- Client-side errors are not retried. Examples are a deleted endpoint, an HTTP 4xx response, or an SQS queue whose policy does not allow SNS. These go straight to the DLQ if you have configured one.
- Server-side errors are retried according to the policy. Examples are a 5xx response, a timeout, or an endpoint that is briefly unavailable. The message goes to the DLQ only after the retries are used up.
Without a DLQ, a message that exhausts its retries is discarded. You can only find out from the NumberOfNotificationsFailed metric.
Attaching a subscription DLQ
The DLQ must be an SQS queue in the same account and Region as the subscription. A standard topic needs a standard queue, and a FIFO topic needs a FIFO queue. The queue also needs a policy that lets SNS send to it. Without that policy, SNS cannot move failed messages into the DLQ, and they are lost.
import json
import boto3
sqs = boto3.client("sqs")
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
# Queue that receives the fan-out messages
orders_url = sqs.create_queue(QueueName="orders")["QueueUrl"]
orders_arn = sqs.get_queue_attributes(
QueueUrl=orders_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
# Subscription DLQ, kept for the maximum 14 days
dlq_url = sqs.create_queue(
QueueName="orders-subscription-dlq",
Attributes={"MessageRetentionPeriod": "1209600"},
)["QueueUrl"]
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
# Let SNS write failed messages into the DLQ
dlq_policy = {
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Service": "sns.amazonaws.com"},
"Action": "sqs:SendMessage",
"Resource": dlq_arn,
"Condition": {"ArnEquals": {"aws:SourceArn": topic_arn}},
}],
}
sqs.set_queue_attributes(
QueueUrl=dlq_url, Attributes={"Policy": json.dumps(dlq_policy)}
)
# Subscribe the orders queue and attach the DLQ to the subscription
sub_arn = sns.subscribe(
TopicArn=topic_arn,
Protocol="sqs",
Endpoint=orders_arn,
ReturnSubscriptionArn=True,
)["SubscriptionArn"]
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="RedrivePolicy",
AttributeValue=json.dumps({"deadLetterTargetArn": dlq_arn}),
)
print(sub_arn)The orders queue still needs its own access policy for SNS, as in the earlier access-policy chapter. If you forget it, every publish fails with a client error and lands in orders-subscription-dlq. That is a quick way to see the DLQ work.
Tuning retries for HTTP/S endpoints
For HTTP/S subscriptions you can set a DeliveryPolicy with a healthyRetryPolicy. The delay between attempts grows from minDelayTarget to maxDelayTarget (both in seconds) following the backoffFunction, which is linear, arithmetic, geometric, or exponential.
import json
import boto3
sns = boto3.client("sns")
subscription_arn = "arn:aws:sns:us-east-1:123456789012:order-events:EXAMPLE-ID" # replace with your HTTP/S subscription ARN
policy = {
"healthyRetryPolicy": {
"numRetries": 10,
"numNoDelayRetries": 2,
"minDelayTarget": 5,
"maxDelayTarget": 60,
"numMinDelayRetries": 3,
"backoffFunction": "exponential",
}
}
sns.set_subscription_attributes(
SubscriptionArn=subscription_arn,
AttributeName="DeliveryPolicy",
AttributeValue=json.dumps(policy),
)numRetries must be at least the sum of the no-delay, min-delay, and max-delay retry counts. Keep the total retry window shorter than the time your endpoint needs to recover. A very long window delays the moment a message reaches the DLQ.
Working with the DLQ contents
Messages in a subscription DLQ are the original SNS payloads. They carry message attributes that explain the failure, including ERROR_CODE and ERROR_MESSAGE. To reprocess them, fix the cause and then redrive. You can use the SQS console's redrive feature, or read each message and publish it again. Make the consumers idempotent, because a replayed message may already have been partly handled.
Monitoring
Watch these SNS CloudWatch metrics, which are published per topic and per protocol.
NumberOfNotificationsFailedcounts deliveries that failed after retries.NumberOfNotificationsRedrivenToDlqcounts messages moved to a subscription DLQ.NumberOfNotificationsFailedToRedriveToDlqcounts messages SNS could not move to the DLQ. A non-zero value usually means the DLQ policy is wrong.
Also alarm on ApproximateNumberOfMessagesVisible for the DLQ itself. A DLQ nobody watches only hides failures.
Exercise
You subscribe a queue to a topic and attach a subscription DLQ, but you forget to add the SNS access policy to the subscribed queue. What happens to published messages, and where can you see them?
Show answer
SNS gets a client-side error (no permission) on each delivery, so it does not retry. It sends each message to the subscription DLQ, provided the DLQ's own policy allows SNS to write to it. You can read the messages there, and the NumberOfNotificationsFailed and NumberOfNotificationsRedrivenToDlq metrics rise. If the DLQ policy is also missing, the messages are lost and NumberOfNotificationsFailedToRedriveToDlq rises.