AWS Cost Efficiency

AWS Lambda – Understanding Pricing and Strategies to Optimize Cost

Did you know?

AWS Lambda can handle billions of function invocations per day! That's enough to power large-scale applications with massive user traffic like Netflix and Twitch, all while you only pay for the time your code runs.

The serverless computing market is growing fast and expected to reach $36.84 billion by 2028. AWS Lambda is a popular choice for businesses because of its streamlined code maintenance, cost-effectiveness, and seamless scalability. As more companies switch to serverless functions, it is crucial to keep Lambda costs down for long-term success. This exponential growth underscores the importance of cost optimization for sustainable business growth. As businesses increasingly rely on AWS Lambda for streamlined operations, reducing Lambda costs becomes important.[1]

This blog post will cover Lambda pricing, factors influencing Lambda costs, and strategies to reduce Lambda expenses.

Factors affecting AWS Lambda cost

Several factors influence AWS Lambda pricing. Function execution time, which is the time taken for functions to execute, impacts costs, calculated in milliseconds. Usage Frequency, measured in requests, determines charges based on how often functions are invoked. Memory Allocation plays a role, with higher memory configurations incurring higher costs. Provisioned Concurrency ensures quick execution but adds an extra cost. Ephemeral Storage usage contributes to overall pricing. HTTP Response Streams and Lambda@Edge usage affect costs due to increased requests and data transfer. Data Transfer to other AWS services and interactions with additional AWS Services may incur extra charges. These factors collectively determine the pricing structure of AWS Lambda.

AWS Lambda Pricing


Pricing Component Description Rate
AWS Lambda Pricing
X86
-Duration
-Request
Arm
-Duration
-Request
Overall pricing for using AWS Lambda services, encompassing various factors such as function execution duration, requests, and additional charges. X86
First 6 Billion GB-seconds / month: $0.0000166667 per GB-s
Next 9 Billion GB-seconds / month: $0.000015 per GB-s
Over 15 Billion GB-seconds / month: $0.0000133334 per GB-s
$0.20 per 1M requests
Arm
First 7.5 Billion GB-seconds / month: $0.0000133334 per GB-s
Next 11.25 Billion GB-seconds / month: $0.0000120001 per GB-s
Over 18.75 Billion GB-seconds / month: $0.0000106667 per GB-s
$0.20 per 1M requests
Ephemeral Storage Temporary storage allocated to Lambda functions, with pricing based on the amount of storage allocated and function execution duration. $0.0000000309 for every GB-second
Provisioned Concurrency
X86
-Duration
-Request
Arm
-Duration
-Request
Enables keeping Lambda functions initialized and hyper-ready to respond quickly, with pricing based on the amount of concurrency configured and duration. X86
$0.0000097222 per GB-s
$0.20 per 1M requests
Arm
$0.0000077778 per GB-s
$0.20 per 1M requests
Lambda HTTP Response Stream Pricing
-processed bytes
Charges for returning HTTP response streams from Lambda functions invoked via specific APIs or URLs, with pricing based on the amount of data written to the response stream $0.008000 per GB
Lambda@Edge Pricing
-Requests
-Duration
Pricing for using Lambda@Edge, a feature of Amazon CloudFront for running code closer to users, with charges based on the number of requests and duration of function execution. $0.60 per 1M requests
$0.00005001 for every GB-second
Data Transfer & Other Charges Charges related to data transfer and additional expenses incurred when using Lambda functions. Data "in" and "out" of Lambda incurs EC2 rates. Intra-region transfers with select services are free. VPC usage may have extra charges.
Costs apply for Lambda functions using other AWS services or transferring data. E.g., S3 read/write requests. See AWS service pages for detailed pricing.

Refer to AWS Lambda Pricing for detailed Pricing on Lambda.

Pricing Example

Scenario: Let say you are running a chat bot like BERT or GPT, on AWS Lambda to improve customer service. The model processes six million requests monthly, with an average duration of 280 ms. It is configured with 4096 MB of memory on an x86 processor and allocated 2048 MB of ephemeral storage

Monthly compute charges:
The monthly compute price is $0.0000166667 per GB-s and the free tier provides 400,000 GB-s.
Total compute (seconds) = 6M * 280ms = 1,680,000 seconds
Total compute (GB-s) = 1,680,000 * 4096 MB/1024 MB = 6,720,000 GB-s
Total compute – AWS Free Tier compute = Monthly billable compute GB- s
6,720,000 GB-s – 400,000 free tier GB-s = 6,320,000 GB-s
Monthly compute charges = 6,320,000 * $0.0000166667 = $105.33

Monthly request charges:
The monthly request price is $0.20 per one million requests and the free tier provides one million requests per month.
Total requests – Free tier requests = monthly billable requests
6 million requests – 1 million free tier requests = 5 million monthly billable requests
Monthly request charges = 5 million * $0.2/million = $1

Monthly ephemeral storage charges:
The monthly ephemeral storage price is $0.0000000309 for every GB-second and Lambda provides 512 MB of storage at no additional cost.
Total compute (seconds) = 6M * 280ms = 1,680,000 seconds
Total billable ephemeral storage = 2048 MB – 512 MB = 1536 MB
Total ephemeral storage (GB-s) = 1,680,000 * 1536 MB/1024 MB = 2,520,000 GB-s
Monthly ephemeral storage charges = 2,520,000 * $0.0000000309 = $0.08

Total monthly charges
Total charges = Compute charges + Request charges + ephemeral charges = $105.33 + $1 + $0.08 = $106.41 per month

Also refer to AWS lambda Pricing for more pricing examples.

Strategies to reduce AWS Lambda cost

1. Right-Sizing

Right-sizing Lambda resources involves optimizing the codebase of Lambda functions to improve execution time. This includes identifying and addressing inefficiencies in the code that lead to longer execution times, ultimately enhancing performance and reducing costs. Additionally, aligning memory allocation with the specific workload requirements helps prevent over-provisioning, ensuring efficient resource utilization. Regular monitoring and refinement of the codebase, in response to changing workload demands, are essential practices for maximizing cost efficiency through right-sizing.

2. Use Amazon Code-Guru Profiler

To reduce Lambda costs effectively, employ Amazon CodeGuru Profiler, a tool that utilizes machine learning to identify costly lines of code. Enable code profiling in function configurations to gather performance data and analyze it to pinpoint resource-intensive areas and bottlenecks. Optimize these sections using best practices and efficient coding techniques. Validate changes to ensure functionality remains intact. Regularly iterate this process for continuous improvement.

3. Use Amazon X-ray

The AWS X-Ray can be used to trace all AWS SDK calls inside Lambda functions. This helps to identify any bottlenecks in the application performance. To optimize Lambda costs using AWS X-Ray, enable tracing for your functions and analyze trace data to identify performance bottlenecks. Optimize code and resources to reduce duration, focusing on minimizing dependencies and package size. Validate changes and iterate regularly for incremental improvements. For Bash functions, ensure efficient code execution and minimize resource usage.

For example, using the AWS CLI:

aws lambda update-function-configuration --function-name my-function --tracing-config Mode=Active

4. Use AWS Graviton2

Graviton2 is an AWS designed ARM-based processor for high-performance, cost-effective computing. Graviton2 functions are designed to deliver up to 19% better performance at 20% lower cost than x86. To use AWS Graviton2 for reducing Lambda costs, consider migrating functions to Graviton2-based instances. Graviton2 processors offer better price-performance ratios compared to traditional x86 processors, potentially reducing overall execution costs for Lambda functions.

To assess the impact of Graviton2 on your code, utilize the Lambda Power Tuning tool to compare it against x86. This tool enables you to visualize and compare both results simultaneously on a single chart.

Image for showing AWS Lambda Power Tuning Results

Explore more on choosing Graviton instances for optimizing Lambda costs and performance with these recommended blogs:

  1. Choosing the right AWS Graviton Instance for your workloads | A Cost Analysis
  2. Best Practices for reducing AWS Graviton instances costs 

These resources will help you make informed decisions when selecting Graviton instances for your Amazon Lambda deployments.

5. Use Compute Savings Plan

To reduce Lambda costs, utilize Compute Savings Plans. AWS Savings Plans is a flexible pricing model offering lower prices compared to on-demand pricing, in exchange for a specific usage commitment (measured in $/hour) for a one- or three-year period. Lambda usage for duration and provisioned concurrency are charged at a discounted Savings Plans rate of up to 17% for a 1- or 3-year term. Analyze usage patterns, purchase aligned plans, and apply them to functions for discounted rates. Monitor usage and adjust plans to optimize savings over time.

6. Event filtering

To reduce Lambda costs using event filtering, you can implement mechanisms to filter out unnecessary events before they trigger Lambda functions. This can be achieved by configuring event sources such as Amazon S3 buckets, Amazon SQS queues, or Amazon Kinesis streams to only send relevant events to Lambda. By filtering out irrelevant events, you can minimize the number of function invocations, thus reducing overall Lambda costs.

Example code snippet

Using S3 Event Filtering:

{
  "Type": "AWS::S3::Bucket",
  "Properties": {
    "BucketName": "example-bucket",
    "NotificationConfiguration": {
      "LambdaConfigurations": [
        {
          "Event": "s3:ObjectCreated:*",
          "Filter": {
            "S3Key": {
              "Rules": [
                {
                  "Name": "suffix",
                  "Value": ".log"
                }
              ]
            }
          },
          "Function": {
            "Fn::GetAtt": ["LambdaFunction", "Arn"]
          }
        }
      ]
    }
  }
}

Autodesk implemented event filtering in their serverless solution, Tailor, to automate the AWS account creation process efficiently, reducing account-creation time by 99%.-Alan Williams ,Enterprise Architect [6]

7. Batch Processing

To reduce Lambda costs, implement batch processing by aggregating similar tasks, triggering batch jobs efficiently, and optimizing processing logic. Implement robust error handling and monitoring mechanisms to ensure reliable execution while continuously seeking optimization opportunities such as fine-tuning batch sizes and resource allocation.

Example code snippet

Create an SQS Queue with Batch Size:

{
  "Type": "AWS::SQS::Queue",
  "Properties": {
    "QueueName": "batch-processing-queue"
  }
}

Lambda Function Configuration:

{
  "Type": "AWS::Lambda::Function",
  "Properties": {
    "FunctionName": "BatchProcessingFunction",
    "Handler": "index.handler",
    "Runtime": "python3.9",
    "Role": {
      "Fn::GetAtt": ["LambdaExecutionRole", "Arn"]
    },
    "Environment": {
      "Variables": {
        "QUEUE_URL": {
          "Ref": "BatchProcessingQueue"
        }
      }
    },
    "Events": {
      "SQSTrigger": {
        "Type": "SQS",
        "Properties": {
          "Queue": {
            "Ref": "BatchProcessingQueue"
          },
          "BatchSize": 10
        }
      }
    }
  }
}

By using batch processing, Netflix can handle multiple events together, optimizing processing logic and resource allocation, thus improving efficiency and reducing operational costs. [7]

Conclusion

In conclusion, by implementing cost optimization strategies such as right-sizing resources, leveraging AWS Graviton2 for cost-effective computing, utilizing Compute Savings Plans, and employing event filtering and batch processing techniques, organizations can effectively reduce Lambda expenses. These optimization strategies not only help in minimizing costs but also enhance operational efficiency and scalability. With a proactive approach to cost optimization, businesses can maximize the value of AWS Lambda while ensuring long-term success in the serverless computing landscape.

References

1. Serverless Architecture Market size worth $ 36.84 Billion, Globally, by 2028 at 21.71% CAGR: Verified Market Research®

2. AWS Lambda Pricing

3. Best practices for working with AWS Lambda functions

4. Architecture and Best Practices - AWS Lambda

5. Cost optimization - AWS Lambda

6. Autodesk Goes Serverless in the AWS Cloud, Reduces Account-Creation Time by 99%

7. Netflix & AWS Lambda Case Study

FAQs

1. What is AWS Lambda pricing based on?

AWS Lambda pricing is based on the number of requests and the duration it takes for your code to execute. Pricing factors include Number of requests ,Duration (measured in milliseconds),Memory allocation, Provisioned concurrency, Data transfer costs.

2. How does AWS Lambda's free tier work?

AWS Lambda offers a free tier that includes 1 million free requests per month and 400,000 GB-seconds of compute time per month. This is automatically applied to your account.

3. What is the cost of an AWS Lambda function invocation?

The cost of an AWS Lambda function invocation is based on the number of requests and the compute time consumed, billed in milliseconds.

4. How do memory and storage affect AWS Lambda costs?

Memory allocated to your Lambda function and the amount of ephemeral storage used directly impact the cost. More memory and storage lead to higher costs.

5. What is Lambda@Edge pricing?

Lambda@Edge pricing is based on the number of requests and the duration of execution for functions deployed at AWS edge locations. This service is tailored for low-latency web content delivery.

Subscribed !
Your information has been submitted
Oops! Something went wrong while submitting the form.

Similar Blog Posts

Maintain Control and Curb Wasted Spend!

Strategical use of SCPs saves more cloud cost than one can imagine. Astuto does that for you!