Amazon Web Services (AWS) offers over 200 services. But, AWS Lambda continues to stand out for several reasons. This AWS Lambda tutorial will help explain Lambda in simple terms so you can decide if the service suits your computing needs.
We’ll cover AWS Lambda, how it works, how it compares to EC2, use cases, benefits, limitations, and more. Additionally, we’ll cover how you can monitor and manage your Lambda costs without the burden of cost management.
What Is AWS Lambda?
AWS Lambda is the event-based serverless computing service for the AWS platform. Event-driven functions are compute events that happen automatically in response to various inputs known as triggers.
This is sometimes called Functions-as-a-Service (FaaS), although the AWS Lambda ecosystem extends beyond that. We’ll discuss event-driven functions later.
Through serverless computing, Lambda enables developers to write and execute code without worrying about administrative tasks.
Those tasks include booking server resources from a cloud provider, maintaining servers in optimal condition, manually scaling RAM, CPU, and memory resources up and down, managing the underlying operating system, or patching security issues.
AWS takes care of all that and more on your developers’ behalf. That way, they can focus on writing code to ensure your customers have smooth service delivery.
All your developers need to do is bring your code to AWS to deploy it for the specific use cases you want to see.
By not needing to buy, maintain, and replace all the hardware, AWS Lambda enables you to develop and run cloud-based operations quickly and cost-effectively. Think of Lambda in AWS as a fully managed service you can use to develop and run cloud-based operations fast and cost-effectively by not needing to buy, maintain, and replace all the hardware. Or the time and money you’d need to hire experienced talent to do all the maintenance work.
Lambda is cost-efficient because it takes advantage of serverless architecture to reduce wasted cloud spend.
Is AWS Lambda Serverless Computing?
No. Instead, AWS Lambda is an essential component of serverless technology for AWS customers. Here’s how:
You need several components to build an application on serverless architecture. One typical architecture is the LAMP stack, which requires:
- Linux operating system
- Apache HTTP server
- MySQL relational database management
- PHP programming language
Another, more specific stack for a web application would look like this:
- Database service
- HTTP gateway service
- Computing service
For people already using AWS, Lambda is the computing service in that stack.
But that’s not why serverless computing can be cost-efficient for running your operations in the cloud. There are two main benefits built into the serverless architecture:
- Pay-per-request pricing model – You only pay for requests Lambda has served and the time it took AWS to serve those requests. Before your compute request, you do not pay a cent like most other architectures that cost money by running continuously without actually doing anything for you.
- Autoscaling – This means the service scales up and down on demand. It increases compute resources such as CPU, RAM, and memory when demand increases. But it shuts some of those down when there is little activity inside the servers. It can automatically scale from zero to practically infinity and back to zero again when your system is idle.
Automatic scaling in serverless technology: An example
Suppose you are an insurance company looking to enjoy the advantages of serverless technology. Your computing requirements would scale up in case of a natural disaster, approaching a policy renewal deadline, or running a discount promotion.
During such times, potentially millions of people would search and log into your insurance company’s website to claim coverage against losses, make claims, or sign up to redeem the discount.
After the incident or promotion, you will notice the following:
- Fewer people log onto your website.
- You would also notice that your servers’ RAM, CPU, memory, etc., usage reduced with reduced server activity.
All this would happen inside your organization’s servers with no human intervention.
In any case, AWS would charge you as much or as little computing power as you use instead of a fixed amount that disregards the peak and off-peak activity you saw.
Still with us?
That’s how cloud service providers who offer serverless services charge them on a pay-as-you-go, usage-based pricing model.
You don’t need to book excess server resources like IT departments used to do in the hopes the extra capacity would handle any unforeseen activity spikes.
You would also not have to pay for provisioned capacity that you didn’t use. AWS offers an option to provision capacity via Amazon EC2, which we’ll compare with Lambda below.
Combine the autoscaling feature with the lack of need to buy or maintain hardware, and you’ll see why Lambda and serverless architecture are so appealing from a cost perspective.
But how does it all come together?
How AWS Lambda Works
As the go-to serverless computing platform for AWS web services, Lambda offers developers a powerful platform for creating and running complex cloud-based applications.
Lambda also seamlessly integrates with other web services in the AWS ecosystem, giving you all the options you need to create large, secure, flexible, and cost-efficient applications in the cloud.
The other AWS services you may need include:
- Database management
- App development
- Backup and restore
- Website Hosting
- E-commerce
- IoT
- Big data analytics
- Chatbots
- Streaming
There are over 200 AWS services now, with more rolling out soon.
Lambda is unique because it automatically runs your code in response to multiple events from various sources within or outside the AWS ecosystem.
That is important because this is how you trigger Lambda functions, which respond by doing what you set them up to do without scaling limitations.
What Is A Lambda Function In AWS?
A Lambda function is the code you run in AWS Lambda.
And how do you do that?
While you don’t need to, be sure to write the code in a stateless style. That means writing code that assumes no affinity to the underlying AWS Lambda infrastructure.
You can create, call, and manage Lambda functions using these five interfaces:
- AWS Management Console
- AWS CloudFormation
- AWS Serverless Application Models (SAM)
- AWS SDKs
- AWS Command Line Interface
Another thing.
Why must you use stateless code for AWS Lambda?
AWS Lambda only allows you to generate as many function copies as the rate at which events come in. That improves scalability and performance while keeping costs reasonably low.
However, Lambda will let you access stateful data when you call other internet-available services such as Amazon DynamoDB and Amazon S3.
What’s in a Lambda function?
AWS Lambda functions into independent containers when you use the Serverless Application Model (SAM) for your code.
The Lambda function is usually a container because it comprises configuration information that relates to that function. That information includes the function name, description, resource requirements, and entry point.
Credit: Serverless-stack
That is the information a function uses to execute itself when triggered.
What Triggers AWS Lambda Functions?
As mentioned earlier, many event sources can trigger Lambda functions (cause Lambda to run your code).
For example, you can trigger a Lambda function by updating tables in Amazon DynamoDB, changing an object in Amazon S3, parsing HTTP requests through Amazon API Gateway, or streaming data through serverless processing with Amazon Kinesis.
More Lambda function triggers include:
- CloudFront
- SQS
- Alexa Smart Home
- SNS
- AWS IoT
- CloudWatch Events (and Logs)
- Application Load Balancer
Speaking of other AWS services, how is Lambda different from Amazon EC2?
What Programming Languages Does AWS Lambda Support?
AWS supports the following languages natively:
- Node.js (14, 12) with Amazon Linux 2 OS.
- Python (3.6, 3.7) with Amazon Linux and (3.8) with Amazon Linux 2 OS.
- Go Runtimes (1.x) with Amazon Linux 2 OS.
- C# runtimes (.NET Core 3.1) with Amazon Linux 2.
- Ruby 2.7 with Amazon Linux 2 OS.
- Java 8 with Amazon Linux OS.
- Java 8 (Java8.la2) and Java 11 with Amazon Linux 2 OS.
- Custom Runtime (provided al2 and provided) with Amazon Linux 2 and Amazon Linux, respectively. So you can give any Docker Container Image as a custom runtime.
Also, AWS provides a Runtime API you can use to write your code in additional languages. AWS maintains the runtimes and provides Amazon Linux and Linux 2 environments to run them in.
AWS Lambda Vs. EC2: How They Compare
Here’s a quick comparison if you are considering Lambda versus Amazon EC2.
Lambda is a fully managed serverless computing service where you only need to upload and run your code to start.
EC2 contrasts that by using cloud-based virtual machines (VMs) architecture. So EC2 will let you control or customize instances, provision capacity, operating system, and network tools, and tweak the underlying infrastructure to improve security.
But that is if you have experience handling those responsibilities.
With EC2, you can migrate existing applications to the cloud more rapidly because you do not have to change their architecture too much. Instead, you can change the EC2 infrastructure to support the app.
But suppose you do not have the experience, budget, and time to swim in a pool of technical responsibilities. In that case, Lambda provides a managed, readily available, highly scalable, and secure serverless computing platform.
You won’t have access to its infrastructure because AWS handles everything on your behalf.
Lambda also only runs in response to a trigger known as an event. Unlike other Platform-as-a-Service (PaaS) offerings, it does not run 24/7. That makes it more cost-effective because AWS charges you for only the resources you use.
AWS Lambda Use Cases: When Should You Use AWS Lambda?
Now you know why you’d want to manage your AWS instances with Lambda rather than EC2.
So here are several powerful AWS Lambda features and how to use them.
- Take advantage of serverless computing
- Execute real-time data processing
- Perform stream processing in real-time
- Automate daily backups
- Transform data as it moves through unique resources
- Use Amazon API Gateways to send requests to Lambda via HTTP end-points
- Use Lambda’s flexibility and cost savings to process clicks in-app
- Process objects you upload to Amazon S3
- Analyze real-time logs
- Where you have a steady stream of instances that last a short time
- Maintain application performance at any scale
- File processing in real-time
- Prepare data for a Machine Learning (ML) model
- Use in the back-end to build applications that are sensitive to latency
- Build web apps that scale up and down seamlessly, even across multiple data centers
- Handle third-party API requests for serverless backend
- Convert documents into different formats in real-time
AWS Lambda is constantly evolving, so you can expect more capabilities soon.
Lambda pros and cons
Here are the common Lambda benefits and drawbacks:
Pros
- Cost-efficient, you pay only for active use, with no idle charges.
- Scales instantly with demand.
- Fully managed service
- Smooth integration with other AWS services
- Supports multiple languages and useful developer tools.
Cons
- Cold start latency, can experience delays when inactive.
- Limits execution limit to 15 minutes at a time
- limits concurrent function executions to 1,000
- Costs can spike if you are unsure how to optimize AWS costs.
- Functions must be stateless for scalability.
AWS Lambda Pricing Explained: How Does The Pay-As-You-Go Pricing Work?
Lambda does not charge by server units. Instead, you pay for the:
- Number of requests AWS served
- The time it took those functions to execute your code (duration)
AWS counts a request immediately as it executes in response to an invoke call or event notification. It then calculates the duration from when your Lambda function (your code) starts executing until it terminates or returns.
The service meters billing in 1-millisecond increments. However, the actual price per duration depends on the amount of memory you allocate to a function.
Once you choose the memory you want for your function within the AWS Lambda resource model, Lambda will assign your function commensurate CPU, RAM, and other compute resources.
That happens each time you change your memory needs.
For Provisioned Concurrency, Lambda counts:
- The amount of concurrency you configure
- The duration you configure it
If you enable Provisioned Concurrency for your functions, you’ll also pay for responses and duration. The amount you pay per request and duration may also depend on your location, although most regions get the same rates.
However, if you are in Cape Town, South Africa, expect the most expensive rate at $0.27/1 million requests and $0.0000221/GB-second.
Here are Lambda prices for distinct memory sizes for which you allocate a function per GB-second duration in Cape Town.
Compare that with charges applied in most other US, European, and Asian locations: $0.20/1 million requests and $0.0000166667/GB-second duration.
Take North Virginia (US) or Stockholm (Europe) as examples.
Here are the duration prices in North Virginia and Stockholm.
Milan also has a different Lambda pricing rate for the rest.
How to calculate AWS Lambda costs
AWS offers every account holder 1 million free requests and 400,000 GB-seconds of compute time monthly. Use less than these numbers, and you won’t have to pay AWS a penny.
But what if you use more than what the AWS free tier offers?
Once you have the requests, duration, and memory data and rates, it’ll be easier to calculate how much you can expect to pay for AWS Lambda for your needs and location.
Here’s an example.
Say your organization is in North Virginia (US), and you allocate your function 512 MB of memory, execute it 4 million times in a month, and run for 150 milliseconds each time. Calculate your AWS Lambda bill like this:
- First, convert 512 MB into GBs by dividing 1024 MB by 1024 MB (the accurate number of MBs in 1 GB), which works out to 1 GB.
- Second, convert 150 milliseconds into seconds by dividing 150 by 1,000 (number of milliseconds in 1 second), which equals 0.15 seconds.
- Then, locate per request and duration charges on the AWS Lambda pricing page and base your rate on your location. The costs are $0.020 per 1 million requests and $0.0000166667/GB-second duration for North Virginia.
- To find your billable duration, multiply the amount of executions X how long they lasted in seconds, so 4 million X 0.15 seconds = 600,000 seconds. Then multiply the number of seconds X memory amount to find the GB-second amount, so 600,000 seconds X 1 GB = 600,000 GB-seconds.
- Remember, AWS offers the first 400,000 GB-seconds free-of-charge, so 600,000 GB-seconds – 400,000 GB-seconds = 200,000 GB-seconds in billable GB-seconds. Now, the monthly compute charges = Billable GB-second duration X cost per GB-second, so 200,000 GB-second X $0.0000166667/GB-second = $3.33334 = $3.33.
- Now, find your billable requests for the month by first taking out 1 million free tier requests from the month’s total requests, so 4,000,000 requests – 1,000,000 requests = 3,000,000 billable requests for the month.
- Then calculate the month’s request charges = Charges per 1 million requests X billable requests for the month, so $0.20 per Million X 3,000,000/1000,000 = $0.2 X 3 = $0.6.
- Now take total compute charges + total request charges = Month’s total charges. That is $3.33 + $0.6 = $3.93 for that month.
That example delves into AWS Lambda pricing only. Depending on the other AWS services you use with Lambda, you may pay more, such as data transfer charges.
That’s not all. Suppose you use four distinct memory sizes to run four different functions.
In that case, you’ll need to calculate the total monthly charges for each of the four functions separately. Then, add the four costs together to arrive at the final sum you’ll pay using commensurate AWS Lambda computing resources.
Additionally, if you need to use Provisioning Concurrency, you’ll also use a slightly different calculation because these charges can be more complex.
Here’s a snapshot from AWS, for example:
Credit: AWS Lambda
After seeing these calculations, if you feel managing your AWS bill can quickly spiral out of your manual calculators’ control like a runaway truck, that’s because it can. It usually does unless you know how to monitor and measure your AWS Lambda spend.
How To Monitor And Measure Lambda Costs
Now, picture this. Over 80% of AWS customers who previously ran containers in AWS had switched to Lambda by January 2020. Many cite Lambda’s potential cost savings and operational ease as major reasons for that move.
But, using Lambda doesn’t always result in desirable cost savings. You have to know how to optimize AWS costs to see a reduction in your Lambda spend or higher ROI.
Many cost optimization tools are notoriously overdependent on tagging, clunky, and too complex. They also do not provide actionable insights, such as mapping costs to specific unit costs, like cost per customer.
That makes their results too complicated for many team members to understand or inform data-driven decisions. Without clear visibility into your Lambda costs, your teams may not know how their work affects everything else, such as your company’s ability to price products or services profitably or work within your engineering budget.
That can be a costly mistake, like Adobe, in 2018, when a dev team working on an Azure project racked up $80,000 per day for a week in unexpected fees. Pinterest, Intuit, CloudOne, and Infor have received surprising cloud computing bills.
Instead, you want a cloud cost intelligence platform that shows you something as insightful and precise as this:
That’s a CloudZero Cost Per Customer report, which helps organizations see their cloud costs mapped to specific customers.
With CloudZero, you can also pull other easy-to-digest reports to help you map AWS costs to specific teams, features, and products. Additionally, our cloud cost intelligence platform will alert you of cost anomalies so you won’t have to realize you are bleeding cash a week later, as Adobe did.
Ultimately, CloudZero gives you the cost visibility to measure, monitor, and optimize your AWS Lambda costs. to see how you can control and predict your cloud spend with confidence.