DEV Community

Cover image for What is the Lambda Execution context and why use it?
JP Scriven
JP Scriven

Posted on

What is the Lambda Execution context and why use it?

What is the AWS Lambda Execution Context?

When your Lambda function gets called, Lambda will then invoke your function in an execution environment, which is an isolated runtime environment. The execution context is a temporary runtime environment that initializes any external dependencies of your lambda code. As your lambda function can be invoke numerous times and scale the execution context is maintained for some time in anticipation of another Lambda function invocation. When that happens it can "reuse" the context to execution time which will save time on your function. The execution context includes a /tmp directory, that provides 512mb of temporary storage for your functions.

What can it be used for?

There are a number of things the execution context can be used for but some great use cases for example is database connection, HTTP clients, SDK clients, etc...
Best practice to not put any connections for example inside your handler, because that will mean that every time your function gets invoked, it will create a new database connection, which will cause problems in the future. You want to be able to create that database connection outside of your handler and then just use that connection within the handler of your Lambda function.

Do not initialize your Database connections like this:

Bad initializing lambda function handler
This will cause a new connection to your DB every time your function gets invoked.

Rather create your function as follows:

Best practice database connection in your function
This is best practice and your Lambda function can now reuse the database connection in your handler, without the need to recreating the database connection if your function gets invoked multiple times in a short period.

/tmp space:

When you need to work with a big file inside of your Lambda function, you can use the /tmp space to temporarily save the file to use, if it's not bigger than 512MB. When the execution context is frozen, the directory content remains, which is helpful for multiple invocations. If you need more permanent objects that will not temporarily be used, then rather use something like AWS S3 for persistence of the object.

Top comments (1)

Collapse
 
sharath44665 profile image
Sharath

Hi Admin/Anybody,

Can you confirm whether or not this topic is out of date?

I may be wrong, but can you give me a source that proves your point, which is provided/discussed on this web site?

import sys
import logging
import pymysql
import json
import os

# rds settings
user_name = os.environ['USER_NAME']
password = os.environ['PASSWORD']
rds_proxy_host = os.environ['RDS_PROXY_HOST']
db_name = os.environ['DB_NAME']

logger = logging.getLogger()
logger.setLevel(logging.INFO)

# create the database connection outside of the handler to allow connections to be
# re-used by subsequent function invocations.
try:
        conn = pymysql.connect(host=rds_proxy_host, user=user_name, passwd=password, db=db_name, connect_timeout=5)
except pymysql.MySQLError as e:
    logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
    logger.error(e)
    sys.exit(1)

logger.info("SUCCESS: Connection to RDS for MySQL instance succeeded")

def lambda_handler(event, context):
    """
    This function creates a new RDS database table and writes records to it
    """
    message = event['Records'][0]['body']
    data = json.loads(message)
    CustID = data['CustID']
    Name = data['Name']

    item_count = 0
    sql_string = f"insert into Customer (CustID, Name) values({CustID}, '{Name}')"

    with conn.cursor() as cur:
        cur.execute("create table if not exists Customer ( CustID  int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (CustID))")
        cur.execute(sql_string)
        conn.commit()
        cur.execute("select * from Customer")
        logger.info("The following items have been added to the database:")
        for row in cur:
            item_count += 1
            logger.info(row)
    conn.commit()

    return "Added %d items to RDS for MySQL table" %(item_count)

Enter fullscreen mode Exit fullscreen mode