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);
}

 

Now, replace the FunctionHandler method of the Function class with the following code:

public bool FunctionHandler(InputObject inputObject, ILambdaContext context)
{
   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:

 

Figure 1: Deploy the Lambda Function to AWS

 

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:

Figure 2: The AWS Lambda once executed

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.

Figure 3: Monitoring AWS Lambda using CloudWatch (Source: Epsagon)

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})+)$");
            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:

Figure 4: Associate your Epsagon account with your AWS account

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.”

Figure 5: CloudWatch Logs (Source: AWS)

Monitoring Metrics from Epsagon

You can view the memory usage, invocations, and duration data in Epsagon as shown below:

Figure 6: Performance information of your AWS Lambda function

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:

Figure 7: Trace information of AWS Lambda functions as viewed in Epsagon

You can click on any of the traces to see additional details as well, as shown below:

Figure 8: Additional details

When you click on “Show Logs,” you’ll be able to see the complete log of the request:

Figure 9: AWS Lambda request logs as viewed in Epsagon

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!

Epsagon is now part of Cisco! Visit the Cisco TechBlog to read technical posts about Emerging Tech and Incubation.

 

Read more

Your Guide for Monitoring AWS Lambda with Epsagon

Debugging AWS Lambda