Amazon SNS Notification Topics Subscribe From AWS Lambda

In this article, we are going to subscribe Amazon SNS topics from AWS Lambda Functions. This will be hands-on lab for Amazon SNS Notifications Subscribe From AWS Lambda.

Amazon SNS Topics Subscribe From AWS Lambda

By the end of the article, we will develop AWS Lambda function which subscribe from Amazon SNS topic and perform its business logic.

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

Hands-on Lab: Amazon SNS Notifications Subscribe From AWS Lambda

We can use a Lambda function to subscribe to an Amazon SNS topic.
Here you can see our very basic architecture:

Amazon SNS Topics Subscribe From AWS Lambda

So during the hands-on lab, we will follow below steps:

  • Create an Amazon SNS topic
  • Create a Lambda function
  • Create a Lambda subscription to Amazon SNS topic
  • Develop Lambda function for incoming event from Amazon SNS topic
  • Publish Message from Amazon SNS
  • Log incoming SNS Message into Lambda Function

As you know that, when we implement any architecture on AWS, we have 2 main steps;

  1. Create infrastructure on AWS Cloud
  2. Develop Lambda code for interacting to SNS

So we will start with the first step: Create this architecture infrastructure on AWS Cloud.

Create Notification Amazon SNS topic

We are going to do hands-on lab Create Goal Notification Amazon SNS topic. Think about that we are developing football application that update scores regularly. And we use Amazon SNS for goal notifications.

  • Create topic
  • Standart
  • name — goalNotification

Save SNS topic with Create topic button. We can See Topic Detail, We can create Subscription, Click Create Subscription and See protocols. So we need to create lambda function.

Create Lambda Function for Asnyc Invocations from Amazon SNS

We will create the function that processes events from Amazon SNS. Open the Functions page of the Lambda console. Choose Create function. On the Create function page, choose — Create from Scratch

Name —goalFunction

Create Function. Ready to develop our codes on Lambda Function. Add logger into function code:

exports.handler = async (event) => {
console.log(“event:”, JSON.stringify(event, undefined, 2));
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify(‘Hello from Lambda!’),
};
return response;
};

Added log to see incoming event from SNS with async invocation.

As we learned from Lambda async invocations, Amazon SNS, invoke functions asynchronously to process events. When you invoke a function asynchronously, you don’t wait for a response from the function code. You hand off the event to Lambda and Lambda handles the rest. We can configure how Lambda handles errors, and can send invocation records to a downstream resource to chain together components of your application.

You can see lambda configurations with goto Lambda-Configurations-Async configurations.

https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations

Lambda manages the function’s asynchronous event queue and attempts to retry on errors. If the function returns an error, Lambda attempts to run it two more times, with a one-minute wait between the first two attempts, and two minutes between the second and third attempts. Function errors include errors returned by the function’s code and errors returned by the function’s runtime, such as timeouts.

Lambda permissions

When SNS invoke our function asynchronously, it needs to invoke Lambda permissions into Resource-Based Policy section. So when we subscribe our lambda function to the SNS, we should give required permission to SNS, in our case permission is invoke Lambda operation. So we should give required permissions.

Create Lambda Subscription to Amazon SNS topic

We will Subscribes lambda function to an Amazon SNS topic. We have 2 options:

  1. Goto SNS topic and Create subscription from SNS topic.
  2. Goto Lambda function and Add Trigger — SNS

Amazon SNS invoke functions asynchronously to process events. So we can add trigger to SNS into our Lambda function. When SNS invoke our function asynchronously, it needs to invoke Lambda permissions into Resource-Based Policy section. With adding trigger SNS into Lambda function, this will add required permissions.

  • Goto Lambda and Add Trigger — Add SNS topic subscription — goalTopic

Develop Lambda function for incoming event from Amazon SNS topic

we are going to do hands-on lab Develop Lambda function for incoming event from Amazon SNS topic. When developing our Lambda function we should now incoming event json object from Amazon SNS topic.

Amazon SNS Topics Subscribe From AWS Lambda

There are several ways to know, we can check test template or get sns-notification. Also I had example incoming event :

INFO event: {
“Records”: [
{
“EventSource”: “aws:sns”,
“EventVersion”: “1.0”,
“EventSubscriptionArn”: “arn:aws:sns:us-east-2:308360398142:testTopic:dcce19d9-d904–4986–89ba-3d89a450df66”,
“Sns”: {
“Type”: “Notification”,
“MessageId”: “428dd3f1–2e2e-53fc-8c78–88e39f1f2175”,
“TopicArn”: “arn:aws:sns:us-east-2:xxxx:testTopic”,
“Subject”: “testMessage”,
“Message”: “testMessage”,
“Timestamp”: “2022–06–02T12:37:05.595Z”,
“SignatureVersion”: “1”,
“Signature”: “xxx/xx+xx++xx+xx+xx+xxx==”,
“SigningCertUrl”: “https://sns.us-east-2.amazonaws.com/SimpleNotificationService-xx.pem”,
“UnsubscribeUrl”: “https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:308360398142:testTopic:dcce19d9-d904-4986-89ba-3d89a450df66",
“MessageAttributes”: {
“attr1”: {
“Type”: “String”,
“Value”: “val1”
}
]
}

Now we can develop our lambda function as per incoming event from above json. Lambda Function:

exports.handler = async (event) => {
console.log(“event:”, JSON.stringify(event, undefined, 2));

var message = event.Records[0].Sns.Message;
console.log(‘Message received from SNS:’, message);
};

Deploy the function. Since this will asnyc invocation, we don’t need to return anything. To be simple I only log incoming message.

Publish Message from Amazon SNS

We are going to do hands-on lab Publish Message from Amazon SNS and see Lambda execution.

  • goto SNS Topic — Send Message
  • goto Lambda — See Logs

As you can se that we can finished our hands-on lab. We can extend this lab, for example insert incoming notification into DynamoDB table or send it to SQS and so on. To see full developments of this hands-on lab, you can check below course on Udemy.

Step by Step Design AWS Architectures w/ Course

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

In this course, we will learn almost all the AWS Serverless Services with all aspects. We are going to build serverless applications with using AWS Lambda, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, Amazon S3, Amazon SNS, Amazon SQS, Amazon EventBridge, AWS Step Functions, DynamoDB and Kinesis Streams. This course will be 100% hands-on, and you will be developing a real-world application with hands-on labs together and step by step.

Source Code

Get the Source Code from Serverless Microservices GitHub — Clone or fork this repository, if you like don’t forget the star. If you find or ask anything you can directly open issue on repository.

--

--

Mehmet Ozkaya
AWS Lambda & Serverless — Developer Guide with Hands-on Labs

Software Architect | Udemy Instructor | AWS Community Builder | Cloud-Native and Serverless Event-driven Microservices https://github.com/mehmetozkaya