Amazon SNS message delivery status - Amazon Simple Notification Service

Amazon SNS message delivery status

Amazon SNS provides support to log the delivery status of notification messages sent to topics with the following Amazon SNS endpoints:

  • HTTP

  • Amazon Data Firehose

  • AWS Lambda

  • Platform application endpoint

  • Amazon Simple Queue Service

After you configure the message delivery status attributes, log entries are sent to CloudWatch Logs for messages sent to topic subscribers. Logging message delivery status helps provide better operational insight, such as the following:

  • Knowing whether a message was delivered to the Amazon SNS endpoint.

  • Identifying the response sent from the Amazon SNS endpoint to Amazon SNS.

  • Determining the message dwell time (the time between the publish timestamp and just before handing off to an Amazon SNS endpoint).

To configure topic attributes for message delivery status, you can use the AWS Management Console, AWS software development kits (SDKs), query API, or AWS CloudFormation.

Configuring delivery status logging using the AWS Management Console

  1. Sign in to the Amazon SNS console.

  2. On the navigation panel, choose Topics.

  3. On the Topics page, choose a topic and then choose Edit.

  4. On the Edit MyTopic page, expand the Delivery status logging section.

  5. Choose the protocol for which you want to log delivery status; for example AWS Lambda.

  6. Enter the Success sample rate (the percentage of successful messages for which you want to receive CloudWatch Logs.

  7. In the IAM roles section, do one of the following:

    • To choose an existing service role from your account, choose Use existing service role and then specify IAM roles for successful and failed deliveries.

    • To create a new service role in your account, choose Create new service role, choose Create new roles to define the IAM roles for successful and failed deliveries in the IAM console.

      To give Amazon SNS write access to use CloudWatch Logs on your behalf, choose Allow.

  8. Choose Save changes.

    You can now view and parse the CloudWatch Logs containing the message delivery status. For more information about using CloudWatch, see the CloudWatch Documentation.

Configuring delivery status logging using the AWS SDKs

The AWS SDKs provide APIs in several languages for using message delivery status attributes with Amazon SNS.

Topic attributes

You can use the following topic attribute name values for message delivery status:

HTTP

  • HTTPSuccessFeedbackRoleArn – Indicates successful message delivery status for an Amazon SNS topic that is subscribed to an HTTP endpoint.

  • HTTPSuccessFeedbackSampleRate – Indicates percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an HTTP endpoint.

  • HTTPFailureFeedbackRoleArn – Indicates failed message delivery status for an Amazon SNS topic that is subscribed to an HTTP endpoint.

Amazon Data Firehose

  • FirehoseSuccessFeedbackRoleArn – Indicates successful message delivery status for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint.

  • FirehoseSuccessFeedbackSampleRate – Indicates percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint.

  • FirehoseFailureFeedbackRoleArn – Indicates failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon Kinesis Data Firehose endpoint.

AWS Lambda

  • LambdaSuccessFeedbackRoleArn – Indicates successful message delivery status for an Amazon SNS topic that is subscribed to an Lambda endpoint.

  • LambdaSuccessFeedbackSampleRate – Indicates percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Lambda endpoint.

  • LambdaFailureFeedbackRoleArn – Indicates failed message delivery status for an Amazon SNS topic that is subscribed to an Lambda endpoint.

Platform application endpoint

  • ApplicationSuccessFeedbackRoleArn – Indicates successful message delivery status for an Amazon SNS topic that is subscribed to an AWS application endpoint.

  • ApplicationSuccessFeedbackSampleRate – Indicates percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an AWS application endpoint.

  • ApplicationFailureFeedbackRoleArn – Indicates failed message delivery status for an Amazon SNS topic that is subscribed to an AWS application endpoint.

    Note

    In addition to being able to configure topic attributes for message delivery status of notification messages sent to Amazon SNS application endpoints, you can also configure application attributes for the delivery status of push notification messages sent to push notification services. For more information, see Using Amazon SNS Application Attributes for Message Delivery Status.

Amazon SQS

  • SQSSuccessFeedbackRoleArn – Indicates successful message delivery status for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint.

  • SQSSuccessFeedbackSampleRate – Indicates percentage of successful messages to sample for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint.

  • SQSFailureFeedbackRoleArn – Indicates failed message delivery status for an Amazon SNS topic that is subscribed to an Amazon SQS endpoint.

Note

The <ENDPOINT>SuccessFeedbackRoleArn and <ENDPOINT>FailureFeedbackRoleArn attributes are used to give Amazon SNS write access to use CloudWatch Logs on your behalf. The <ENDPOINT>SuccessFeedbackSampleRate attribute is for specifying the sample rate percentage (0-100) of successfully delivered messages. After you configure the <ENDPOINT>FailureFeedbackRoleArn attribute, then all failed message deliveries generate CloudWatch Logs.

AWS SDK examples to configure topic attributes

The following code examples show how to set Amazon SNS topic attributes.

CLI
AWS CLI

To set an attribute for a topic

The following set-topic-attributes example sets the DisplayName attribute for the specified topic.

aws sns set-topic-attributes \ --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \ --attribute-name DisplayName \ --attribute-value MyTopicDisplayName

This command produces no output.

Java
SDK for Java 2.x
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.SetTopicAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SetTopicAttributes { public static void main(String[] args) { final String usage = """ Usage: <attribute> <topicArn> <value> Where: attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy . topicArn - The ARN of the topic.\s value - The value for the attribute. """; if (args.length < 3) { System.out.println(usage); System.exit(1); } String attribute = args[0]; String topicArn = args[1]; String value = args[2]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setTopAttr(snsClient, attribute, topicArn, value); snsClient.close(); } public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) { try { SetTopicAttributesRequest request = SetTopicAttributesRequest.builder() .attributeName(attribute) .attributeValue(value) .topicArn(topicArn) .build(); SetTopicAttributesResponse result = snsClient.setTopicAttributes(request); System.out.println( "\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.topicArn() + " updated " + request.attributeName() + " to " + request.attributeValue()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
JavaScript
SDK for JavaScript (v3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

Create the client in a separate module and export it.

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

Import the SDK and client modules and call the API.

import { SetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const setTopicAttributes = async ( topicArn = "TOPIC_ARN", attributeName = "DisplayName", attributeValue = "Test Topic", ) => { const response = await snsClient.send( new SetTopicAttributesCommand({ AttributeName: attributeName, AttributeValue: attributeValue, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; };
Kotlin
SDK for Kotlin
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

suspend fun setTopAttr(attribute: String?, topicArnVal: String?, value: String?) { val request = SetTopicAttributesRequest { attributeName = attribute attributeValue = value topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.setTopicAttributes(request) println("Topic ${request.topicArn} was updated.") } }
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Configure the message delivery status attributes for an Amazon SNS Topic. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $attribute = 'Policy | DisplayName | DeliveryPolicy'; $value = 'First Topic'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->setTopicAttributes([ 'AttributeName' => $attribute, 'AttributeValue' => $value, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

# Service class to enable an SNS resource with a specified policy class SnsResourceEnabler # Initializes the SnsResourceEnabler with an SNS resource client # # @param sns_resource [Aws::SNS::Resource] The SNS resource client def initialize(sns_resource) @sns_resource = sns_resource @logger = Logger.new($stdout) end # Sets a policy on a specified SNS topic # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource to include in the policy # @param policy_name [String] The name of the policy attribute to set def enable_resource(topic_arn, resource_arn, policy_name) policy = generate_policy(topic_arn, resource_arn) topic = @sns_resource.topic(topic_arn) topic.set_attributes({ attribute_name: policy_name, attribute_value: policy }) @logger.info("Policy #{policy_name} set successfully for topic #{topic_arn}.") rescue Aws::SNS::Errors::ServiceError => e @logger.error("Failed to set policy: #{e.message}") end private # Generates a policy string with dynamic resource ARNs # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource # @return [String] The policy as a JSON string def generate_policy(topic_arn, resource_arn) { Version: "2008-10-17", Id: "__default_policy_ID", Statement: [{ Sid: "__default_statement_ID", Effect: "Allow", Principal: { "AWS": "*" }, Action: ["SNS:Publish"], Resource: topic_arn, Condition: { ArnEquals: { "AWS:SourceArn": resource_arn } } }] }.to_json end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = "MY_TOPIC_ARN" # Should be replaced with a real topic ARN resource_arn = "MY_RESOURCE_ARN" # Should be replaced with a real resource ARN policy_name = "POLICY_NAME" # Typically, this is "Policy" sns_resource = Aws::SNS::Resource.new enabler = SnsResourceEnabler.new(sns_resource) enabler.enable_resource(topic_arn, resource_arn, policy_name) end
SAP ABAP
SDK for SAP ABAP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

TRY. lo_sns->settopicattributes( iv_topicarn = iv_topic_arn iv_attributename = iv_attribute_name iv_attributevalue = iv_attribute_value ). MESSAGE 'Set/updated SNS topic attributes.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY.

Configuring delivery status logging using AWS CloudFormation

To configure DeliveryStatusLogging using AWS CloudFormation, use a JSON or YAML template to create an AWS CloudFormation stack. For more information, see the DeliveryStatusLogging property of the AWS::SNS::Topic resource in the AWS CloudFormation User Guide. Below are examples of AWS CloudFormation templates in JSON and YAML to create a new topic or update an existing topic with all DeliveryStatusLogging attributes for the Amazon SQS protocol.

JSON
"Resources": { "MySNSTopic" : { "Type" : "AWS::SNS::Topic", "Properties" : { "TopicName" : "TestTopic", "DisplayName" : "TEST", "SignatureVersion" : "2", "DeliveryStatusLogging" : [{ "Protocol": "sqs", "SuccessFeedbackSampleRate": "45", "SuccessFeedbackRoleArn": "arn:aws:iam::123456789012:role/SNSSuccessFeedback_test1", "FailureFeedbackRoleArn": "arn:aws:iam::123456789012:role/SNSFailureFeedback_test2" }] } } }
YAML
Resources: MySNSTopic: Type: AWS::SNS::Topic Properties: TopicName:TestTopic DisplayName:TEST SignatureVersion:2 DeliveryStatusLogging: - Protocol: sqs SuccessFeedbackSampleRate: 45 SuccessFeedbackRoleArn: arn:aws:iam::123456789012:role/SNSSuccessFeedback_test1 FailureFeedbackRoleArn: arn:aws:iam::123456789012:role/SNSFailureFeedback_test2