C# When using an AWS lambda, can I be sure that the destructor in my function will be executed?

Viewed 398

I'm using the service collection class to build a service provider that is used for my lambda. I don't really want to dispose of all my singletons every time the function handler is called, but I do want to dispose of them whenever the lambda is spinning down.

It's my understanding that without this, there's a chance that some unmanaged connections may not be closed correctly. To avoid that problem, I added a destructor which calls .Dispose() on the service provider.

How can I be sure that the lambdas are exited gracefully enough that my destructor will be called every time, and is my understanding that it can be beneficial for unmanaged resources correct?

Sample code:

public class Function {

   private readonly ServiceProvider _provider;

   public Function() {
     _provider = new ServiceCollection.AddXyz();
   }

   ~Function()  {
     _provider.Dispose();
   }
}

The handler is omitted but just know that it's opening database connections, rabbit mq connections, etc. all via the service collection container, and I don't want to wrap it in a using statement with a scope because if there are multiple calls that come in for a single lifetime of the lambda, I want the same connections to be used.

1 Answers

AWS Lambda does not currently provide a guaranteed mechanism to cleanup when the lambda environment is closing.

This was discussed here: https://github.com/aws/aws-lambda-dotnet/issues/342

If you are wanting for code to be called when the Lambda service reclaims the execution environment there is no service hook for that to happen. When the Lambda service detects a frozen execution environment that hasn't been used in awhile it deletes the execution environment regardless of what is inside the execution environment.

Fortunately you don't need to clean up any resources on the Lambda itself.

But for connections to external services, like a database, you might want to explore lowering any built-in connection timeouts so any servers your Lambda connected to will be more aggressive about closing abandoned connections left open by Lambda hosts shutting down.

Alternatively, if you'd rather ensure the connections are closed and don't mind re-opening them on every request, you can instead Dispose your ServiceProvider after every Function invocation, by calling _provider.Dispose() in a finally block of the Function method.

Related