Lambda is pay-per-use, so it should be cheap — until it is not. A recursive invocation bug, an oversized memory setting, or a missing timeout can turn a $2/month function into a $200 surprise. This post covers the most common causes of unexpected AWS Lambda costs and what to do about each one.
The AWS CLI examples in this guide are run on WSL2 Ubuntu in Windows, but they work the same on any system with the AWS CLI installed.
How Lambda Pricing Works
Lambda charges for two things:
- Requests — $0.20 per 1 million invocations
- Duration — billed per millisecond based on allocated memory
The free tier covers 1 million requests and 400,000 GB-seconds per month. Most small workloads fit within this. Costs spike when duration or invocation count goes higher than expected — and that usually happens because of one of the issues below.
Common AWS Lambda Cost Traps
1. Recursive or Infinite Loop Invocations
This is the most expensive mistake. It happens when a Lambda function triggers itself — directly or through a chain of services. Classic example: a function writes to an S3 bucket that has an event notification triggering the same function.
AWS added recursive loop detection in 2023 and has extended it since. It now covers loops between Lambda and Amazon SQS, Amazon SNS, Amazon S3 (added October 2024) and EventBridge custom event buses. When Lambda detects a loop (after about 16 recursive calls), it stops the invocation. The event goes to a dead-letter queue or on-failure destination only if you configured one; otherwise it is dropped.
Detection is on by default (Terminate) and is set per function. Check that nobody switched it off:
aws lambda get-function-recursion-config --function-name my-function
# Restore the default if it returns "Allow"
aws lambda put-function-recursion-config \
--function-name my-function \
--recursive-loop Terminate
Detection is a safety net, not a design. Loops through services it doesn’t cover (DynamoDB Streams, for example) are not stopped. For S3-triggered Lambdas, the safest pattern is still to write output to a different bucket or prefix than the one triggering the function. If you must write to the same bucket, use a prefix filter on the trigger so the output does not match. If your trigger arrives wrapped in SNS or SQS, see How to Extract S3 Payload from SQS/SNS Event in AWS Lambda to read the object key you need for that check.
2. Timeout Set Too High
The default Lambda timeout is 3 seconds, but many developers bump it to the maximum (15 minutes) “just in case.” The problem: if something goes wrong — a downstream API hangs, a database connection stalls — the function sits there burning duration charges until it times out.
Set the timeout to just above the expected execution time. If your function normally finishes in 8 seconds, a 15-second timeout is reasonable. A 900-second timeout is not. Check the function’s Duration metric in CloudWatch and size the timeout based on real data. If a job genuinely needs longer than Lambda allows, split the work instead, as shown in How to Avoid AWS Lambda Timeout When Processing HubSpot Records.
3. Over-Provisioned Memory
Lambda bills per GB-second. A function configured with 3,008 MB that only uses 200 MB is paying 15x more per millisecond than necessary. But there is a tradeoff — more memory also means more CPU. Sometimes bumping memory from 128 MB to 256 MB makes a function run 3x faster, which actually costs less overall.
The right approach is to test different memory settings and find the lowest cost. The open-source AWS Lambda Power Tuning tool (by Alex Casalboni) does this automatically — it runs your function at multiple memory configurations and shows you the best price-performance point. You can find it at alexcasalboni/aws-lambda-power-tuning on GitHub.
4. CloudWatch Logs Retention
Every Lambda invocation writes logs to CloudWatch. By default, these logs are kept forever. Over months, log storage adds up — especially for high-traffic functions or functions that log verbose output.
Set a retention policy on every Lambda log group. For most functions, 7–30 days is enough. You can do this from the console or with the CLI:
aws logs put-retention-policy \
--log-group-name /aws/lambda/my-function \
--retention-in-days 14
Retention controls storage, but you also pay for every GB ingested. Switch noisy functions to JSON logs and raise the log level so debug output is dropped before it reaches CloudWatch:
aws lambda update-function-configuration \
--function-name my-function \
--logging-config LogFormat=JSON,ApplicationLogLevel=WARN,SystemLogLevel=WARN
Log-level filtering only works with the JSON log format, and your code needs to log through the runtime’s standard logger for the level to apply.
If you have dozens of Lambda functions with bloated logs, you can bulk-delete old CloudWatch logs with a Python script.
5. SQS Polling on Empty Queues
When Lambda is configured with an SQS event source, it continuously polls the queue. If the queue is empty most of the time, those polling requests still count as SQS API calls — and SQS charges $0.40 per million requests. For rarely-used queues, this background polling can cost more than the actual processing.
Changing the batching window does not stop this background polling. A larger BatchSize or MaximumBatchingWindowInSeconds only reduces how many times your function is invoked when messages do arrive, by packing more messages into each call. To stop polling a queue that is idle for long periods, disable the event source mapping and re-enable it when needed:
aws lambda update-event-source-mapping \
--uuid your-mapping-uuid \
--no-enabled
Get the UUID from aws lambda list-event-source-mappings --function-name my-function. Also, make sure your SQS visibility timeout is set correctly — if messages become visible again before Lambda finishes processing, they get reprocessed, doubling invocations.
6. Provisioned Concurrency Left On
Provisioned Concurrency keeps a set number of Lambda instances warm to avoid cold starts. It charges you for every second those instances are kept warm — even if no requests come in. If you enabled it for a demo or a load test and forgot to turn it off, you are paying 24/7 for idle capacity.
list-provisioned-concurrency-configs only checks one function at a time, so loop over every function in the Region:
for fn in $(aws lambda list-functions --query 'Functions[].FunctionName' --output text); do
aws lambda list-provisioned-concurrency-configs \
--function-name "$fn" \
--query 'ProvisionedConcurrencyConfigs[].[FunctionArn,AllocatedProvisionedConcurrentExecutions]' \
--output text
done
To remove it:
aws lambda delete-provisioned-concurrency-config \
--function-name my-function \
--qualifier my-alias
7. No Concurrency Limit
By default, all functions in an account share a quota of 1,000 concurrent executions per Region (new accounts can start lower, and you can request an increase). One function can use most of that pool on its own. If a spike hits — a sudden burst of S3 events, an SQS backlog, or a DDoS on an API Gateway — Lambda scales out to handle it, and you pay for every concurrent execution.
Set a reserved concurrency limit on functions to cap how many run at once:
aws lambda put-function-concurrency \
--function-name my-function \
--reserved-concurrent-executions 50
This limits the function to 50 concurrent executions. Excess invocations get throttled (HTTP 429) instead of running. This protects both your costs and downstream services from being overwhelmed.
8. Running on x86 When arm64 Would Do
Lambda functions on the arm64 architecture (AWS Graviton) are billed about 20% less per GB-second than x86_64, and that discount also applies to provisioned concurrency. Pure Python, Node.js, and Java code usually runs unchanged. Functions with compiled dependencies or container images need arm64 builds, so test before you switch.
Set it in your infrastructure code, for example Architectures: [arm64] on a SAM function. See How to Deploy AWS Lambda with SAM and GitLab CI/CD Using OIDC for a full SAM pipeline.
Set Up a Billing Alarm
A billing alarm catches cost spikes early. This creates a CloudWatch alarm that emails you when estimated charges exceed $10:
aws cloudwatch put-metric-alarm \
--alarm-name "billing-alarm-10usd" \
--metric-name EstimatedCharges \
--namespace AWS/Billing \
--statistic Maximum \
--period 21600 \
--threshold 10 \
--comparison-operator GreaterThanThreshold \
--dimensions Name=Currency,Value=USD \
--evaluation-periods 1 \
--alarm-actions arn:aws:sns:us-east-1:123456789012:billing-alerts
--threshold 10— triggers when charges exceed $10 (adjust to your budget)--period 21600— checks every 6 hours--alarm-actions— the SNS topic ARN that sends the email notification
You need to enable billing alerts first in the AWS Billing console under Billing Preferences. The alarm must be created in us-east-1 — billing metrics are only available in that region.
AWS Budgets and Cost Anomaly Detection
Two other tools are worth turning on alongside the alarm:
- AWS Budgets — set a monthly budget (overall or filtered to Lambda) and get alerts on forecasted spend, so you hear about a spike before the month ends rather than after.
- Cost Anomaly Detection — free, in the Billing console. It learns your normal spend per service and alerts you when something jumps, which suits Lambda loops that start mid-month.
Monitor Lambda Costs with Cost Explorer
AWS Cost Explorer lets you filter costs by service and see exactly which Lambda functions are driving spend. Open Cost Explorer, filter by “AWS Lambda”, and group by “API Operation” to see the breakdown between invocations, duration, and provisioned concurrency.
For function-level cost visibility, enable cost allocation tags. Tag your Lambda functions with a project or team name, activate those tags in the Billing console, and Cost Explorer will show costs per tag within 24 hours.
Quick Checklist
| Action | Why It Matters |
|---|---|
| Set timeouts to realistic values | Prevents hung functions from burning duration charges |
| Right-size memory with Power Tuning | Finds the cheapest memory/speed combination |
| Set CloudWatch log retention to 7-30 days | Stops log storage from growing forever |
| Add reserved concurrency limits | Caps runaway scaling during traffic spikes |
| Check for provisioned concurrency left on | Avoid paying for idle warm instances |
| Avoid recursive invocation patterns | Prevents infinite loops that rack up millions of calls |
| Set SQS visibility timeout correctly | Prevents duplicate processing and double charges |
| Use arm64 where your code supports it | About 20% cheaper duration pricing |
| Use JSON logs with a WARN log level | Cuts CloudWatch ingestion from debug output |
| Create a billing alarm | Get notified before a small issue becomes a big bill |
| Enable Budgets and Cost Anomaly Detection | Catches unusual spend and forecasted overruns |
| Tag functions and use Cost Explorer | Know exactly which functions cost what |
Conclusion
Most unexpected Lambda costs come from a handful of misconfigurations — high timeouts, missing concurrency limits, infinite retention logs, or recursive triggers. Setting realistic limits and a billing alarm catches problems early before they become expensive.
If your Lambda functions process data from queues, make sure to also read Setting Up Cross-Account SNS to SQS Subscription in AWS to structure your event-driven architecture correctly. For monitoring Lambda performance over time, consider setting up Datadog monitoring for your Lambda functions.


