
Stop Wasting Money on Lambda: Automate Right-Sizing Across Your AWS Account
You might have a Lambda function set to use 1024 MB of memory. Its actually using less than 80 MB. This is happening now in your account and you're paying for the allocated memory, not the actual usage.
Stop Wasting Money on Lambda: Automate Right-Sizing Across Your AWS Account
The Silent Cost Leak Nobody Talks About
You know how it feels when you find out a Lambda function is still running with a lot of memory allocated even though it never uses that much. This is not a missed chance to optimize. This is a cost that adds up on your AWS bill every time the function is used.
Here is the truth: the cost of using AWS Lambda depends on two things. How many times the function is used and how memory it uses. While the cost per use is very small memory is the one thing you can control.. Most teams do not control it.
I have seen production accounts where:
- A payment processor function is using a lot of memory. It is only using a small part of it
- An authentication validator function is using a small amount of memory but it is getting close to the limit during peak traffic
- Old report generator functions have not been updated since they were first used and they are still using a lot of memory
The problem is that there is no automated way to find and fix these issues.
Checking everything manually is not practical. Spreadsheets get outdated. The courage to actually change production configurations without a lot of analysis is the barrier.
So we built Lambda Rightsizer. A tool that makes it easy to optimize the memory usage of your Lambda functions like optimizing a database. It comes with safety guarantees, built-in rollback and scripts to apply the changes.
Why This Matters
Let us do the math. Imagine you have 50 Lambda functions:
- 30% of them are using much memory
- The average waste is 300 MB per function
- The average number of times each function is used per day is 1,000
That's 15 functions x 300 MB x 1,000 uses per day = 4.5 GB-seconds per day of pure waste.
At the price of AWS Lambda in the us-east-1 region that is $2.30 per day x 365 = $839.50 per year just for those 15 functions. If you have 200 functions you are looking at $5,000 or more in spending.
And that is before considering the compliance angle: you cannot optimize what you do not measure. Optimizing the memory usage of your Lambda functions is also a practice for cost governance audits.
What Makes This
The Discovery Problem
Finding all your Lambda functions is easy. But figuring out how memory each one actually uses is where most solutions fail.
CloudWatch Logs Insights is powerful. It can be slow. Direct metric queries are not accurate.. Parsing raw logs locally is prone to errors.
Lambda Rightsizer uses a three-step strategy:
- CloudWatch Logs Insights. Server-side aggregation of REPORT log lines
- CloudWatch Logs filter. Event parsing
- CloudWatch Metrics. MaxMemoryUsed metric
The tool tries each step in sequence falling back to the one if necessary. No manual CloudWatch searching is required.
The Analysis Problem
Raw memory numbers do not tell you if a function is correctly sized. You need context:
- Is peak usage near the limit?
- Is usage less than 30% of allocated?
- Are you seeing a reliable trend or just a few outlier invocations?
Lambda Rightsizer applies a utilization band model:
| Utilization Status | Action |
|---|---|---|
| < 30% | Over-provisioned | Reduce to safety floor |
| 30–70% | Optimal | Keep as-is |
| 70–80% Watch | Monitor |
| > 80% Under-provisioned | Increase above safety floor |
But here is the part: the tool never recommends below the observed peak + 20% headroom. This protects against cold-start spikes. Prevents the "we reduced memory and now functions timeout" surprise.
The Risk Problem
Not all sizing recommendations are equally safe. A reduction from 1024 MB to 128 MB on a function that has only had an invocations in the past month is different from a change backed by a lot of telemetry.
Lambda Rightsizer scores every recommendation on a 1-5 scale, based on:
- Sample count
- Data source quality
- Magnitude of change
- P95 proximity to recommended ceiling
High-risk recommendations require confirmation. You can also skip them entirely for deployments.
The Remediation Problem
with perfect analysis applying changes safely requires:
- Pre-flight validation that AWS credentials are valid
- A full change summary before any AWS calls
- Confirmation prompts
- Detailed per-function comments explaining the recommendation
- A companion rollback script in case something goes wrong
- For CI/CD: batch mode without prompts but still with safety guards
Most tools stop at reporting. Lambda Rightsizer generates production- bash scripts that handle all of this.
Architecture
Here is what happens under the hood:
┌─ CLI
│ ├─ Parses arguments
│ └─ Validates AWS credentials
│
├─ Discovery
│ └─ Paginates ListFunctions
│
├─ Metrics Collection. PARALLEL
│ ├─ Tries Logs Insights first
│ ├─ Falls back to Logs filter
│ └─ Falls back to CloudWatch Metrics
│ └─ Returns peak, avg, min P95 memory
│
├─ Optimization
│ ├─ Calculates utilization %
│ ├─ Applies utilization band logic
│ ├─ Computes safety floor
│ ├─ Risk-scores the recommendation
│ └─ Returns OptimizationRecord
│
└─ Output
├─ Console table
├─ CSV export
├─ JSON report
├─ remediation script
├─ rollback script
└─ backup
** design decisions:**
- Parallel metrics collection
- Fallback chains
- Timestamped outputs
- Built-in rollback
- Safety-first remediation
- Zero production impact by default
Key Features
1. Console Dashboard
════════════════════════════════════════════════════════════════════════════════
LAMBDA RIGHTSIZER
Generated: 2024-03-15 14:23:01 UTC Region: us-east-1
Lookback: 14 days Waste threshold: 40%
════════════════════════════════════════════════════════════════════════════════
| Function Runtime | Alloc | Peak | Avg | P95 | Util | Waste | Status |
|--- |--- |--- |--- |--- |--- |--- |--- |--- |
payment-processor | python3.11 | 1024 87 | 72 | 85 | 7% | 91.5% | over-prov |
| order-handler | nodejs18 | 512 201 | 178 198 | 34.8%| 60.7%, over-prov |
| image-resizer Python3.11 | 256 | 231 | 198 | 228 | 77.3%| 9.8% | watch |
auth-validator | nodejs18 | 128 | 98 | 81 | 96 | 63.3%| 23.4% | |
|--- |--- |--- |--- |--- |--- |--- |--- |--- |
| SUMMARY | | | | | | | |
| Total analyzed | 5 | Over-prov: 2 | Optimal: 1 |
| savings | 1152 MB | Under-provisioning: 0 | Watch: 1 |
The colorized report, sorted by severity immediately shows you where the waste is.
2. Three Data Strategies
Not all functions have logs. Not all have CloudWatch metrics history. Lambda Rightsizer tries three approaches to get the data it needs:
- It uses CloudWatch Logs Insights. This is fast, server-side and cheap if you have logs.
- It uses CloudWatch Logs filter. This is slower but it can parse raw REPORT lines.
- It uses CloudWatch Metrics. This is the resort but it is always available even without logs.
It picks the one that succeeds for each function. You will not get an " data" message if there is any signal at all.
3. Multi-Region Support
You can scan one region. You can scan multiple regions at the same time. Each run produces reports so you can compare regions side by side.
4. Filtering
You can scan all functions. You can target specific ones by name:
python -m lambda_rightsizer.main --filter payment order,auth
This is perfect for focusing on high-risk services.
5. Function-Level Risk Scoring
Every recommendation comes with a risk score from 1 to 5. High-risk changes need confirmation:
# Preview before applying
DRY_RUN=true bash remediation_20240315T142301Z.sh
# Apply
bash remediation_20240315T142301Z.sh
# Apply in batch mode
SKIP_HIGH_RISK=true bash remediation_20240315T142301Z.sh
# Force apply all
FORCE=true bash remediation_20240315T142301Z.sh
Lambda Rightsizer is a tool that helps you save money by finding wasted resources in your Lambda functions.
6. Instant Rollback
There is a companion rollback script that restores every function to its memory value:
bash rollback_20240315T142301Z.sh
The backup JSON file ensures you can always go back to the original state even weeks later.
7. Configurable Thresholds
All analysis parameters can be changed via a file called
.env :
LOOKBACK_DAYS=30
UTIL_REDUCE_THRESHOLD=25
UTIL_INCREASE_THRESHOLD=85
SAFETY_BUFFER_FACTOR=1.30
MIN_INVOCATIONS=20
You can change these settings to make the tool more or less aggressive.
8. JSON Reports for Automation
All analysis output is available in JSON for automation:
{
": {
"generated_at": "2024-03-15 14:23:01 UTC"
"region": "us-east-1"
"lookback_days": 14
}
"summary": {
"total": 5
"over_provisioned": 2
"total_savings_mb": 1152
}
"functions": [
{
"function_name": "payment-processor"
"allocated_mb": 1024
"recommended_mb": 128
"status": "over_provisioned"
"risk_score": 2
}
]
}
This JSON report has all the information you need to automate the process.
Real-World Impact
Lets talk about numbers. We ran Lambda Rightsizer against a -sized production account with 60 functions in the us-east-1 region:
| Metric | Before | After |
|---|---|---|
| Total allocated memory | 31,680 MB 18,240 MB |
| Over-provisioned functions | 18 | 0 |
Estimated annual spend | $4,200 | $2,400 |
| Savings |. | $1,800/Year |
That's from one region. Multi-region accounts often see $5,000 to $10,000 in savings.
Getting Started in 5 Minutes
1. Clone and install
git clone <repo>
cd lambda-rightsizer
python -m venv.venv
source.venv/bin/activate
pip install -r requirements.txt
2. Set up IAM
Attach the provided read- policy to your analysis identity:
{
"Version": "2012-10-17"
"Statement": [
{ "Sid": "LambdaDiscoverFunctions" "Action": ["lambda:ListFunctions"] "Resource": "*" }
{ "Sid": "CloudWatchLogsInsights" "Action": ["logs:StartQuery" "logs:GetQueryResults"] "Resource": "arn:aws:logs:*:*:log-group:/aws/lambda/*" }
{ "Sid": "CloudWatchMetrics" "Action": ["cloudwatch:GetMetricStatistics"] "Resource": "*" }
]
}
For remediation add the policy to a separate role.
3. Configure
AWS_REGION=us-east-1
AWS_PROFILE=default
LOOKBACK_DAYS=14
OUTPUT_DIR=./output
You can change these settings to fit your needs.
4. Run the analysis
python -m lambda_rightsizer.main
This will not make any changes. You will get a report and some scripts.
5. Review and apply
cd output/20240315T142301Z/
# Preview what would change
DRY_RUN=true bash remediation_20240315T142301Z.sh
# Apply the changes
bash remediation_20240315T142301Z.sh
# If anything goes wrong instantly rollback
bash rollback_20240315T142301Z.sh
That's it.
Safety Guarantees Built In
Read- by Default
The analysis tool makes zero AWS API calls that modify state. It only reads.
Pre-Change Summary
The generated bash script prints out every change before asking for confirmation.
DRY_RUN Mode
Preview all changes without touching anything:
DRY_RUN=true bash remediation_20240315T142301Z.sh
Risk Scoring
High-risk recommendations are. Require explicit per-function confirmation.
Immediate Rollback
Every applied change can be undone in seconds with the companion rollback script and backup JSON.
Safety Headroom
The tool never recommends below peak observed memory times 1.20 rounded to the 64 MB.
Why We Built This
We realized that cost optimization is only possible at scale. One function is easy to analyze. Fifty functions need tooling. Two hundred functions must be automated.
The other lesson is safety first. Teams will not adopt an optimizer that requires faith. Every recommendation needs context, risk scoring and an escape hatch.
Future Enhancements
We are working on:
- Cost projection module
- Concurrent execution analysis
- Duration analysis
- Cost anomaly detection
- Multi-region orchestration
- Slack integration
- RI and Savings Plan leverage
Open Source and Contribution
Lambda Rightsizer is source. We welcome contributions.
AWS Lambda over-provisioning is real and fixable.. Manual optimization does not scale.
Lambda Rightsizer changes the equation: automated discovery, safe analysis and ready-to-apply remediation with built-in rollback and risk scoring.
In an account you can find $2,000 to $10,000 in annual savings in 30 minutes. Importantly you will gain visibility into how your functions actually behave in production. And that visibility is worth more, than the cost savings.
Stop leaving money on the table. Get started today.
To get started you need to do a things.
First you have to get a copy of the repository by running the command to clone it.
You do this with the command
git clone <repo> .Then you go into the lambda-rightsizer folder by typing
cd lambda-rightsizer .Next you run the program with
python -m lambda_rightsizer.main .Then run one remediation script.
Your Chief Financial Officer will thank you.
Questions?
- Documentation: See the README for detailed configuration options, architecture diagrams and troubleshooting
- Examples: Check output/ for sample reports and scripts, from real-world runs
- Issues: Open a GitHub issue or PR with questions, bugs or feature requests
- Connect with me on [ LinkedIn] ( https://www.linkedin.com/in/rushabh-trivedi-361094168/ )
- If you like this post, put a start on the Github
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article