AWS Lambda Tutorial – A Guide to Creating Your First Function

Share This:
AWS Lambda

AWS Lambda is one of the leading serverless architectures in the cloud today. It was first-to-market among the major cloud vendors, offers the most competitive pricing, and is employed by Netflix, one of the largest cloud service providers in existence.

In this tutorial, you’ll set up your first AWS Lambda function. You’ll create a service, add a few lines of code, and test it from inside the AWS console. As you progress throughout the tutorial, you’ll also learn why Lambda and Function-as-a-Service have enjoyed widespread adoption over the past few years.

What Is AWS Lambda?

AWS Lambda is a way to run code without creating, managing, or paying for servers. You supply AWS with the code required to run your function, and you pay for the time AWS runs it, and nothing more.

Your code can access any other AWS service or it can run on its own. While there are some rules about how long a function has to respond to a request, there’s almost no limit to what your Lambda can do.

The real power, though, comes from the scalability that Lambda offers you. AWS will scale your code for you, depending on the number of requests it receives. Not having to build and pay for servers is nice. Not having to build and pay for them when your application suddenly goes viral can mean the difference between survival and virtual death.

That all sounds great, but let’s balance out some of the excitement with a quick look at some trade-offs you might have to make if you use AWS Lambda or any other serverless architecture.

Should I Use It?

While AWS Lambda and serverless architecture have some really cool benefits, there are caveats. State management in a serverless architecture requires a bit of a mindset shift. There’s no local state, and traditional database connections are not really applicable to short-lived functions.

Because Lambdas are not persistent, you cannot use connection pooling from the Lambda. If you try to use traditional database connections and AWS spins up 20 lambdas to service 20 requests that come in during a short window, you’re likely to run into data access issues.

Amazon wants to help you solve this data access problem by providing additional services such as DynamoDB or Aurora. This is great to help you solve the connection pooling issue. However, one price you’ll pay for this is vendor lock-in. The more you rely on AWS to manage your infrastructure, the harder it’s going to be to make a decision to move away from that later. That might be fine for your situation, but it’s good to keep in mind. 

Another potential issue is the cold start.

Lambdas can be really cheap because you only pay for what you use, but that means that when the lambda is finally triggered, there will be some overhead to turn it on and service the event. It’s not a significant amount of time, on the order of seconds. Your lambdas will persist for a period of time after the initial cold start, so the cost is not felt on every request. 

So it looks like there are some things to consider regarding data and state management, vendor lock-in, and performance. That being said, you shouldn’t be scared of using lambdas, just be aware of what you’re buying. Now, let’s move on to making your first AWS Lambda! 

AWS Lambda Tutorial

AWS Account

The first thing you’ll need to create a Lambda function is an AWS account if you don’t already have one. The good news is that Amazon makes it very easy to create a login, and you can complete this tutorial using AWS’ free tier. Your Lambda function’s first million requests each month are free!

AWS Lambda Free Limit

Go to the AWS Management Console and create an account.

Create an AWS Account

Once you have an account, log in to AWS.

Create a Lambda

Once you’re at the console, you can start setting up your function. Click on the services menu near the upper right-hand side of the page. Then, you’ll see an entry for Lambda under the Compute menu.

AWS Lambda Option

Click the Lambda entry, and AWS will take you to your Lambda console. Here’s mine.

AWS Lambda Console

If you have a new account, your console will be empty. Either way, click the Create Function button.

Creating a New Lambda Function

Before you proceed, let’s cover some more basics.

Also Read: Amazon Lightsail review

Lambda Functions

Before you create a Lambda function, you need to identify its inputs and triggers, choose a runtime environment, and decide what permissions and role the service will use.

Lambda functions accept JSON-formatted input and usually respond using the same format. The contents of your function’s input and output are closely tied to the event source that will trigger your function.

An obvious event source is a web request. Lambdas can be set up as an HTTP service. But they are capable of a responding to events from within AWS infrastructure, including Alexa, Cloudfront, Simple Storage Service, and the Simple Email Service.

You also need to select a runtime for your function. AWS Lambda supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby. There’s also a Runtime API you can use for other programming languages.

Finally, your function will need an AWS role.

This role defines the entitlements the function has within the AWS platform. AWS security is a deep enough topic that it deserves a series of articles of its own. We’ll use one of the predefined roles AWS offers for new functions.

Pick a Blueprint

Now it’s time to finishing creating your function. You’ll use Python for this function because you can enter the code right into the console.

First, select the Use a Blueprint box in the center of the Create Function page.

AWS Lambda Function Blueprint

Then, type Hello in the search box.

Hello Search

Press enter and AWS will search for blueprints with Hello in the name. One of them will be hello-world-python. Select this and click Configure.

Hello World Python Blueprint

Configure and Create Your Function

Configure Lambda Function

This will take you to a form where you will name your function, select a role, and edit the Python code.

Enter a name, and leave the default role. The default role allows your lambda to send system out logs to CloudWatch.

Let’s take a quick look at the Python code included in the blueprint.

import json print('Loading function') def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) print("value1 = " + event['key1']) print("value2 = " + event['key2']) print("value3 = " + event['key3']) return event['key1'] # Echo back the first key value #raise Exception('Something went wrong')

AWS will call the lambda_handler function each time an event is triggered. This function prints the values associated with three JSON fields: “key1,” “key2,” and “key3.”

Click the Create Function button at the bottom of the form.

Lambda Create Function

You’ve created a Lambda function! Now let’s make an edit using the web editor. Let’s make a simple edit and uncomment the JSON dump on line 7.

Editing Lambda Code

The Save button at the top right of the page should go from being grayed-out to orange. Once you hit the Save button, you should see a banner at the top of the page indicating that the function was updated. Now it’s time to test it. Fortunately, AWS makes this very easy.

Save Changes

Test Your Lambda Function

Now, let’s follow the instructions at the top of the page. Click the Test button that is next to the Save button. AWS will display a form that looks similar to this:

Testing Lambda Function

This test will pass a simple JSON document to your function with the three keys it expects set to “value1,” “value2,” and “value3.” That’s good enough for a start. Click the Create button at the bottom.

Click the Test Button

AWS saves your test, and you can run it from the function page with the Test button. This makes it easy to set up different test cases and run them by name.

Click the test button. AWS will run your test and display a result box.

Successful Execution

The test succeeded, and you can see your log result if you click the details disclosure icon.

Here they are:

START RequestId: d17a8ec3-4231-4bff-8dea-5c3f1a12342e Version: $LATEST
Received event: {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
value1 = value1
value2 = value2
value3 = value3
END RequestId: d17a8ec3-4231-4bff-8dea-5c3f1a12342e
REPORT RequestId: d17a8ec3-4231-4bff-8dea-5c3f1a12342e Duration: 1.54 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 47 MB Init Duration: 136.21 ms

At the top of the log is the “Received event” print statement you just uncommented from the code. Then there’s the rest of the messages in the code. AWS sends standard output to CloudWatch logs for you.

Let’s modify the code and run a different test.

First, uncomment the last line in the code and comment the line before it, so it looks like this:

import json

print('Loading function')


def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("value1 = " + event['key1'])
    print("value2 = " + event['key2'])
    print("value3 = " + event['key3'])
    #return event['key1']  # Echo back the first key value
    raise Exception('Something went wrong')

Now your code will raise an exception each time it’s called. Click the Save button on the top right-hand side of the page.

Next, rerun the test.

Execution Failed

AWS caught the exception, logged it for you, and registered the test as a failure.

Congratulations! You wrote and tested your first AWS Lambda function, but now what?

Next Steps

Now that you can log in to AWS and create functions using Amazon’s blueprints, it’s time to take it to the next level. It is really easy to get a quick lambda function up and running to test it out, but editing lambdas in the web console is not a sustainable development strategy.

You might want to look at how to build and deploy functions from your local machine or a continuous integration server. To do that, you could consider looking into CloudFormation templates for managing lambdas.

Amazon’s Lambda documentation is also really great and is a valuable resource to learn how you can take advantage of serverless architecture, as well as what pitfalls to watch out for. 

Start creating Lambdas with your code, and use them to tie your services together. Lambdas are a powerful mechanism for building scalable applications and a useful tool for coordinating activity between different services via events. Stayed tuned for more posts about functions and serverless computing. Meanwhile, take a look at my other blog posts!

Also Read: How to Run a Serverless WordPress Blog

Share This:

Popular on WPSteam Right Now!

Leave a Reply

Your email address will not be published. Required fields are marked *

I need help with...