C# Lambda constructor not called in consecutive lambda calls

懵懂的女人 提交于 2019-12-13 17:52:22

问题


I have a c# aws lambda class with some code in its constructor. The lambda method itself is getting called every time I initiate it (with an SNS message post), however, I cannot see the constructor getting called (added log calls to observe from cloudwatch). The constructor only gets called at first launch (after the aws stack creation/update).

Is this an expected behaviour? Does aws somehow cache my lambda instances?

public class MyLambda
{
     public MyLambda()
     {
          Console.WriteLine("Hello from ctor");
     }

     // This is the method assigned in CloudFormation
     public bool Execute(SNSEvent snsEvent)
     {          
          Console.WriteLine("Lambda called");
          return true;
     }
}

And here is the outcome in cloudwatch log; First time initiate Lambda:

Hello from ctor
Lambda called

And second time initiation of Lambda

Lambda called

回答1:


AWS reuses the instances as described in this blog post, in the FAQ and the official documentation.

In general the instances are reused and replaced every now and then. If you have a higher load AWS will create more concurrent instances. So usually it's very likely that your instances get reused, but you cannot count on it as they get recycled. When the instance is reused than the constructor won't be called again as the constructor was already called during the initialization.

Usually the first call to a new instance is quite slow, as the run-time does initialization like loading itself, class loading, etc and calling the constructor. The subsequent calls are usually much faster as the Lambda is already fully initialized. However, if you haven't called your Lambda for a while it needs some warm-up from its "freeze" as well. This still constitutes a reuse, so the constructor won't be called again.




回答2:


This means your lambdas must be idempotent, and you shouldn't do anything else than initialization in your class constructor (as it always should be), because you can't be certain it will be called again in subsequent calls...

I think it's a good thing that will speed up the process... for example all the services you configure and inject in your constructor are one of the most expensive things performance wise, and they won't be done again and again.



来源:https://stackoverflow.com/questions/43463130/c-sharp-lambda-constructor-not-called-in-consecutive-lambda-calls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!