As my first story, I decided to write a bit about my recent issue with AWS Lambda and global variables.
Overview
Was happily writing some refactor when for some reason I decided to move the variable that holds the response of the Lambda to a global variable, removing it from the scope of the handler to a global state and changing it inside the handler, at the time I had no clue what I was about to do, now that you have an overview of the situation can you guess what happened?
The issue
That lambda response was doing an append due to how we are handling data from DynamoDB, so over multiple calls to that lambda, the response was returning a list of more and more invites even from other accounts.
This, as you can imagine, was a huge issue, the project was not in production yet so we catch these issues a few days later when the entire team was testing a staging environment with multiple accounts.
Resolution
That part was not simple since we just noticed that doing some printf, and that the variable was not clean when the lambda (hot state) was triggered, just simply moving this variable to the Handler fixed the issues.
Since the lambda do not save the local variables memory state, everything inside the handle will be new at every call.
Conclusion
It was our first project with lambdas and go so this was not a simple issue to catch, we start to be more careful with what we put as a global variable, there are some external libs initialization that you want to actually make global, so the lambda while hot caches, but never put lambda response or input as variable.
Create this variables on the handler so they are fresh and clean every time the lambda runs.
Think twice in what you want to put as global, be careful in this decisions because they can cause a major problem and users get the wrong information or even mixed.
Always test, integration and manual testing are something that I try to make mandatory on my day to day work, test from multiple contexts always to prevent this to happen.
Ps: If you have any recommendation please send me a message, always open to improve.
Top comments (0)