Symptom
aws sns publish returns a MessageId, so the publisher looks fine. But the subscriber gets nothing: the SQS queue stays empty, the Lambda function has no invocations, or the webhook never receives a POST. CloudWatch alarms that notify through SNS may also stop paging people without any error showing up.
A MessageId only tells you that SNS accepted the message. Delivery to each subscription happens later and fails on its own. Use the metrics to work out which kind of failure you have before you change anything.
TOPIC_ARN=arn:aws:sns:eu-west-1:111122223333:orders-events
TOPIC=orders-events
Step 1: read the topic metrics
SNS publishes per-topic metrics in the AWS/SNS namespace, with the TopicName dimension.
for m in NumberOfMessagesPublished NumberOfNotificationsDelivered NumberOfNotificationsFailed \
NumberOfNotificationsFilteredOut NumberOfNotificationsFilteredOut-InvalidAttributes \
NumberOfNotificationsFilteredOut-InvalidMessageBody NumberOfNotificationsRedrivenToDlq; do
printf "%-55s " "$m"
aws cloudwatch get-metric-statistics --namespace AWS/SNS --metric-name "$m" \
--dimensions Name=TopicName,Value=$TOPIC \
--start-time "$(date -u -d '-3 hours' +%FT%TZ)" --end-time "$(date -u +%FT%TZ)" \
--period 10800 --statistics Sum --query "Datapoints[0].Sum" --output text
done
| What the metrics show | Meaning | Go to |
|---|---|---|
Published > 0, Delivered and Failed both 0 | No confirmed subscription matched the message | Step 2 |
FilteredOut* > 0 | A filter policy dropped the messages | Step 3 |
Failed > 0 | SNS tried to deliver and the endpoint refused it | Steps 4 and 5 |
Delivered > 0 but the consumer saw nothing | Delivery worked. Check the consumer side (Step 6) | Step 6 |
Published is 0 | The publisher is sending to another topic, Region or account, or is failing | Check publisher logs and CloudTrail Publish events |
Tip
These metrics are totals for the whole topic. With several subscriptions on one topic, use delivery status logs (Step 4) to see which subscription failed.
Step 2: check that the subscription exists and is confirmed
aws sns list-subscriptions-by-topic --topic-arn $TOPIC_ARN \
--query "Subscriptions[].{proto:Protocol,endpoint:Endpoint,arn:SubscriptionArn}" --output table
A SubscriptionArn of PendingConfirmation means nobody confirmed it. SNS does not deliver to it. Email and HTTP/S endpoints have to confirm. Same-account SQS and Lambda subscriptions are confirmed automatically, but a cross-account SQS subscription created by the topic owner needs the queue owner to confirm it.
For HTTP/S endpoints, the endpoint must handle the SubscriptionConfirmation message and visit the SubscribeURL in it. If the endpoint missed it, delete the subscription and subscribe again while you watch the endpoint logs.
Look at the subscription attributes too:
SUB_ARN=arn:aws:sns:eu-west-1:111122223333:orders-events:7f1c...
aws sns get-subscription-attributes --subscription-arn $SUB_ARN \
--query "Attributes.{pending:PendingConfirmation,raw:RawMessageDelivery,filter:FilterPolicy,scope:FilterPolicyScope,dlq:RedrivePolicy}"
Step 3: fix filter policies that drop everything
A subscription with a FilterPolicy only gets messages that match it. Most "SNS lost my messages" tickets come down to filtering.
| Cause | Metric that rises | Fix |
|---|---|---|
| Policy filters on message attributes, but the publisher puts the field in the body | FilteredOut-NoMessageAttributes or FilteredOut | Set FilterPolicyScope to MessageBody, or publish the attribute |
FilterPolicyScope is MessageBody but the body isn't valid JSON | FilteredOut-InvalidMessageBody | Publish JSON, or filter on attributes instead |
Attribute sent as String but the policy uses a numeric match | FilteredOut-InvalidAttributes or FilteredOut | Send DataType=Number, or change the policy |
Case or value mismatch ("Created" vs "created") | FilteredOut | String matching is exact. Align the values |
| Policy key names a nested field but scope is attributes | FilteredOut | Nested keys only work with MessageBody scope |
Test a filter by publishing a message that you know should match:
aws sns publish --topic-arn $TOPIC_ARN \
--message '{"orderId":"test-1","eventType":"created"}' \
--message-attributes '{"eventType":{"DataType":"String","StringValue":"created"}}'
Change the policy or its scope:
aws sns set-subscription-attributes --subscription-arn $SUB_ARN \
--attribute-name FilterPolicyScope --attribute-value MessageBody
aws sns set-subscription-attributes --subscription-arn $SUB_ARN \
--attribute-name FilterPolicy --attribute-value '{"eventType":["created","updated"]}'
Warning
Filter policy changes can take several minutes to take effect. Messages published in that window are filtered with the old policy. If you widen a policy, you don't get back any messages that were already filtered out. Republish them from the source system.
Step 4: turn on delivery status logging
To see why delivery to SQS, Lambda, HTTP/S or Firehose failed, enable delivery status logging on the topic. You need an IAM role that SNS can assume (trust sns.amazonaws.com) with logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents and logs:PutMetricFilter.
ROLE=arn:aws:iam::111122223333:role/SNSDeliveryStatusLogging
for p in SQS Lambda HTTP; do
aws sns set-topic-attributes --topic-arn $TOPIC_ARN --attribute-name ${p}FailureFeedbackRoleArn --attribute-value $ROLE
aws sns set-topic-attributes --topic-arn $TOPIC_ARN --attribute-name ${p}SuccessFeedbackRoleArn --attribute-value $ROLE
aws sns set-topic-attributes --topic-arn $TOPIC_ARN --attribute-name ${p}SuccessFeedbackSampleRate --attribute-value 10
done
Failures go to the log group sns/<region>/<account-id>/<topic-name>/Failure. Successes go to the same name without /Failure.
aws logs filter-log-events \
--log-group-name sns/eu-west-1/111122223333/$TOPIC/Failure \
--start-time $(( $(date +%s) - 3600 ))000 \
--query "events[].message" --output text | head -20
Each entry has delivery.statusCode, delivery.providerResponse and the destination. Use the provider response to pick a fix in Step 5.
Step 5: map delivery failures to fixes
| Subscriber | Typical provider response | Cause | Fix |
|---|---|---|---|
| SQS | Access denied / not authorized to sqs:SendMessage | Queue policy doesn't allow the topic | Add a queue policy statement (below) |
| SQS (encrypted) | KMS access denied, key disabled | Queue uses the AWS managed aws/sqs key, or a customer managed key whose key policy leaves out SNS | Use a customer managed key that grants sns.amazonaws.com kms:GenerateDataKey and kms:Decrypt |
| SQS FIFO | Subscription rejected | Standard topic with a FIFO queue | FIFO queues need a FIFO topic |
| Lambda | Not authorized to invoke | Function resource policy is missing | aws lambda add-permission (below) |
| HTTP/S | 4xx/5xx, timeout, TLS errors | Endpoint down, auth, invalid certificate chain | Fix the endpoint. Tune DeliveryPolicy retries |
| Any (topic encrypted) | Publisher gets KMS.AccessDeniedException | Publisher or AWS service can't use the topic key | Grant the key to the publisher principal |
Queue policy for an SNS subscription:
QUEUE_URL=https://sqs.eu-west-1.amazonaws.com/111122223333/orders-worker
QUEUE_ARN=arn:aws:sqs:eu-west-1:111122223333:orders-worker
cat > policy.json <<EOF
{"Policy":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"sns.amazonaws.com\"},\"Action\":\"sqs:SendMessage\",\"Resource\":\"$QUEUE_ARN\",\"Condition\":{\"ArnEquals\":{\"aws:SourceArn\":\"$TOPIC_ARN\"}}}]}"}
EOF
aws sqs set-queue-attributes --queue-url $QUEUE_URL --attributes file://policy.json
Caution
set-queue-attributeswithPolicyreplaces the whole queue policy. Read the current policy withaws sqs get-queue-attributes --queue-url $QUEUE_URL --attribute-names Policyfirst and merge the statement into it. Otherwise you cut off other producers.
Lambda permission:
aws lambda add-permission --function-name orders-handler \
--statement-id sns-orders-events --action lambda:InvokeFunction \
--principal sns.amazonaws.com --source-arn $TOPIC_ARN
CloudWatch alarms that stopped notifying
If an alarm moves to ALARM but nobody gets paged, check the topic encryption. CloudWatch alarms can't publish to a topic encrypted with the AWS managed aws/sns key. Use a customer managed key whose key policy allows cloudwatch.amazonaws.com to call kms:Decrypt and kms:GenerateDataKey. The alarm history shows the failed action:
aws cloudwatch describe-alarm-history --alarm-name prod-api-5xx \
--history-item-type Action --max-records 5 --query "AlarmHistoryItems[].HistorySummary"
Step 6: delivered but the consumer saw nothing
If NumberOfNotificationsDelivered is rising:
- SQS: another consumer, or a Lambda event source mapping, may be reading and deleting the messages. Check
NumberOfMessagesReceivedon the queue. - Raw message delivery: if
RawMessageDeliveryisfalse, the consumer gets the SNS JSON envelope. A parser that expects your own payload may fail and throw the message away. Turn on raw delivery, or unwrap theMessagefield. - Lambda: check the function's
Errorsmetric and its log group. SNS invokes Lambda asynchronously, so failures are retried and then sent to the function's on-failure destination, if one is set.
Prevent it next time
- Attach a dead-letter queue to each critical subscription, so failed deliveries are kept and not dropped:
aws sns set-subscription-attributes --subscription-arn $SUB_ARN \
--attribute-name RedrivePolicy \
--attribute-value '{"deadLetterTargetArn":"arn:aws:sqs:eu-west-1:111122223333:orders-events-dlq"}'
The DLQ needs its own queue policy that allows sns.amazonaws.com to send, and it must be the same type as the topic (standard or FIFO). Alarm on NumberOfNotificationsRedrivenToDlq and NumberOfNotificationsFailedToRedriveToDlq.
- Alarm on
NumberOfNotificationsFailed> 0 and onNumberOfNotificationsFilteredOut-InvalidAttributesfor every production topic. - Keep delivery status logging on for failures, with a log retention period set.
- Keep filter policies and queue policies in infrastructure code, and have a test publish a matching message after each deploy.
- Use customer managed KMS keys for topics and queues that AWS services publish to.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get