Scope of Python globals in AWS Lambda

Viewed 3635

What is the scope or lifespan of a global variable in AWS Lambda?

for example if I do something like this:

cache = {}

def lambda_handler(event, context):
   # do something with "cache"
   # do something else with "cache"

Is cache going to be initialized once per invocation (fresh process for each Lambda execution) or once this module is initialized, is it re-used for multiple invocations?

2 Answers

Global variables retain their value between invocations in the same execution environment.

Libraries should be defined in the initialization code outside of the handler, so they are loaded once when the execution environment is created.

source aws

import boto3, json

client = boto3.resource('dynamodb', region_name='eu-west-1')
tbl = client.Table('my-dynamo-table')

mydata = {}
mydata["groups"] = []

def lambda_handler(event, context):
    if len(mydata["groups"]) == 0:
        # data is not cached, make call to dynamo
        data = tbl.scan()
        group_data = data['Items']

        for group in group_data:
            mydata["groups"].append(group['name'])
        return mydata

    else:
        # return cached content
        return mydata

Take advantage of execution environment reuse to improve the performance of your function. Initialize SDK clients and database connections outside of the function handler, and cache static assets locally in the /tmp directory. Subsequent invocations processed by the same instance of your function can reuse these resources. This saves cost by reducing function run time.

aws

Lambda Global Variables do not get updated with every invocation. Whatever you write inside the handler function will get invoked with each invocation.

Coming to lifespan of Global Variables, it stays as long as the initialized container stays up ( it shutdowns the container if it remains inactive for certain period.of time) or code is modified and redeployed. We should be cautios of what we are putting up as cache, i.e if the cached data is updated frequently then storing it up in cache is not a good idea.

https://docs.aws.amazon.com/lambda/latest/dg/runtimes-context.html

https://medium.com/tensult/aws-lambda-function-issues-with-global-variables-eb5785d4b876

Related