Pricing Login
Pricing
Support
Demo
Interactive demos

Click through interactive platform demos now.

Live demo, real expert

Schedule a platform demo with a Sumo Logic expert.

Start free trial
Back to blog results

August 23, 2016 By Andrew Male

A Brief Tutorial to Understanding, Starting, and Using AWS Lambda

As cloud computing continues to become more and more accessible to businesses (and individuals), it can be a full-time job keeping up with all the tools released by the likes of Amazon, Microsoft, and others. One such tool is AWS Lambda, something that stands to revolutionize the accessibility (and affordability) of distributed computing.

What Are AWS Lambda Functions?

The short answer is that Lambdas are discrete blocks of code which are executed without having to manage the overhead of hardware and software involved in hosting that code. Your code can currently be written in either Python or Node.js, and can be uploaded with project-specific dependencies to facilitate a seemingly endless set of possibilities.

Getting Started with AWS Lambda

Sometimes the best way to understand a system is to simply start using it, so let’s dispense with the introductions and get right into some code. Since I much more frequently use JavaScript in my life, I’ll be doing my examples here in Node.js. The equivalent scripts in Python will rarely be more complicated, and Amazon provides plenty of examples in both languages to allow you the chance to learn.

Once you get through the AWS Console and are creating a new Lambda function, you are first presented with a selection of templates. One of the templates available is a hello-world template in Node.js. Selecting it will bring you to a configuration screen with several options, as well as the following code:

article

There are three important pieces of this code. First, the line of code that creates the function:

exports.handler = function(event, context) {

This code (and the associated closing bracket) is the heart of any Lambda. The Lambda system relies on having this exported handler to know where it will pass execution when the Lambda has been triggered.
Second in line is the event argument for the handler, which receives any input provided by the trigger for the lambda. This example does a good job of showing how the following JSON would be accessible to the code:


{
“key3”: “value3”,
“key2”: “value2”,
“key1”: “value1”
}

The final piece that’s important is the context success/failure call:

context.succeed(event.key1);

That call lets the Lambda host environment know whether or not the lambda was able to complete its work. You can also include (as shown) additional information with your success/failure indication, which is important if you plan on debugging what you’ve created.

Everything else in the code (in this case the console.log() calls) is superfluous as far as the Lambda environment is concerned.

How to Use AWS Lambda Functions

With the basics out of the way, let’s get into the nitty-gritty of showing how the system can be useful to you. Let’s consider the following situation: You are tasked with sending a notification email to a manager whenever someone visits a specific page on a website. For pre-existing reasons, you aren’t able to send email directly from the web server, so you have to create a system that can be remotely invoked to deliver emails.

In the past, maybe you would create a service or cron job that constantly polled a database table for outgoing emails. Maybe you’d even create your own message queue handler to do the work on demand (much better), but you’re still stuck building and maintaining extra infrastructure. Enter Lambdas!

Use Case: Our Email Handler

Starting from the hello-world example provided by Amazon, I’m going to remove everything except the exported handler. I’ll then include the AWS SDK (thankfully built into the Lambda environment, so I can do this without uploading my code in a ZIP file), building a parameter object for use with my AWS SES (Simple Email Service) account, and attempt sending the email through SES before deciding if the operation was successful. Here is the completed code (and the explanation of the lines below):

var AWS = require('aws-sdk');
exports.handler = function(event, context) {
var params = {
Destination: {
ToAddresses: ['manager@domain.com']
},
Message: {
Body: {
Text: {
Data: 'Someone has pinged the website!',
Charset: 'utf8'
}
},
Subject: {
Data: 'A Website Ping',
Charset: 'utf8'
}
},
Source: 'noreply@domain.com',
SourceArn: 'arn-here'
};
new AWS.SES().sendEmail(params, function(err, data) {
if (err) {
context.fail('Failed to send email (' + err + ')');
} else {
context.succeed('The website has been pinged');
}
});
};

The first line accomplishes loading the AWS SDK for use later on in the script. We use our typical handler export, and inside the function build our SES parameters and attempt sending through the SDK.
The parameter object for SES includes the bare minimum of options for an SES email, including the Destination, Message, Source, and SourceArn definitions. The SourceArn is part of AWS’ Identity and Access Management (IAM) system and indicates which email address the lambda is attempting to use for delivery.

Lambda Tutorial Extra Credit

Once this much has been done, we technically have a functioning lambda (hit ‘Test’ on the configuration page to be sure). However, getting it to work within our system would require at least creating an API endpoint to enable remote triggering of the lambda via a REST call. Additionally, there are ways to add triggers for other services within AWS, so choosing the best trigger approach will be based on your technology requirements.

Other Common Lambda Uses?

While utilizing the system for distributed (and thus asynchronous) email notifications/delivery is useful, it’s hardly the end of where Lambdas are useful. Some other ideas for great applications of the feature:

  • On-demand distributed file conversion (change video file encodings, get metadata from uploads, etc)
  • Index updates for services such as ElasticSearch
  • Heavy computations for data analysis

And these are just a few of the potential use cases where Lambdas will shine.

The Brass Tacks of AWS Lambda

Hopefully this has been a quick but educational introduction into the world of AWS Lambdas. We’ve shown how you can perform non-time-sensitive operations outside of the confines of your application with a small amount of effort. Lambdas can accomplish much more—so good luck, and have fun embracing distributed computing.

Editor’s Note: A Brief Tutorial to Understanding, Starting, and Using AWS Lambda is published by the Sumo Logic DevOps Community. If you’d like to learn more or contribute, visit devops.sumologic.com. Also, be sure to visit the Sumo Logic Developersfor free tools, API’s and example code that will enable you to monitor and troubleshoot applications from code to production.

About the Author

Andrew Male (@AndyM84) is a senior engineer at an enterprise development company in Boston, MA. Andrew has been programming from a young age and is entirely self-taught; he has spent time in many corners of the programming world including game/VR work, agency work, and teaching development to students and adults alike. He spends most of his time working on architecture design and pursuing his favorite hobby—physics.

Complete visibility for DevSecOps

Reduce downtime and move from reactive to proactive monitoring.

Sumo Logic cloud-native SaaS analytics

Build, run, and secure modern applications and cloud infrastructures.

Start free trial

Andrew Male

More posts by Andrew Male.

People who read this also enjoyed