Small example to help understand the life cycle of variables in Lambda, and how I am using them myself.
pre = random.random()
time.sleep(10)def lambda_handler(event, context):
if __name__ == "__main__":
Copy this script into a new Lambda function, and let’s play around with it.
after running it several times you may notice that:
- The main is never called when ran on Lambda - we may use it freely for local developement
- The first run takes about 10 seconds to return results, while following runs takes less than a second - global variables are initialized once, when Lambda is initialized, and stay alive as long as the container running the lambda is alive
- The output of consequent runs is something like this:
which means that variables defined inside the handler are fresh, and have per-request lifetime
- Changing environment variable (and actually anything that requires to “save” the new Lambda triggers creation of a fresh Lambda (this includes variables that are not used)
- Values that are dynamic, and should be changed upon request should be bound to environment variables or should be defined inside the handler scope (e.g. LogLevel, Dynamic threshold definitions etc.)
- Values that are static or that are derived directly from environment variables could be defined globally
- Heavy computations that are relatively dynamic, could be defined globally to prevent re-calculating them, but upon changing them, a “re-deploy” should be done
- “Re-Deploys” could be easily done, by changing some environment variable in the Lambda definition