How to trigger Lambda with SNS

Hi,

As a AWS developer you might have wrote some Lambda. If you don't know what is it I am inviting you to check this article out. It does give you an overview about AWS Lambda, or the following tag since I often talking about Lambda. Ok so today I'll talk about Lambda and SNS.

What is AWS SNS

AWS SNS stands for Amazon Web Service Simple Notification Service. Its allow you to send message through topics. You can make various kind of subscription to those topics and its can helps you to make so many thing. SNS helps you to connect multiple AWS sub-service together and the language will always be the same they are AWS event based messages.

Why am I using SNS with Lambda

Honestly each time data data arrives into a bucket a S3 event is triggered because of ObjectCreate's event is set. See the complete list of events you can add to a S3 bucket:

Ok so from here most of the time an event is attached and you can set a destination for this event. It could be sent to various destinations such as:

At the beginning I used to connect the s3 event to a Lambda directly but lately I had multiple things to do for each S3 event triggered from bucket. So what the point of this? Just create a second s3 event and trigger another lambda. However, unfortunately you can't set the same kind of event for the same bucket in AWS S3. SNS will hepls is the key to solve this.

Trigger multiple action

You can trigger multiple event based action from a S3 bucket or any other based event from AWS through SNS.

You have to create a topic on SNS section and make subscription to it. Once is done for our previous example is quite simple.

You can see the difference on the second schema, SNS is only forwarding the S3 original bucket event. In this case from a Lambda point of view you will have to parse the received event which is a SNS's one containing a message which itself contains our S3 event record.

In this way you can attach n subscriptions to your topic. Those subscriptions could be from various protocol see the list bellow:

I decided to be short that time, just to let you have an overview about how you can trigger multiple action from any source event toward various lambdas with SNS.

Later I'll talk how I handled this in my lambda configuration (serverless.yml), especially on how I managed to attach and subscribe/unsubscribe to topic automatically. This avoid you to manually attach your lambda to your topics and let you deploy your function easily with Serverless.