How To Get The Ball Rolling With AWS Lambda

Posted By:Shivaranjani Ramakrishnan
Posted on:06 Aug 2019

In our previous post, we spoke about what serverless is, and the general architecture of AWS Lambda. In this post, we will get a more hands-on feel of the Lambda function and how to go about using it. To get started you need to have an AWS account. AWS offers an AWS free tier account for a year. So if you don’t have an account, create one and get started.

How AWS Lambda Works?

Before we start to write our first lambda function lets us understand how it works. In general, the whole idea behind serverless is for us to run our code when needed and not worry about managing a server. Now, for our code to run it needs to be triggered.

AWS lambda works insisive cloud
Source: Cleveroad

The lambda function can be invoked as a result of any event that has occurred in another AWS service. It can be invoked either synchronously or asynchronously. For synchronous invocation, the service that has invoked the lambda function and waits for a response from the function if it runs asynchronously, it gets triggered and the other service is unaware of the lambda response after that. 

Six Steps to Create AWS Lambda Function Using Python

Now that we know how to trigger our function we can go ahead an create our first Lambda function. We will be using python for this example.

Step 1: Create AWS Lambda Function

Go to the AWS console, and click on Lambda under services. Once you’re here you can click on Create Function.

create lambda insisive cloud
Create Lambda

Here you can enter your function name and then select the specified runtime. As of today, lambda supports six runtimes that include Java, NodeJS, Python etc. Today we will be writing our function code in python and for the sake of brevity our function checks if a number is prime or not. 

We can leave the Permissions field to default, usually, when your Lambda function needs access to other AWS services such as S3 etc, the role comes into the picture. A service role can be created for the Lambda service to access the S3 service and then, this role can be attached to the lambda function that requires the aforementioned set of permissions.

Step 2: Import JSON

Now that we have created our function and click on it you will be able to see the sample lambda code AWS provides for a newly created Lambda function.

def lambda_handler(event, context):

    # TODO implement

    return {

        'statusCode': 200,

        'body': json.dumps('Hello from Lambda!')

   }

In the above sample code, the lambda_handler acts as the entry point of the function. This handler has two parameters event and context.

The event object is used to pass user data from triggers. Suppose you need to pass a list of dictionaries etc, all that can be passed as a JSON object to the event data. Other services such as SNS, S3 also use event object to pass information required for the lambda function to execute.

The context object provides methods and properties that provide information about the invocation, function, and execution environment which can be pretty insightful. Since Lambda is billed based on function execution time and memory we can figure out how much time our function actually takes to execute using the context method ‘get_remaining_time_in_milles’ which will give us the amount of time remaining up until the function times out. Similarly, information such as the function name, function version etc can be retrieved.

Step 3: You can use the below code snippet for your function.

import json

def lambda_handler(event, context):

    num = event['num']

    print(context.get_remaining_time_in_millis()) 

    # If given number is greater than 1 

    if num > 1:  

       # Iterate from 2 to n / 2  

       for i in range(2, num//2): 

           # If num is divisible by any number between  

           # 2 and n / 2, it is not prime  

           if (num % i) == 0: 

               print(num, "is not a prime number") 

               break

       else: 

           print(num, "is a prime number")

    else: 

       print(num, "is not a prime number") 

    return {}

AWS Lambda func insisive cloud
AWS Lambda Function Screen

Step 4: Set Time And Memory For The Function

Now that you’ve finished writing your code you have to set a time and memory for the function.

AWS Lambda Time and Memory

By default the function is set to 3 seconds, you can go up to 15 minutes, after which your function times out. The default memory allocated is 128MB, depending on the memory you choose a proportional amount of CPU is assigned to your function. If your function is CPU intensive it is wiser to set a higher memory.

Lambda time and memory insisive cloud
AWS Lambda time and memory

Step 5: Create Test Event

Now we can test our code by creating a test event. Here, we are passing the number to be checked.

Lambda Test Event insisive cloud
Lambda Test Event Screen

Step 6: Lastly, Save And Click On Test

Lambda function save insisive cloud
Lambda function save screen

Once you Save and click on Test you will get the execution result. Here you can see the output of your code and other information like the memory used by your function, the total time your function ran for and how much of it you got billed for. 

Our Thoughts

AWS Lambda has various use cases to accomplish various tasks. In our next blog, we will be talking about various use-cases of lambda and how it can be integrated with other AWS services. 

Also read: Configure AWS Lambda programmatically with Boto3

Make the most of your cloud and optimize your cloud cost upto by 60% with insisive cloud App; schedule a demo or just drop email at info@insisiv.com. 

Leave a Reply

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


Notice: Undefined index: loggedin_user in /var/www/html/wp-content/plugins/freshchat/widget-settings/add_to_page.php on line 97