AWS Tutorials: Lambda basics

Pedro Cabido
AWS Tip
Published in
8 min readOct 6, 2022

--

AWS Lambda Logo

These AWS Tutorials articles will be used as my personal learning notes but at the same time as a way to distribute information to everyone interested in learning AWS.

Today’s post will begin a series about AWS Lambda. AWS Lambda is, for me, one of the most fascinating AWS services because of how they turn something so complex in such a simple way.

What is AWS Lambda?

Extracting from AWS documentation:

Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, and logging.

Let’s break this quote down into plain english:

  • compute service — servers that run computing processes
  • run code without provisioning or managing servers — reference to the old way of software engineering where thinking about bare-metal servers were part of the business
  • high-availability compute infrastructure — meaning that your application will always be available no matter how many AWS servers go down
  • performs all of the administration of the compute resources — another reference to the times where SysAdmins were hired to just manage computing servers
  • including server and operating system maintenance — one of the main exhausting tasks of every SysAdmin, upgrading, updating, securing, protecting an Operating System
  • capacity provisioning and automatic scaling — no need to plan and buy compute capacity in advance, no more excess or lack of compute power
  • logging — compute power with logging built-in? A dream come true for every software engineer

So, this translates into the new buzzword of software engineering: Serverless. Running serverless applications means that we and our team can focus on code development and business domain rather than spend effort on operational, administrative tasks.

With Lambda we can run almost any type of application or backend service as long as the code is in one of the supported languages and frameworks: Node.js, Python, Java, .Net, Go and Ruby.

In Lambda the code is organised in Lambda functions that only run when needed and it is automatically scaled from few requests per day to thousands of requests per second.

The best part is that we only pay when the code is running measured by the consumed compute time. Check here for more pricing details.

Lambda functions can be invoked by the Lambda API or by reacting to events from other AWS services like a request from API Gateway, an update on DynamoDB or S3, etc.

AWS provides a template feature to make the configuration and management of AWS serverless applications easy: AWS Serverless Application Model or SAM (jump to my basics post here or my advance post here on SAM).

Deploy an Hello World app in Lambda

Since we are in a beginners guide, we’ll see how to deploy, invoke and monitor a test application using the AWS console.

  1. Access to our Lambda Console
  2. Click Create Function
  3. Choose the function name, our favourite runtime and click Create Function again.
AWS Lambda Console creating a function

And that’s it! As much as we could think that so much complexity and software engineering could be difficult to set up, we can see that AWS did a great job abstracting all that complexity from the developers.

This is what we have after the function is created:

AWS Lambda console with created function

It’s time to prove the value of Lambda and test it by invoking it and see the results by using the built-in Test tool provided by the Lambda console.

  1. Choose the Test tab
  2. In this tab, the Create new event option should already be selected
  3. Choose a name for the test, leave the Event sharing settings and Template with the default values
  4. Select Save
AWS Lambda console creating a new test event

5. Go back to the Code tab and press the orange Test button

We are automatically presented with the Execution results tab where we can see all the information about the running code.

AWS Lambda Console with running code

From the console we can see:

  • The response from the function with a 200 status code (success) and in the body the function return value “Hello from Lambda!”:
{
"statusCode": 200,
"body": "\"Hello from Lambda!\""
}
  • The REPORT from the Function logs mentioning several relevant informations:
REPORT RequestId: f1719dc5-fec4-4a54-94e7-1fc699869d67 Duration: 1.38 ms Billed Duration: 2 ms Memory Size: 128 MB Max Memory Used: 36 MB Init Duration: 101.81 ms

As we can see, with an extremely quick and easy deployment, we were able to have a fully working function in the AWS Cloud. Since we can integrate these Lambda functions with other AWS services, the possibilities of creating real-world applications are enormous.

How about implementing a little more complex application? Let’s understand how we can receive parameters from the event handler.

Hello World version 2.0

In the first deployed version we’ve tested an event with this body:

{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}

But we don’t take any advantage of it in the application since we’ve a static response of “Hello from Lambda!” .

We can change our Python code to be able to use what comes inside the event object. For that we can create a new Test event like this:

AWS Lambda console creating a new test event with firstName and lastName

Also, we need to update our Python code to receive the event object and use those variables:

import json

def lambda_handler(event, context):
return {
'statusCode': 200,
'body': json.dumps(f'Hello {event["firstName}{event["lastName"]}!')
}

If we run the test again we can see that the response is getting the dynamic information from the event:

{
"statusCode": 200,
"body": "\"Hello Keanu Reeves!\""
}

Logging

AWS Lambda is fully integrated with the AWS services. Which means that when we need to integrate some additional service, we can count on an AWS service for that.

That’s what we have for logging: AWS CloudWatch.

On the Lambda Console we have the Monitor tab which is capable of giving us a preview of Metrics, Logs and Traces.

Especially for logs, we can also select the View logs in CloudWatch and we’ll be sent to the CloudWatch console.

Here we are directly sent to our app’s log group and from there we can see the latest log streams available:

AWS CloudWatch console inside a Log Group

If we select one of those log streams we can see logs from every request sent to our lambda function in a similar fashion that we had directly on the Lambda console on the Execution results tab.

Check here for more information about Lambda logs in CloudWatch.

Clean-up

At the end don’t forget to clean every created resource to avoid unnecessary costs:

  • Lambda function — on the Lambda console, select the function and then choose delete in the Actions menu.
  • Log group — on the CloudWatch console, select the function’s log group and choose delete in the Actions menu.
  • Execution role — on the IAM console, select the function’s role and select Delete role.

Lambda Foundations Concepts

Now it’s time to review some important concepts about Lambda that will be fundamental to know while progressing our study about it.

Trigger

A trigger can be an AWS service configured to invoke a Lambda function. It’s also able to invoke an event source mapping which is a Lambda resource that reads from a data stream or queue and then invokes a function.
Basically, a trigger is everything that ends up running a Lambda function.

Example — an HTTP API endpoint can be configured with a Route to connect to a Lambda function as seen in my previous post here.

Event

Is a document that contains data formatted in JSON that Lambda uses to process by converting it to an object to be passed to the function code.

Example — the event that we’ve created on the test above:

{
"firstName": "Keanu",
"lastName": "Reeves"
}

Execution environment

It’s a secure and isolated environment for the Lambda function runtime. Since Lambda is a fully managed service, this execution environment handles all the processes and resources that our function and all its dependencies require to run.

Deployment package

The Lambda function can be deployed into two types of packages:

  • .zip file — contains all the code and dependencies and Lambda runs the execution environment
  • container image — image that contains the code and dependencies as well as the operating system and the Lambda runtime

Layer

In order to reduce the deployment files and to make the deployment faster, Layers can be used to package libraries and dependencies required by the function.

Layers improve code sharing and separation of responsibilities and we are allowed to have up to 5 layers per function. All the Layer’s content will be available on the /opt directory.

Extension

As the name says, it can extend our Lambdas functionalities by integrating them with other tools like monitoring, observability, etc.

Concurrency / Scaling

When the function is triggered, an instance of the function is provisioned that allows it to process incoming events. Every event will create a new instance. If an instance is running when a new event arrives, Lambda will provision a new instance creating a concurrency scenario.

When the function is invoked faster than it can process the result, Lambda starts to scale up the number of instances running our code. The opposite happens when the incoming traffic decreases and the number of running instances is reduced to be either frozen or stopped.

AWS docs provides a great visual image of that here:

AWS Lambda scaling up and down

Asynchronous / Destination

It’s possible to configure a Lambda function to be invoked synchronously (the client waits for the function response) or asynchronously (where Lambda queues the events to be processed by a specific order).

In asynchronous architectural scenarios Lambda uses destinations to send the events. These destinations can be used for failed events (that need to be queued and then reprocessed) or successfully processed (to be sent to other AWS services).

AWS docs provides a great visual image of that here:

AWS Lambda asynchronous processing diagram

Event source mappings

This is the functionality that allows Lambda to process events from data streams or queues by reading items from Amazon SQS, Amazon Kinesis, DynamoDB, or others.

The items from these sources can be sent in batches that are received by the event source mapping resource and each item can have hundreds or thousands of items.

AWS docs provides a great visual image of that here:

AWS Lambda event source mapping diagram

In the next posts, we will deeply cover this and more details about Lambda with a more advanced perspective.

Thanks for reading. Hope this helps you as much as it helped me. ❤️
If you want to follow my AWS Learning journey, follow me in Medium and Twitter.

More posts like this:

--

--

Platform Engineer @ Cazoo | Eager to learn everything about coding/internet/startups/leadership/product