First, be careful using global variables. If you are developing and running the function locally, perhaps using something like
lambda-local,
node-lambda, or the
Serverless Framework, global variables will be uninitialized on each run. But, when running functions deployed on Lambda, global variables can retain their
state from one invocation to the next. This can bite you in the aws if you’re not careful.

Suppose you want to time how long your function takes to run. You could write code like this:

It will work correctly the first time, but for subsequent times, the start time variable could retain it’s value and give incorrect times in the log. Instead, you should move the variable declaration or initialization inside the handler function.

Second, you can use a global variable for caching. For instance, say we’ve developed a serverless API for a client and one of the functions looks up user permissions in a DynamoDB table.
Because we expect the number of users to remain small, instead of looking up the user who invoked the lambda function
in the DynamoDB table each time the function is called, we just scan the table (let’s say it only consumes 1 read unit)
and cache the result for up to 15 minutes.

This drastically reduces the required provisioned reads needed on the users table, and reduces the Lambda execution time and overall API latency.