Sub topic 16
SNS Delivery Retries, Subscription Dead-Letter Queues, and Lambda Batch Failures
This chapter assumes you can already create an SNS topic, subscribe an SQS queue to it, and read the SQS redrive policy from the earlier chapters. It covers what SNS does when delivery fails, and how Lambda reports which messages in a batch failed.
How SNS retries delivery
SNS delivers a message to each subscription independently. A failure on one subscription does not affect the others.
- SQS and Lambda endpoints: SNS uses an AWS-managed retry policy that you cannot change. It keeps retrying for many days, with growing delays between attempts.
- HTTP/S endpoints: you can set a delivery policy with the number of retries, the delay between them, and a backoff function.
- Errors that cannot succeed: SNS does not retry when the endpoint is gone or access is denied, for example a deleted queue or a queue policy that blocks the topic.
Subscription dead-letter queues
A subscription dead-letter queue (DLQ) is an SQS queue that catches messages SNS gave up on. You attach it to the subscription, not to the topic, through the subscription's RedrivePolicy attribute.
This is a different mechanism from the SQS DLQ. The SQS DLQ catches messages a consumer received but could not process. The subscription DLQ catches messages SNS could not deliver to the endpoint at all.
The following code creates the DLQ, lets SNS write to it, and attaches it to a subscription. It assumes the order-events topic and orders queue from earlier chapters exist.
import json
import boto3
sqs = boto3.client("sqs")
sns = boto3.client("sns")
topic_arn = sns.create_topic(Name="order-events")["TopicArn"]
queue_arn = sqs.get_queue_attributes(
QueueUrl=sqs.get_queue_url(QueueName="orders")["QueueUrl"],
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
# subscribe is idempotent for the same topic, protocol, and endpoint
sub_arn = sns.subscribe(
TopicArn=topic_arn, Protocol="sqs", Endpoint=queue_arn,
ReturnSubscriptionArn=True,
)["SubscriptionArn"]
dlq_url = sqs.create_queue(QueueName="orders-sub-dlq")["QueueUrl"]
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
# SNS must be allowed to write to the 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(policy)})
sns.set_subscription_attributes(
SubscriptionArn=sub_arn,
AttributeName="RedrivePolicy",
AttributeValue=json.dumps({"deadLetterTargetArn": dlq_arn}),
)The DLQ must be in the same account and Region as the subscription. It must also be the same type as the topic: standard for standard, FIFO for FIFO.
Lambda as an SQS consumer
Lambda polls the queue for you and calls your function with a batch of messages. If the function raises an error, the whole batch returns to the queue, including messages that succeeded. Those messages are then processed twice.
Partial batch responses avoid this. Your function returns the IDs of only the failed messages, and Lambda deletes the rest. The handler from the earlier code example does this:
import json
def process(order):
print("processing", order)
def handler(event, context):
failures = []
for record in event["Records"]:
try:
process(json.loads(record["body"]))
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}You must enable this on the event source mapping:
import boto3
lam = boto3.client("lambda")
lam.create_event_source_mapping(
EventSourceArn="arn:aws:sqs:us-east-1:123456789012:orders",
FunctionName="process-orders",
BatchSize=10,
FunctionResponseTypes=["ReportBatchItemFailures"],
)Common errors
- Without
ReportBatchItemFailures, the returnedbatchItemFailureslist is ignored. - Set the queue's visibility timeout to at least six times the function timeout. A shorter value lets messages reappear while the function is still working on them.
- Failed messages count toward
maxReceiveCount, so keep a redrive policy on the queue. Otherwise a poison message retries until retention expires. - Keep consumers idempotent. Retries still deliver duplicates.
Exercise
A Lambda function processes a batch of 10 messages. Message 3 fails, and the function returns an empty batchItemFailures list. What happens to message 3?
Show answer
Lambda treats an empty list as full success and deletes all 10 messages, so message 3 is lost. The function must include message 3's messageId in batchItemFailures so it returns to the queue.