.NET Core AWS Lambda Lifetime After Uncontrolled Exception

I am writing my first AWS Lambda function. It maintains some state in a static variable and I wanted to know whether that static variable sticks around if an uncontrolled exception occurs.

In a console application for example, an uncontrolled exception results in the ending of that process. Any state is lost. In an ASP.NET application, only the request dies, but the application continues. So not knowing the details of the hosting environment of a function, I wasn't sure what would happen.

So I created a very basic function to try it out. It is the basic S3 template with the guts replaced. There is a static List<string> and in the function handler, we print out the current item count, add an item then throw an exception.

public class Function
{
    IAmazonS3 S3Client { get; set; }
    static List<string> Items = new List<string>();

    /// <summary>
    /// Default constructor. This constructor is used by Lambda to construct the instance. When invoked in a Lambda environment
    /// the AWS credentials will come from the IAM role associated with the function and the AWS region will be set to the
    /// region the Lambda function is executed in.
    /// </summary>
    public Function()
    {
        S3Client = new AmazonS3Client();
    }

    /// <summary>
    /// Constructs an instance with a preconfigured S3 client. This can be used for testing the outside of the Lambda environment.
    /// </summary>
    /// <param name="s3Client"></param>
    public Function(IAmazonS3 s3Client)
    {
        this.S3Client = s3Client;
    }

    /// <summary>
    /// This method is called for every Lambda invocation. This method takes in an S3 event object and can be used 
    /// to respond to S3 notifications.
    /// </summary>
    /// <param name="evnt"></param>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context)
    {
        await Task.Yield();
        context.Logger.LogLine($"Item count {Items.Count}");

        Items.Add(Guid.NewGuid().ToString());
        throw new Exception("Something bad happened");
    }
}

I executed the function four times and saw that the count incremented 0, 1, 2, 3. Which means that the host process survives uncontrolled exceptions.

That's it folks!