• I am a software enginner with deep passion for Big Data, Data Analysis, Machine Learning and Cloud Computing.
  • Co-founder and CTO @Mindbliss
  • Business Intelligence Team Lead @Mindvalley
  • Orginizer of Big Data Iran
  • Designer and Instructor of  Data Science Primer Course @ Magic

https://ca.linkedin.com/in/fartashh

@fartashh

fartashh.github.io

fartashh@gmail.com

Fartash Haghani

Architecting Serverless Push Notification System in AWS

Push Notifcation

One of the best approaches to increase and keep customer engagement with your app is push notification.

And there are many services such SNS, Firebase, Pushwoosh, Urban Airship, carnival, appboy, kahunna

Our Problem

  • Integrable with our user management system
  • Authentication and Authorization with Auth0
  • Send notification to user (multiple devices, multiple platform) not only single device
  • Schedule notification
  • Flexible user segmentation
  • Comprehensive API to manage notification system

Proposed Solution

you can find all lambdas of the system here lets look at each step of implementing the solution;

SNS

Create Platform Application

Database

Implement Lambdas

How to Configure your Lambda functions like a champ and let your code sail smoothly to Production

Function versions and aliases in AWS Lambda

A version in AWS Lambda is essentially a snapshot of your application code. Once you write your function and test it, you can publish a version. When you publish a version, you cannot make changes to that particular version and it is assigned a sequential number (1,2,3, etc.). AWS Lambda automatically names the working version of your code as $LATEST.

This brings us to aliases. An alias is a pointer to a particular version of your function. You name your function aliases and you control which version they point to. For example, you can have an alias named DEV that points to version $LATEST, a TEST alias that points to version 4 and a PROD alias that points to version 3. Typically your PROD alias would point to an older version than TEST and TEST to an older version than DEV.

When you run a Lambda function, you can specify which alias to run. This means that you choose to run either a DEV, TEST or PROD version of your code. Also, during function execution your code can know which alias is running by looking at the invoked function ARN, which is available in the Context object. The context object is available to the Lambda function code.

 

For example, the invoked function ARN for my DEV alias would be:

arn:aws:lambda:us-east-1:123456789012:function:helloStagedWorld:DEV

… and it can be accessed using the context object:

context.invokedFunctionArn

ways of storing configuration

  1. Store config files in an S3 bucket
  2. Store config files in a DynamoDB table
  3. Place my config files in the same package as my function code
import json
import urllib
import boto3

print('Loading function')

s3 = boto3.client('s3')


def load_config(env_alias):
    bucket = 'sns-lambda-config'
    key = 'config.json'
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        config = json.loads(response['Body'].read())
        return config[env_alias]

    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e

AWS Lambda Environment Variables

You can now supply environment variables to your Lambda functions. This allows you to effect configuration changes without modifying or redeploying your code, and should make your serverless application development even more efficient. Each environment variable is a key/value pair. The keys and the values are encrypted using AWS Key Management Service (KMS) and decrypted on an as-needed basis. There’s no per-function limit on the number of environment variables, but the total size can be no more than 4 kb.

 Lambdas Configuration

{
  "$LATEST": {
    "APPLICATIONS": {
      "appname-ios-dev": "arn:aws:sns:us-east-1:xxxxxxxxxx:app/APNS_SANDBOX/ios-dev"
    },
    "DATABASE": {
      "host": "dev-sns-lambda.xxxxxxxxxx.us-east-1.rds.amazonaws.com",
      "port": 5432,
      "db": "xxxxxxxxxx",
      "tables": {
        "users_endpoints": "users_endpoints",
        "topics": "topics",
        "subscriptions":"subscriptions",
        "notifications":"notifications"
      },
      "user": "xxxxxxxxxx",
      "password": "xxxxxxxxxxxxxxxxxx"
    }
  },
  "DEV": {
  },
  "TEST": {
  },
  "PROD": {
  }
}

Deploy Lambdas

API Gateway

Send Scheduled notification

You may figure it out by now that there is one lambda handel_notification_cron which is not connected to any end point. For this lambda we need to add CloudWatch Events - Schedule trigger. This trigger enable us to have a cron job and call lambdas every few minutes to send scheduled notifications.

Security

There are three techniques to secure your APIs. The simplest way is using api-key you can simply add new api-key in API Gateway console and enforce APIs to use it. The second method is adding Authorizers, it allows developers to authorize their APIs using bearer token authorization strategies, such as OAuth using an AWS Lambda function. And third method is using AWS_IAM role

# load config
try:
    Config = conf.load_config('$LATEST')
except Exception as e:
    logger.error("ERROR: couldn't load conf file")
    sys.exit()

try:
    db_conn = psycopg2.connect(database=Config['DATABASE']['db'], user=Config['DATABASE']['user'],
                               password=Config['DATABASE']['password'],
                               host=Config['DATABASE']['host'], port=Config['DATABASE']['port'])
except Exception as e:
    logger.error("ERROR: Unexpected error: Could not connect to datbase instance.")
    sys.exit()

try:
    sns_client = boto3.client('sns')
except Exception as e:
    logger.error("ERROR: Unexpected error: Could not connect to sns instance.")
    sys.exit()

logger.info("SUCCESS: Connection to DATABASE and SNS instance succeeded")


def handler(event, context):
    """
    @api {POST} https://bk3om565e4.execute-api.us-east-1.amazonaws.com/prod/ create_topic
    @apiName create_topic
    @apiGroup Topic
    @apiDescription create new topic
    @apiVersion 0.1.0
    @apiHeader {String} x-api-key api-key.
    @apiParam {String} topic_name       Mandatory
    @apiParamExample {json} Example:
    {
        "payload":
        {
            "topic_name": "topic_name"
        }
    }
    @apiSuccessExample {json} Success-Response:
        HTTP/1.1 200 OK
        {
              code='200', message='success',
              data={
                      topic_arn {String}
              },
              metadata={}
        }
    """
    try:
        logger.info(event)
        payload = event.get('payload')
        topic_arn = __create_topic(payload['topic_name'])
        __save_topic(payload['topic_name'], topic_arn)
        return get_raw_response_message(code=200, message='success', data={'topic_arn': topic_arn})
    except Exception as e:
        logger.exception(e)
        return get_raw_response_message(code=406, message=e.message, data={})


def __create_topic(topic_name):
    try:
        response = sns_client.create_topic(Name=topic_name)
        return response['TopicArn']
    except Exception as e:
        raise (e)


def __save_topic(topic_name, topic_arn):
    insert_query = """
        INSERT INTO {table_name}(
                name, arn)
        VALUES ('{name}','{arn}');
    """.format(**{
        'table_name': Config['DATABASE']['tables']['topics'],
        'name': topic_name,
        'arn': topic_arn
    })
    try:
        with db_conn.cursor() as cur:
            cur.execute(insert_query)
            db_conn.commit()
            logger.info(cur.statusmessage)
    except Exception as e:
        with db_conn.cursor() as cur:
            cur.execute("ROLLBACK;")
        raise e


def get_raw_response_message(code=200, message='', data={}, metadata={}, status_code=200):
    response = dict(code=code, message=message, data=data, metadata=metadata, timestamp=time.time())
    return response

Thank YOU :)

AWS-Server less push notification

By fartash haghani

AWS-Server less push notification

  • 510