Overview
Faster execution = lower duration charges.
Key Optimizations
1. Minimize Package Size
Smaller deployment = faster cold starts:
- Remove unused dependencies
- Use tree-shaking for JavaScript
- Import only what you need
- Use Lambda Layers for shared code
Before:
const AWS = require('aws-sdk'); // Entire SDK
const _ = require('lodash'); // Entire library
After:
const S3 = require('aws-sdk/clients/s3'); // Only S3
const get = require('lodash.get'); // Only get function
2. Initialize Outside Handler
Reuse connections across invocations:
import boto3
# GOOD: Initialize outside (reused)
s3 = boto3.client('s3')
def lambda_handler(event, context):
s3.get_object(Bucket='...', Key='...')
# BAD: Initialize inside (created every time)
def lambda_handler(event, context):
s3 = boto3.client('s3')
3. Use /tmp for Caching
Cache static data between invocations:
import os
import json
CACHE_FILE = '/tmp/config.json'
def lambda_handler(event, context):
if os.path.exists(CACHE_FILE):
with open(CACHE_FILE) as f:
config = json.load(f)
else:
config = fetch_config()
with open(CACHE_FILE, 'w') as f:
json.dump(config, f)
The /tmp directory lives on Lambda’s ephemeral storage, which is local to each execution environment, persists only for the lifetime of that environment, and is not durable across cold starts or between functions. By default you get 512 MB, but you can configure ephemeral storage up to 10 GB per function when you need more scratch space—just don’t treat it as permanent storage or a replacement for S3.
4. Optimize Dependencies
Use lightweight alternatives:
| Heavy | Lightweight | Notes |
|---|---|---|
| requests | urllib3 | Often significantly lighter and faster for simple HTTP use cases |
| pandas | built-in csv | For basic CSV parsing, standard libraries avoid the startup and memory overhead of pandas |
| numpy | built-in math | For simple math, built-ins avoid large native dependencies and can reduce cold start time |
5. Use AWS X-Ray
Identify bottlenecks:
from aws_xray_sdk.core import xray_recorder
@xray_recorder.capture('expensive_operation')
def process_data(data):
# Your code
pass
Note: X-Ray adds extra traces and sampling, which can increase both Lambda and X-Ray charges. Enable it selectively (e.g., lower sampling rates, specific functions or stages) and turn it off once you’ve identified and fixed the bottlenecks.
6. CodeGuru Profiler
Find expensive code lines:
- Automatically profiles functions
- Shows which lines cost the most
- Provides optimization recommendations
- Designed to run continuously in production with low overhead (typically a few percent with sampling), but it only supports specific runtimes/agents (for example Java, Python, and Node.js) and is billed separately—check current CodeGuru Profiler pricing and runtime support before enabling it broadly.
Tools
- AWS Lambda Power Tuning - Find optimal memory
- AWS X-Ray - Trace execution
- CodeGuru Profiler - Profile code
- CloudWatch Insights - Analyze logs