Outshift Logo

INSIGHTS

9 min read

Blog thumbnail
Published on 02/14/2022
Last updated on 05/03/2024

Getting Started with AWS Lambda in .NET

Share

Serverless computing is becoming increasingly popular, and with the proliferation of serverless computing over the past few years, the adoption of Function-as-a-service (FaaS) computing models has also increased. Some of the popular FaaS providers today include AWS Lambda, Microsoft Azure Functions, and Google Cloud Functions. In this article, we’ll examine how you can build and deploy AWS Lambda applications to AWS, as well as how to integrate your Epsagon account for monitoring.

What Is AWS Lambda?

AWS Lambda is a serverless stateless compute service that allows you to execute code for virtually any backend service, without the need to deploy or manage infrastructure resources on AWS. It is a good choice when you need a function to run for a short period. AWS Lambda functions are invoked as a result of events generated by other services, with each event simply being a JSON document including the data to be processed by your function.

Benefits and Limitations

Lambda Functions can scale infinitely, reduce costs, have high availability, and help you build resilient applications. You only have to pay for the compute time your code consumes—there is no fee for idle time processing. However, they have certain drawbacks too, such as startup latency, testing and debugging challenges, etc.

Use Cases

Some of the typical use cases of Lambda Functions are real-time data processing, building data pipelines, responding to web requests, and even composing and sending emails. However, there are certain drawbacks too such as startup latency challenges in testing and debugging.

Building a Payroll Microservices-Based Application

Microservices architecture is an architectural approach or pattern in which a single application comprises numerous tiny, loosely coupled, and independently deployable services that are built, tested, deployed, and managed independently. Some of the key benefits of a microservices architecture are better modularity and improved scalability and performance. Our example will be a minimal implementation of a payroll application comprising several microservices such as Employee, Department, Attendance, Salary, etc. Assume you need to verify email addresses in several places with this application. In the sections that follow, we’ll use AWS Lambda to implement a simple, reusable function, showing you how to build, deploy, and test an AWS Lambda function. First, make sure you have the following installed on your computer:
  • .NET 5 SDK
  • Visual Studio 2019
  • AWS Toolkit for Visual Studio
You can create a new Lambda Functions project in .NET either from the .NET CLI or from within Visual Studio 2019. In this example, we’ll be building an AWS Lambda using the latter.

Building an AWS Lambda Function

There are two AWS Lambda project templates available: AWS Lambda and AWS Serverless Application. For just one AWS Lambda function, you should go with the AWS Lambda project template, which we will be using here. But if you need to build and deploy multiple AWS Lambda functions, you should utilize the AWS Serverless Application template. To work with AWS Lambda, launch a console window and type the following command to install the necessary templates:
dotnet new -i Amazon.Lambda.Templates
Once installed, execute the following command to create an empty Lambda Function project:
dotnet new Lambda.EmptyFunction --name AWSLambdaEpsagonDemo
Your AWS Lambda function should look like this:
public class Function
{
    public string FunctionHandler(string input, ILambdaContext context)
{
        return input?.ToUpper();
}
}
Now, let’s write some code in there. You need a Lambda function to check if an email address passed to it as a parameter is valid. The following method tests this and will return as “true” if the email ID is valid and “false” if not.
private bool IsEmailAddressValid(string emailAddress)

{

     string pattern = (@”^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$”);

return new Regex(pattern, RegexOptions.IgnoreCase).IsMatch(emailAddress);

}
replace the FunctionHandler method of the Function class with the following code:
{
   return IsEmailAddressValid(inputObject.EmailAddress);
}
Note how the IsEmailAddressValid method is called from the Lambda function, and the first parameter to the FunctionHandler method is an object of type InputObject. The InputObject class contains just one property, i.e., EmailAddress, as shown in the code snippet given below:
public class InputObject
{
   public string EmailAddress { get; set; }
}

Deploy the Lambda Function

AWS Lambda supports deployment packages in two formats: zip archives and container images. This article uses a zip file as the deployment package. You can deploy an AWS Lambda Function via the AWS Toolkit for Visual Studio or via the AWS Console. We’ll utilize the former method here. While you’re within the Visual Studio IDE, switch to the Solution Explorer Window. Next, select the project, right-click on it, and then select “Publish to AWS Lambda.” The next screen, “Upload to AWS Lambda,” will be displayed as shown below:
[caption id="attachment_1916" align="aligncenter" width="623"]Deploy_the_Lambda_Function Figure 1: Deploy the Lambda Function to AWS[/caption] Next, specify the name and, optionally, the description of the function and other details, as shown in the figure above. Click “Next,” followed by “Upload” to complete the process.

Invoke the Lambda Function

Once the Lambda function is uploaded to AWS, you can test it from either AWS Management Console or from within Visual Studio IDE. To do so from Visual Studio IDE:
  1. Go to All Services -> Lambda in the AWS Management Console.
  2. Choose the Lambda function you want to test.
  3. Select the Test tab.
  4. Select the template you would like to use (we’ll use the simple hello-world template here).
  5. Specify a name for the test event.
  6. Specify the parameter as JSON (see Figure 2 below).
  7. Click “Test” to verify if the email ID is valid.
Figure 2 shows what the output will look like:
[caption id="attachment_1917" align="aligncenter" width="800"]Figure_2_shows Figure 2: The AWS Lambda once executed[/caption]

Accessing Logs from CloudWatch

AWS Lambda automatically logs to AWS CloudWatch by default. It creates a Log Group where you can view all the logs, then dig down to see all the log streams, and finally see all the log events. AWS Lambda is integrated with AWS CloudWatch, allowing you to access these logs easily.
[caption id="attachment_1920" align="aligncenter" width="800"]Accessing_Logs_from_CloudWatch Figure 3: Monitoring AWS Lambda using CloudWatch (Source: Epsagon)[/caption]

Monitoring AWS Lambda Using Epsagon

Monitoring examines the components of an application and provides metrics for deep insights into an application’s overall health. While monitoring may not directly solve issues, it does help in building more stable and reliable applications by gathering data, analyzing it, and alerting as appropriate. Epsagon is an entirely automated, applied observability SaaS solution that allows the monitoring and debugging of cloud services, including containers and serverless computing. It can assist you in identifying bottlenecks in distributed applications by evaluating request flows via payloads, metrics, and events. Epsagon is easy to use and offers automatic data correlation and complete visibility into your applications. It integrates metrics, logs, traces, and alerts into a single dashboard, plus it produces live traces, which help debug serverless applications. Epsagon seamlessly integrates with AWS to get ECS metrics in real-time.

Enabling Tracing in Epsagon

There are three ways you can enable tracing in Lambda functions to view traces:
  • Extending the Epsagon.Dotnet.Lambda.LambdaHandler
  • Using a callback function
  • Setting environment variables
We’ll be using the first option for our example. So, replace the Lambda Function class you created earlier with the following code:
public class Function : LambdaHandler<InputObject, bool> // LambdaHandler<TEvent, TRes>
  {
        public override Task<bool> HandlerFunction(InputObject inputObject,
      ILambdaContext context)
        {
            return Task.FromResult(IsEmailAddressValid(inputObject.EmailAddress));
        }
        private bool IsEmailAddressValid(string emailAddress)
        {
            string pattern = (@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)



amp;quot;); return new Regex(pattern, RegexOptions.IgnoreCase).IsMatch(emailAddress); } }

Integrating Your AWS Account with Your Epsagon Account

If you don’t already have an Epsagon account, you can create one for free at https://app.epsagon.com. To integrate your Epsagon account with your AWS account, log in to your Epsagon account and select Settings -> Integrations -> AWS. Click “Deploy” to deploy a new CloudFormation stack in AWS and associate your Epsagon account with your AWS account: [caption id="attachment_4730" align="aligncenter" width="932"]Associate your Epsagon account with your AWS account Figure 4: Associate your Epsagon account with your AWS account[/caption]
This will then open a new CloudFormation creation wizard in AWS. Specify the name of the stack you want to create and click on “Create stack” to complete the process.
Once your Epsagon account is integrated with AWS, you can start auto-tracing your Lambda Function.

Accessing Amazon CloudWatch Logs for AWS Lambda

Amazon CloudWatch is used to report metrics from AWS Lambda functions. AWS Lambda logs all the requests that come through your Lambda function and saves those logs via Amazon CloudWatch Logs. Follow the steps outlined below to view logs using the Lambda console:
  1. Select your function in the Lambda console.
  2. Select Monitor.
  3. Click “View logs in CloudWatch.”
[caption id="attachment_1922" align="aligncenter" width="942"]Accessing_Amazon_CloudWatch_Logs_for_AWS_Lambda Figure 5: CloudWatch Logs (Source: AWS)[/caption]

Monitoring Metrics from Epsagon

You can view the memory usage, invocations, and duration data in Epsagon as shown below:
[caption id="attachment_1928" align="aligncenter" width="928"]Monitoring_Metrics_from_Epsagon Figure 6: Performance information of your AWS Lambda function[/caption] Whenever an AWS Lambda function is invoked, it will automatically generate a trace. You can invoke the function and view traces under “Trace Search.” To monitor the traces in Epsagon, simply log in to your Epsagon account, and click “Traces” in the Menu:
[caption id="attachment_1930" align="aligncenter" width="924"]Whenever_an_AWS_Lambda Figure 7: Trace information of AWS Lambda functions as viewed in Epsagon[/caption] You can click on any of the traces to see additional details as well, as shown below:
[caption id="attachment_1931" align="aligncenter" width="825"]You_can_click_on Figure 8: Additional details[/caption]
When you click on “Show Logs,” you’ll be able to see the complete log of the request:
[caption id="attachment_1932" align="aligncenter" width="912"]When_you_click_on_“Show Logs,” Figure 9: AWS Lambda request logs as viewed in Epsagon[/caption]

Best Practices

The rule of thumb is that your Lambda Functions must have short timeouts, typically between 3 and 5 seconds, to avoid timeout errors. Another way to prevent AWS lambda timeouts is by using a circuit breaker pattern. If your workload is CPU intensive, you can configure your Lambda Function to use more memory for improved performance.

Summary

AWS Lambda automatically pushes all logs to a CloudWatch Logs Group configured for your Lambda Function. Epsagon uses these logs to generate metrics and monitor serverless applications. Epsagon can retrieve performance metrics from several AWS services such as Lambda, ECS and Fargate, API Gateway, ElasticCache, and more. Check out Epsagon for FREE!
Subscribe card background
Subscribe
Subscribe to
the Shift!

Get emerging insights on emerging technology straight to your inbox.

Unlocking Multi-Cloud Security: Panoptica's Graph-Based Approach

Discover why security teams rely on Panoptica's graph-based technology to navigate and prioritize risks across multi-cloud landscapes, enhancing accuracy and resilience in safeguarding diverse ecosystems.

thumbnail
I
Subscribe
Subscribe
 to
the Shift
!
Get
emerging insights
on emerging technology straight to your inbox.

The Shift keeps you at the forefront of cloud native modern applications, application security, generative AI, quantum computing, and other groundbreaking innovations that are shaping the future of technology.

Outshift Background