Published on 00/00/0000
Last updated on 00/00/0000
Published on 00/00/0000
Last updated on 00/00/0000
Share
Share
INSIGHTS
9 min read
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.
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.
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.
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.
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:
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.
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; }
}
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:
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:
Figure 2 shows what the output will look like:
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.
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.
There are three ways you can enable tracing in Lambda functions to view traces:
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); } }
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"] Figure 4: Associate your Epsagon account with your AWS account[/caption]
Once your Epsagon account is integrated with AWS, you can start auto-tracing your Lambda Function.
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:
You can view the memory usage, invocations, and duration data in Epsagon as shown below:
When you click on “Show Logs,” you’ll be able to see the complete log of the request:
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.
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!
Get emerging insights on innovative technology straight to your inbox.
Discover how AI assistants can revolutionize your business, from automating routine tasks and improving employee productivity to delivering personalized customer experiences and bridging the AI skills gap.
The Shift is Outshift’s exclusive newsletter.
The latest news and updates on generative AI, quantum computing, and other groundbreaking innovations shaping the future of technology.