Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like Request Scoped in AWS Lambda with node?

Is there a scope in AWS Lambda (with node.js) that is request safe? That can be globally visible but won't be change by another possible incoming lambda event? For instance now I have something like this:

module.exports.handler = (event, context, callback) => {
    dependency.doSomething(event.info)
}

const doSomething = info => {
    anotherLib(info)
}

const anotherLib = info => {
    placeWhereIReallyNeedInfo(info)
}

I would like to do something like this:

module.exports.handler = (event, context, callback) => {
    global.info = event.info
    dependency.doSomething()
}

const doSomething = () => {
    anotherLib()
}

const anotherLib = () => {
    placeWhereIReallyNeedInfo(global.info)
}

But then another lambda event could override the global.info before the anotherLib is called. This is especially a problem when I have a lot of different files and asynchronous code and need to keep passing parameters that a function doesn't need.

Thanks in advance

like image 856
Denis Avatar asked Jul 24 '26 01:07

Denis


1 Answers

But then another lambda event could override the global.info before the anotherLib is called.

This is actually a non-issue in Lambda functions. It will never happen, by design.

Only one invocation of your function is ever running at a time in each container. Global scope is perfectly safe in Lambda function code.

If a function invocation is running and another one needs to start, it will always, without exception, run in an entirely different container than any other currently running function. A container won't be reused for another invocation of the function until the first invocation is completely finished.

As your concurrency increases, new containers are automatically created. When a container is around for a few minutes without enough traffic to justify its existence, it is automatically destroyed by the service.

This allows all kinds of things that feel a little dirty but are convenient and quite safe, like creating a global "stash" object instead of passing values around.

This makes sense when you remember that you are paying a per-n-gigabyte-milliseconds charge for each function invocation to have exclusive use of the container in which it is running.

like image 178
Michael - sqlbot Avatar answered Jul 26 '26 17:07

Michael - sqlbot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!