AWS Lambda

AWS Lambda is a function as a service in AWS Cloud, we will cover only necessary parts but you can always refer to the official documentation.

We are going to use these terms throughout the guide: Function, Runtime, Event source and Log streams. Please make yourself familiar with basic concepts of AWS Lambda.

Function as a service (FAAS)

With FAAS you only need to provide your code and select the runtime (interpreter). We are going to use python3.7 runtime.

AWS Lambda can either be a simple python file or entire module. We need to specify a handler to tell lambda where to execute our code.

More details about python in AWS Lambda

Handler

Handler is usually a function lambda_handler which accepts 2 arguments.

Name of handler function can be anything, you just need to point the handler to the function, which accepts 2 arguments.
def lambda_handler(event, context):
    pass

event - Contains data from Event Source usually a Python dict type. It can also be list, str, int, float, or NoneType type. context – Contains runtime information to your handler. This parameter is of the LambdaContext type.

If needed visit more detailed handler documentation

Technical details

AWS Lambda function is a amazon linux container running python interpreter.

First invocation of your lambda function starts the whole container, which loads all your code into memory and executes lambda_handler. Then container stays idle for some time until amazon reclaim it’s resources. During the idle time, your code stays loaded and only lambda_handler is executed. This behaviour cold and hot start of AWS Lambda function.

Cold - invocation starts new container and executes lambda_handler Hot - invocation executes lambda_handler only Check this article for more information about lambda container lifetime.

You can use this feature to preserve open sessions by declaring them outside lambda_handler.

One example for thousands words.

session_not_reused.py
 import boto3

 def lambda_handler(event, context):
     session = boto3.Session()
     client = session.client('iam')
     client.get_user(UserName=event['iam_username'])

In this example the session object is created every time our lambda is called, which can lead to api throttling or different side effects.

We can fix this by declaring our session outside lambda_handler therefore it will be created only when lambda function is invoked from a cold state.

session_reused.py
 import boto3

 session = boto3.Session()
 client = session.client('iam')

 def lambda_handler(event, context):
     client.get_user(UserName=event['iam_username'])