Parsa Jahanlou
Parsa Jahanlou

Reputation: 139

Is there a way to get the cost of a single lambda function?

I'm creating a report of the lambda functions in my AWS accounts and looking to see if I could get the cost of the previous invokes and how many times a lambda function has been invoked. I've looked into the documentation for lambda, pricing, cloudwatch, and costexplorer but haven't found anything. I'm now wondering if I have to go through multiple API calls. All help is appreciated!

Upvotes: 12

Views: 21574

Answers (3)

magnanimousllamacopter
magnanimousllamacopter

Reputation: 406

The following log insights query will tell you the cost of a lambda function for a given period.

parse @message /Duration:\s*(?<@duration_ms>\d+\.\d+)\s*ms\s*Billed\s*Duration:\s*(?<@billed_duration_ms>\d+)\s*ms\s*Memory\s*Size:\s*(?<@memory_size_mb>\d+)\s*MB/
| filter @message like /REPORT RequestId/
| stats sum(@billed_duration_ms * @memory_size_mb * 1.6279296875e-11 + 2.0e-7) as @cost_dollars_total

You just need to go into log insights and select the correct log stream for your lambda function. This can be modified pretty easily to give you an invocation count as well.

Important Note: The 1.6279296875e-11 + 2.0e-7 factor is based on the per compute-millisecond-megabyte cost for an x86 lambda instance in us-east-1. You may need to adjust it if that doesn't apply to you.

Upvotes: 25

JD D
JD D

Reputation: 8097

One other option is that you add a unique tag to each lambda function. Cost explorer should allow you to filter results based on tag. This will not give you historical data but it should allow you to more easily track of a single function cost via the Billing console and APIs.

Upvotes: 3

JD D
JD D

Reputation: 8097

Since cost per function is not available under billing, I think the best way would be to monitor the Invocation and Duration metrics for that specific Lambda function as you can Sum these and capture the total invocations and durations for period of time.

The invocations and duration are the two components of the Lambda cost and with that information you should be able to calculate it based on the region and amount of memory you allocated.

For example, if you allocated 1 GB of memory to your Lambda function in us-east-1 region and you had the captured the following metrics for a month:

Sum of Invocations: 1,000,000
Sum of Duration (milliseconds): 10,000,000


The monthly cost of that function would be:
100,000*0.20/1,000,000 = $0.20 for invocations
0.0000166667*1,000,000/1,000 = $0.166 for duration
or around $0.37 total

Upvotes: 3

Related Questions