r/serverless • • Dec 19 '18

AWS Lambda maintains state between calls

Was playing around with lambda and found an edge case where state is retained. Thought people might be interested. https://medium.com/@thomas.mcnicol/unexpected-aws-lambda-behaviour-7109da2d38f

0 Upvotes

7 comments sorted by

14

u/BraveNewCurrency Dec 19 '18

This is literally in the FAQ:

Q: Will AWS Lambda reuse function instances?

"To improve performance, AWS Lambda may choose to retain an instance of your function and reuse it to serve a subsequent request, rather than creating a new copy. To learn more about how Lambda reuses function instances, visit our documentation. Your code should not assume that this will always happen."

1

u/tmcnicol Dec 19 '18

Cheers mate thanks for pointing it out

9

u/andnog Dec 19 '18

Most likely it’s the execution context since your myVar is declared outside the handler. You can read more about it here https://docs.aws.amazon.com/lambda/latest/dg/running-lambda-code.html

1

u/tmcnicol Dec 19 '18

Thanks mate, I have added your link to the article.

3

u/recursiveCreator Dec 19 '18

it’s, in fact, recommended to take advantage of that and move code out of the handler to make use of a lambda’s warm state (keep connections alive etc) . It’s part of lambda’s best practices ;)

https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html

2

u/j_rapp Dec 19 '18

Yeah this is a known, documented thing. Very useful too. I use it to hold database connections for example.