Introduction
Lambda functions have configurable memory from 128MB to 10GB. When your function tries to allocate more memory than configured, AWS terminates it immediately. This causes the invocation to fail and triggers OOMKilled errors in CloudWatch.
Symptoms
CloudWatch Logs:
```bash $ aws logs filter-log-events --log-group-name /aws/lambda/my-function
Task timed out after 30.00 seconds # Or directly: Runtime exited without providing a reason # Or: OOMKilled ```
Invocation error:
```bash $ aws lambda invoke --function-name my-function output.json
{ "statusCode": 500, "body": "Internal server error" } ```
Memory usage in report:
REPORT RequestId: abc-123 Duration: 15000ms Memory Size: 128MB Max Memory Used: 128MB
# Max Memory Used equals Memory Size = likely OOMCommon Causes
- 1.Memory configuration too low - Default 128MB insufficient for workloads
- 2.Memory leak in code - Accumulating objects without cleanup
- 3.Large data processing - Processing big files or datasets
- 4.Unoptimized dependencies - Heavy libraries consuming memory
- 5.Recursive calls accumulating - Stack overflow or memory accumulation
- 6.Container image size - Large container images consume memory on startup
Step-by-Step Fix
- 1.Check logs for specific error messages
- 2.Verify configuration settings
- 3.Test network connectivity
- 4.Review recent changes
- 5.Apply corrective action
- 6.Verify the fix
Step 1: Check Current Memory Configuration
```bash # Get function memory setting aws lambda get-function-configuration --function-name my-function \ --query 'MemorySize'
# Get actual memory usage from CloudWatch aws cloudwatch get-metric-statistics \ --namespace AWS/Lambda \ --metric-name MemoryUtilization \ --dimensions Name=FunctionName,Value=my-function \ --statistics Maximum \ --period 300 ```
Step 2: Analyze Memory Usage Patterns
```bash # Check recent invocations for memory usage aws logs filter-log-events \ --log-group-name /aws/lambda/my-function \ --filter-pattern "REPORT" \ --query 'events[*].message'
# Parse memory usage from logs aws logs start-query \ --log-group-name /aws/lambda/my-function \ --start-time $(date -d '1 day ago' +%s)000 \ --end-time $(date +%s)000 \ --query-string 'fields @message | filter @message like /Max Memory Used/ | parse @message "Max Memory Used: * MB" as used | stats max(used)'
# Get query results aws logs get-query-results --query-id QUERY_ID ```
Step 3: Increase Memory Allocation
```bash # Lambda memory range: 128MB - 10240MB (10GB) # Increase in 64MB increments
# Update function memory aws lambda update-function-configuration \ --function-name my-function \ --memory-size 512
# Verify the change aws lambda get-function-configuration --function-name my-function \ --query '{Memory:MemorySize,Timeout:Timeout}' ```
Note: Increasing memory also increases CPU proportionally, potentially improving performance.
Step 4: Profile Memory Usage in Code
Python:
```python import tracemalloc import psutil import os
def handler(event, context): # Start memory tracking tracemalloc.start()
# Get current memory process = psutil.Process(os.getpid()) initial_mem = process.memory_info().rss / 1024 / 1024 # MB
# Your function code here result = do_work(event)
# Check memory after work final_mem = process.memory_info().rss / 1024 / 1024 print(f"Memory used: {final_mem - initial_mem} MB")
# Get peak memory current, peak = tracemalloc.get_traced_memory() print(f"Peak memory: {peak / 1024 / 1024} MB")
tracemalloc.stop() return result ```
Node.js:
```javascript exports.handler = async (event) => { const initialMem = process.memoryUsage();
// Your function code const result = await doWork(event);
const finalMem = process.memoryUsage(); console.log('Memory delta:', { rss: (finalMem.rss - initialMem.rss) / 1024 / 1024, heapUsed: (finalMem.heapUsed - initialMem.heapUsed) / 1024 / 1024, external: (finalMem.external - initialMem.external) / 1024 / 1024 });
console.log('Peak heap:', process.memoryUsage().heapUsed / 1024 / 1024, 'MB');
return result; }; ```
Step 5: Optimize Memory-Intensive Operations
```python # BAD: Loading entire file into memory def process_file(bucket, key): s3 = boto3.client('s3') obj = s3.get_object(Bucket=bucket, Key=key) data = obj['Body'].read() # Entire file in memory return process(data)
# GOOD: Stream processing def process_file(bucket, key): s3 = boto3.client('s3') obj = s3.get_object(Bucket=bucket, Key=key) for chunk in obj['Body'].iter_chunks(chunk_size=1024*1024): # 1MB chunks process_chunk(chunk) # Process in chunks
# GOOD: Use generators instead of lists def get_items(): # BAD: return [item for item in large_list] # All in memory # GOOD: for item in large_list: yield item # Process one at a time ```
Step 6: Fix Memory Leaks
Python common leaks:
```python # Check for unclosed resources import gc
def handler(event, context): # Before processing gc.collect()
# Your code
# After processing - force garbage collection gc.collect()
# Check for uncollectable objects print(f"Garbage: {gc.garbage}") ```
Node.js common leaks:
```javascript // Avoid global variables accumulating let cache = {}; // BAD: grows unbounded
// GOOD: Use weak references or bounded cache const cache = new Map(); const MAX_CACHE_SIZE = 100;
function addToCache(key, value) { if (cache.size > MAX_CACHE_SIZE) { // Remove oldest entries const firstKey = cache.keys().next().value; cache.delete(firstKey); } cache.set(key, value); }
// Clean up event listeners process.on('beforeExit', () => { // Remove listeners, clear timers }); ```
Step 7: Optimize Dependencies
```bash # For Python - check package sizes pip show pandas | grep Size pip show numpy | grep Size
# Use lighter alternatives: # pandas -> polars (smaller, faster) # boto3 -> boto3.stub (if only needed for type hints)
# For Node.js - analyze bundle npm run build --analyze
# Use lighter libraries: # lodash -> lodash-es (tree-shakeable) # moment -> date-fns (smaller) ```
Step 8: Set Memory-Based Alarms
# Create CloudWatch alarm for high memory usage
aws cloudwatch put-metric-alarm \
--alarm-name lambda-high-memory \
--namespace AWS/Lambda \
--metric-name MemoryUtilization \
--dimensions Name=FunctionName,Value=my-function \
--statistic Maximum \
--period 60 \
--threshold 90 \
--comparison-operator GreaterThanThreshold \
--evaluation-periods 3 \
--alarm-actions arn:aws:sns:region:account:ops-alertsStep 9: Consider Lambda Power Tuning
Use AWS Lambda Power Tuning tool to find optimal memory:
```bash # Run power tuning step function aws stepfunctions start-execution \ --state-machine-arn arn:aws:states:region:account:stateMachine:lambdaPowerTuning \ --input '{"lambdaARN": "arn:aws:lambda:region:account:function:my-function", "powerValues": [128, 256, 512, 1024, 2048], "num": 100, "parallel": true}'
# Results show: # - Cost per invocation at each memory level # - Average duration at each memory level # - Optimal memory for cost vs speed tradeoff ```
Step 10: Handle Container Image Memory
For Lambda container images:
```bash # Container images use memory for runtime + code # Allocate extra memory for container overhead
# Check image size docker images my-lambda-image
# Image size + runtime overhead + working memory = total needed # Example: 200MB image + 100MB runtime + 300MB work = 600MB minimum
aws lambda update-function-configuration \ --function-name my-container-function \ --memory-size 1024 # Start high for container functions ```
Memory-to-CPU Reference
Lambda memory allocation determines CPU power:
| Memory | CPU Share | Use Case |
|---|---|---|
| 128MB | Low | Simple operations, APIs |
| 256MB | Low | Light processing |
| 512MB | Medium | Normal web functions |
| 1024MB | Medium | Data processing |
| 2048MB | High | Compute-intensive |
| 4096MB+ | High | ML, large datasets |
Verification
```bash # Invoke function and check memory aws lambda invoke --function-name my-function output.json \ --invocation-type RequestResponse
# Check CloudWatch for successful invocations aws logs filter-log-events \ --log-group-name /aws/lambda/my-function \ --filter-pattern "REPORT" \ --start-time $(date -d '10 minutes ago' +%s)000
# Should show Max Memory Used < Memory Size ```
Related Issues
- [Fix AWS Lambda Function Timeout](/articles/fix-aws-lambda-function-timeout)
- [Fix AWS Lambda Cold Start Latency](/articles/fix-aws-lambda-cold-start-latency)
- [Fix AWS Lambda Container Image Pull Failed](/articles/fix-aws-lambda-container-image-pull-failed)
Related Articles
- [AWS troubleshooting: Fix IAM Permission Denied - Complete Tro](fix-iam-permission-denied)
- [AWS cloud troubleshooting: AWS ACM Certificate Pending Validation Because the](aws-acm-certificate-pending-validation-wrong-route53-zone)
- [AWS cloud troubleshooting: AWS ALB Returns 502 Because the Target Closed the ](aws-alb-502-target-closed-connection-keepalive-timeout-mismatch)
- [AWS cloud troubleshooting: Fix AWS ALB CreateListener TargetGroupNotFound Err](aws-alb-createlistener-targetgroupnotfound)
- [AWS cloud troubleshooting: Fix Aws Alb Lambda 502 Bad Gateway Issue in AWS](aws-alb-lambda-502-bad-gateway)
<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "Fix AWS Lambda Memory Limit Exceeded", "description": "Troubleshoot Lambda memory exceeded errors. Analyze usage patterns, increase memory allocation, optimize code, and prevent crashes.", "url": "https://www.fixwikihub.com/fix-aws-lambda-memory-limit-exceeded", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2026-04-01T17:49:16.423Z", "dateModified": "2026-04-01T17:49:16.423Z" } </script>