Architecting Serverless Notifications on AWS

Real-time notification plays an important role in use cases like you need to notify the users when there is an update available for the app or when a comment/inquiry is received on a website. In such use cases, the web admin should be notified and the user should be addressed with some kind of confirmation notification either through email/sms/push notification (in the case of a mobile app).

Generally, implementing notifications will be an easy task when we have a dedicated server with the help of Web Sockets. We can make a permanent link between the server and the user and use publish-subscribe mechanism to share messages. The browser will be subscribed to automatically receive the messages without checking for constant updates.

Generally, implementing notifications will be an easy task when we have a dedicated server with the help of Web Sockets. We can make a permanent link between the server and the user and use publish-subscribe mechanism to share messages. The browser will be subscribed to automatically receive the messages without checking for constant updates.

What exactly does serverless mean?

Before knowing about serverless, we should understand

BaaS:3rd party services (commonly known as “BaaS” or Backend as a Service)

FaaS:Custom code that’s run in the containers (“FaaS” or Function as a Service)

Serverless architecture basically refers to the applications that generally depend on these services. AWS is the best-known vendor host currently. By using these kinds of ideas, and by moving focus to the front end, such architectures generally eradicate the need for the server system sitting behind the application.

Such architectures can significantly reduce the cost of operational and complexity of the dependencies and immaturity of support services.

Here, I’m trying to describe how to implement a notification system (Email, Push Notification, SMS) for a use case that I mentioned earlier.

Serverless Notifications Architecture Diagram

 

Serverless Notifications

 

Advantages of Going Serverless
  • Simple, dynamic & flexible
  • Best-in-class PaaS
  • Easy to use/implement
  • Easy to build
  • Reliable
  • REST API is independent of platform or languages
  • Secure & scalable
  • Deploy fully functional software on the AWS Cloud

Getting Started

Prerequisites

Knowledge of Node JS, and AWS services (Lambda, API-gateway, DynamoDB, cloud watch)

There are many ways to automatically create these routes, functions, and DB setup using some serverless js .But here I am going to show you manual setup of all these things.

Simple Steps for Creating API

Step 1: Create API-Gateway (resources & methods)

    • API-Gateway is a fully managed service provided by AWS that makes easy for users to create, monitor, publish, maintain, and manage secure APIs.
    • Open Amazon API Gateway console. Select an existing API or create new API by entering a name.

 AWS Serverless Model

  • On the API tree view, just click the Actions button in the menu to “Create Resource” and name the resource
  • With the selected resource, create a new method and select the HTTP verb with the method

Step 2: Setting Request templates

Click on Integration request and select body mapping template.

Set the value to application/json and give a template. This template controls the request passed to lambda event. If you want to filter some details as per your requirement or send extra parameters to the request, it is done here. Simply to say, you will have control on the request passed to the lambda function /mock.
You can generate different templates using the online tools provided by AWS.

the request, it is done here. Simply to say, you will have control on the request passed to the lambda function /mock.

You can generate different templates using the online tools provided by AWS

AWS Serverless Notifications

Architecting on AWS

Step 3:Create/setup Lambda

The actual process of triggering the emails/push notifications/messages happen inside this lambda function. Here, I want to show triggers between the lambda and dynamodb and vice versa.
We need 2 lambda functions

  1. Simply receive the request and save the data into dynamodb.
  2. When there is a new data insert into dynamodb, the lambda triggers and sends notifications

Lambda function 1:
A. Event (Request details)
B. Reading the configuration from s3 bucket (secured area)
C. Saving the data into dynamodb
D. Sending the response back to API-gateway

Lambda function 2:
A. Event (inserted data in dynamodb)
B. Reading the configuration from s3 bucket (secured area)
C. Pushing Notification through Firebase
D. Pushing a message through 3rd party service (solution infinity)
E. Reading the templates from s3 (Mail body)
F. Pushing emails through MailGun or Amazon SES (Admin, user, manager, etc)

Step 4: Setting a Response templates

This is also similar to the integration request. Click on Integration response and select body mapping template. Set the value to application/json and give a template
This template controls the response passed by lambda. If you want to filter some details as per your requirement or format json response, it is done here. You will have control on the response passed by the lambda functions /mock. You can generate different templates using the online tools provided by AWS
Note: This is really helpful for formatting the response when you try retrieving the data from dynamodb and passing to the user.

Step 5: Enable CORS

CORS defines a way to client web apps that are loaded in a domain to interact with the resources in other domain.

Click on “Enable CORS” option in Actions

AWS

AWS Serverless

Step 5: Deploying the API

After an API is created, you must deploy it to utilize them. In AWS, deployment takes place in stages .We can say stage as a version of API (dev, test, stg, prod).

Click on “Deploy API” Option in Actions, add the stage details and save. Your API’s are deployed!

Fire Base (Push notification to Devices)

Firebase gives you the scope to develop high-quality apps and to grow the user base. We cover the essentials so that you can monetize your business and focus on your users. We have many services provided by the firebase. Here, I will show you push notification implementation.

Firebase also provides NO-SQL DB for storing data as similar to Dynamodb

    • Log into firebase console and select Create New Project

Architecting AWS

    • You can setup apps for Web, Android, and iOS. Follow the instructions to setup the android or IOS project and build the application and to deploy in your device

AWS API-Gateway

    • Click on the app of your choice.

API-Gateway

    • Click on Notifications from the left panel. Here you can push and test whether your app is working as expected or not

Serverless Model

Result Notification:

Serverless Notifications

Lambda Coding (Node)

Prerequisites for node: Configurations, HTML templates loaded from s3

Node modules: Mailgun, AWS SDK, Markup.js, FCM-push, global-tunnel

Sample code for pushing a notification

var FCM = require('fcm-push');

    var serverKey = '';
    var fcm = new FCM(serverKey);

    var message = {
        to: '/topics/global', // required fill with device token or topics
        collapse_key: 'your_collapse_key',
		priority:'high'	,
		category:'receipt',
        data: {
            your_custom_data_key: 'your_custom_data_value',
			 title: 'sample',			 
            body: JSON.stringify('BODY YOU WANT TO PASS')
        }
    };

    //callback style
    fcm.send(message, function(err, response) {
        if (err) {
            console.log("Something has gone wrong!");
        } else {
            console.log("Successfully sent with response: ", response);
        }
    });
 

Sample code for Mail Notification

templateBody- s3 html template
config- s3 configuration file
var message = mark.up(templateBody, emailObject);
                    //Initialzing mail gun
                    var mailgun = new Mailgun({
                        apiKey: 'MailGun API KEY',
                        domain: 'DomainName registered'
                    });
                    //initialozing the input parameters
                    console.log(config);
                    var data = {
                        from: config.emailFromAddress,
                        to: config.emailTOAddress,
			   bcc: config.emailBCCAddress,
                        subject: config.emailSubject,
                        html: message
                    };

                    //sending the mail through the mailgun
                    mailgun.messages().send(data, function(err, body) {
                        //If there is an error, render the error page
                        if (err) {
                            result.message = 'error';
                            console.log("got an error: ", err);
                        }
                        //Else we can greet    and leave
                        else {
                            result.message = 'Send sucessfully';
                            console.log("sent");
                            context.succeed(result);
                        }
                    });
					 

Sample code for sms Notification

//sending sms to Customer
            //initializing Json request
            var Json = {};
            Json.sender = config.SMSSender;
            Json.message = CustomerQuery;
            Json.format = 'json';
            Json.flash = 0;
			Json.sms = [];
			var receiver = {};
			receiver.to = ContactNo;			
			Json.sms.push(receiver);
            var body = JSON.stringify(Json);
            var globalTunnel = require('global-tunnel'); 
         	// making POST request to send SMS
		  request.post({
                       url:     url,
                       body:   body
                  }, function(error, response){
          if (error) {
			  result.message = 'Send SMS faild'
		      result.error = error ;
              context.fail (result);
		  }
          else{
			  result.message = 'SMS sent Successfully to customer' + ContactNo;
              console.log('response to customer' +  JSON.stringify(response));
		      context.succeed(result);
              }
           });
		    

Sending Push notifications is one of the best approaches to sustain and enhance customer engagement with your app. The existence of great services like AWS helps developers to achieve this service efficiently in a short amount of time.

FacebookTwitterGoogle+Share
About Uday Kiran

Uday Kiran Atta is an Associate Software Engineer at Vmoksha, who has hands on experience on QA and .net framework. He is passionate about exploring emerging trends in the technology and would love to share the ideas with his peers.



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>