Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does AWS lambda store global variables?

I have created simple increment counter as below.

global.counter = 0;
exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, ++global.counter);
};

Whenever I test this function, I get incremented value as expected.

Is this right approach or do I need to store counter in cloud database?

like image 380
Jagdish Idhate Avatar asked Apr 19 '17 07:04

Jagdish Idhate


People also ask

Can Lambda function access global variables?

If you think about it a lambda is just a short-cut to defining a struct with a function operator. Local variables are not in scope for struct member functions but global variables are. Global variables can't be captured.

Is AWS Lambda global or regional?

AWS Lambda is a regional service. A single Lambda function in a single region can make API calls to AWS services in other regions, but they're remote, of course, so any data transferred between that Lambda function and the destination services or vice-versa takes longer and costs more.

Is Lambda function global?

A global lambda is a different beast altogether. It has different behavior from a regular function. Lambdas are objects, while functions are not. They have a type, but that type is distinct from the type of their function.

Does AWS Lambda support environment variables?

You can use environment variables to adjust your function's behavior without updating code. An environment variable is a pair of strings that is stored in a function's version-specific configuration.


2 Answers

When you call your Lambda function for the first time, a container is bootstrapped in the background by AWS.

When you call your Lambda function several times, you MIGHT get the same container to optimise run duration and setup delay.

You can't rely on this behavior but you must be aware it exists.

For you global vars, if you need to run you logic in Lambda, it should be working for several function to call the same code at the same time and should therefore be locked somewhere outside lambda code(DB or cache).

Regards,

like image 165
Thomas L. Avatar answered Sep 18 '22 09:09

Thomas L.


I had the same issue, and I ended up using AWS Elasticache service (Memcached) to store (key,value) pairs. It's quick, pretty easy to use (from python at least) and reliable.

Otherwise I completely agree with Thomas, you should be aware as it can cause issues, but do not trust this "feature".

like image 34
tipchi Avatar answered Sep 21 '22 09:09

tipchi