AWS Serverless: SNS & Lambda

  • Topics

SNS & Lambda: A Match Made in Heaven

Serverless brought about a wave of changes to the way we build and interact with our apps. Amazon users were given AWS Lambda and all of a sudden they saw themselves face to face with the new dawn of event-driven architecture.

What is Lambda?

In the unlikely event that you haven’t heard about AWS Lambda, let me try to explain it. It’s a simple service that lets you run bits of code without having to provision or maintain servers. You pay every invocation and for the time it ran but that’s all you pay. You won’t get charged for the time your Lambdas sit unused.

Pretty much anything you can think of can be translated to Lambda, provided you land into the limits imposed by AWS. You can control all the little events that are triggered by our application in a clean, simple, and cheap way. Naturally, the Simple Notification Service, or SNS, is going to work extremely well with our Lambda due to its resilient and scalable nature.

What is SNS?

Amazon’s Simple Notification Service is a fully managed pub/sub messaging service that lets you decouple distributed services and send messages to a large number of receiving endpoints for parallel processing. One popular use case for SNS is the sending of notifications based on different events from your app directly to your Email, SMS, and mobile push.

 Amazon Simple Notification Service (SNS) is a flexible, fully managed pub/sub messaging and mobile notifications service for coordinating the delivery of messages to subscribing endpoints and clients. – AWS Docs

To get started with SNS is maybe easier than Lambda. All you need to do is to create a topic, which is basically the access point that allows you to publish your messages. After that’s done you’ll have to make sure you’ve set the right protocols for messaging as well as the permissions since you really don’t want people to use your SNS as it can get pretty pricey at scale.

AWS Lambda and SNS

Unless you are after more intricate thrills, AWS Lambda can subscribe directly to SNS topics without having to involve a third party, other services, or additional code. What this leaves you with is a combination of highly scalable systems that work out of the box with minimal setup involved.

What this means is that you can get a simple application that can work instantaneously with no polling and a push-based delivery that’s simple to integrate, flexibly, inexpensive due to the pay-as-you-go model that has no upfront costs that is easy to set up even with the AWS Console which is a point-and-click interface.

 

We’ve always considered AWS Lambda as a more secure alternative to docker or other similar platforms because of it’s ephemeral and stateless nature that reduces by default the surface vectors for possible attacks. SNS is no different when it comes to security as it allows users to encrypt data at rest by using AWS KMS keys and can add another layer of security by using PrivateLink to publish messages to SNS privately and securely.

Practical example

To better understand the relationship between Lambda and SNS let’s look at a simple example together. Think of a scenario where you’d have a user upload files to an S3 bucket. Those files could either be a video or simple images. In either way, you’ll have an event trigger an SNS topic that will call a lambda. At the very end of this scenario, you can have your Lambda send an email directly or have it set up to send you a message via Slack or Telegram.

The beauty of this setup consists in its simplicity. You don’t need to provision any servers or infrastructure beforehand and you only pay what you use for everything including S3. The code itself for SNS message event could be simpler.

Similarly, you could use AWS Pinpoint to send an SMS or even a voice message instead of a simple email or Slack message.

{
  "Records": [
    {
      "EventVersion": "1.0",
      "EventSubscriptionArn": "arn:aws:sns:us-east-2:123456789012:sns-lambda:21be56ed-a058-49f5-8c98-aedd2564c486",
      "EventSource": "aws:sns",
      "Sns": {
        "SignatureVersion": "1",
        "Timestamp": "2019-01-02T12:45:07.000Z",
        "Signature": "tcc6faL2yUC6dgZdmrwh1Y4cGa/ebXEkAi6RibDsvpi+tE/1+82j...65r==",
        "SigningCertUrl": "https://sns.us-east-2.amazonaws.com/SimpleNotificationService-ac565b8b1a6c5d002d285f9598aa1d9b.pem",
        "MessageId": "95df01b4-ee98-5cb9-9903-4c221d41eb5e",
        "Message": "Hello from SNS!",
        "MessageAttributes": {
          "Test": {
            "Type": "String",
            "Value": "TestString"
          },
          "TestBinary": {
            "Type": "Binary",
            "Value": "TestBinary"
          }
        },
        "Type": "Notification",
        "UnsubscribeUrl": "https://sns.us-east-2.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-2:123456789012:test-lambda:21be56ed-a058-49f5-8c98-aedd2564c486",
        "TopicArn":"arn:aws:sns:us-east-2:123456789012:sns-lambda",
        "Subject": "TestInvoke"
      }
    }
  ]
}

The main thing to note is the MessageId, Message, and the Message Attributes.

MessageId: A Universally Unique Identifier, unique for each message published. For a message that Amazon SNS resends during a retry, the message ID of the original message is used.

Message: A string that describes the message.

MessageAttribute: Amazon SNS supports the delivery of message attributes, which let you provide structured metadata items about the message and each message can have up to 10 attributes. Each message attribute has the following items:

  • Name – the attribute name that is case sensitive.
  • Type – which can be a String, String.Array, Number or Binary
  • Value -the string data that has the same restrictions as the body type.

Conclusion

There are countless ways of using AWS Lambda with SNS and the benefits are quite significant. From the ease of which you implement the two services into your application to the cost benefits.

Lumigo is a serverless monitoring and debugging platform. It tracks AWS Lambda, SNS, and other services in your serverless application and alerts you of any issues. You can then use Lumigo to quickly and easily drill down to the root cause of the problem. Get a free account.

Debug fast and move on.

  • Resolve issues 3x faster
  • Reduce error rate
  • Speed up development
No code, 5-minute set up
Start debugging free