Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

445
Visualizações
Scope of Python globals in AWS Lambda

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?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda