AWS Lambda life-cycle

Ido Senesh
Jan 25 · 2 min read

Small example to help understand the life cycle of variables in Lambda, and how I am using them myself.

import random
import time

pre = random.random()
def lambda_handler(event, context):
print(pre, post)

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:
0.481645804584663 0.3031153358808475
0.481645804584663 0.3694771953834214
0.481645804584663 0.6688012907517211

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)

My conclusions:

  • 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
Ido Senesh

Written by

I’m not smart, i’m just good with google

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade