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?
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.
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.
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.
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.
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,
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With