Before you dive into Lambda code optimization, check out these 5 Lambda tips that can slash your AWS bill without changing a single line of code ๐ฐ
Every AWS project I start, I'll typically have 5 things I look out for to save Lambda costs:
1๏ธโฃ Set up proper cost tags - can't optimize what you don't measure!
We need to understand our costs. Activate granular costs to see your daily usage. And set up cost-allocation tags.
I typically use the function names or the CloudFormation stacks as tags. Then find your Lambda functions that emit 80% of the costs and ignore the rest.
2๏ธโฃ Cut that memory allocation - most functions use way less than they're given
Lambda bills by GB/ms. That means you can optimize on two different dimensions:
1. Memory
2. Execution time
Start with memory. Check if your Lambda functions are overprovisioned.
If they are -> Lower the memory.
โ ๏ธ But be cautious: Lowering memory also means lowering compute. Use Lambda Powertuning to find out the perfect value
3๏ธโฃ Lower those timeouts
The second dimension to improve: Execution time
Don't use the maximum timeout of 15 minutes. Find out how long your Lambda functions should run, set it as a maximum timeout, and figure out the outlier.
You will save money once you fix things that let your Lambda run longer than needed. Often, removing the outliers will already help.
But have alerts in place so you'll find those!
4๏ธโฃ Switch to ARM - easy 34% savings (just test your deps first!)
With ARM-Graviton, you save up to 34% without doing anything. For new Lambda,s I use ARM as a default.
Try switching your Lambda to ARM.
But test your workloads!
- ARM can increase your dependency size
- Some dependencies don't work on ARM (e.g., Pydantic v1)
If everything works -> Switch
5๏ธโฃ Use Lambda less -> Batching & Caching
By invoking your Lambda functions fewer times, you will save money as well (obvious, isn't it).
You can do that by making use of batching and caching:
- Batch your messages and work on them in parallel
- Cache your data closer to the user (Edge, API, Database, Redis)
After you did all of that, you can start with code improvements.