Search Tutorials


Top AWS Lambda Interview Questions (2026) | JavaInuse

Top 20 AWS Lambda Interview Questions and Answers


  1. What is AWS Lambda?
  2. What are Lambda execution environments?
  3. What are Lambda triggers and event sources?
  4. What is cold start and how do you mitigate it?
  5. How does Lambda scaling work?
  6. What are Lambda Layers?
  7. What are Lambda environment variables and secrets?
  8. How do you handle errors in Lambda?
  9. What is Lambda Destinations?
  10. How do you configure Lambda VPC access?
  11. What are Lambda extensions?
  12. How do you optimize Lambda performance?
  13. What is Provisioned Concurrency?
  14. How do you monitor and debug Lambda?
  15. What is Lambda@Edge?
  16. How do you implement API Gateway with Lambda?
  17. What are Lambda best practices for security?
  18. How do you handle large payloads in Lambda?
  19. What is AWS SAM for Lambda?
  20. What are Lambda pricing and cost optimization strategies?

1. What is AWS Lambda?

AWS Lambda is a serverless compute service that runs code in response to events without provisioning or managing servers.

Key Features:
- Event-driven execution
- Automatic scaling
- Pay per request and compute time
- Supports multiple runtimes
- Up to 15 minutes execution time

# Basic Lambda Handler (Python)
import json

def lambda_handler(event, context):
    """
    event: Input data (varies by trigger)
    context: Runtime information
    """
    # Process event
    name = event.get('name', 'World')
    
    # Return response
    return {
        'statusCode': 200,
        'body': json.dumps({
            'message': f'Hello, {name}!',
            'requestId': context.aws_request_id
        })
    }

# Context object properties:
# - function_name: Lambda function name
# - memory_limit_in_mb: Memory allocated
# - aws_request_id: Unique request ID
# - get_remaining_time_in_millis(): Time remaining
# - log_group_name: CloudWatch log group

Supported Runtimes:
- Python 3.9, 3.10, 3.11, 3.12
- Node.js 18.x, 20.x
- Java 11, 17, 21
- .NET 6, 8
- Ruby 3.2, 3.3
- Custom Runtime (provided.al2023)

2. What are Lambda execution environments?

Lambda Execution Environment Lifecycle:

INIT Phase (Cold Start):
├── Extension init
├── Runtime init
└── Function init (outside handler)
    └── Initialize connections, load config

INVOKE Phase:
└── Handler execution

SHUTDOWN Phase:
└── Cleanup (extensions, runtime)

# Execution environment reuse
import boto3

# Initialize outside handler (reused across invocations)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')

def lambda_handler(event, context):
    # Handler code (runs each invocation)
    response = table.get_item(Key={'id': event['id']})
    return response['Item']

# Environment reuse benefits:
# - Faster subsequent invocations
# - Connection reuse
# - Cached data persists
# - /tmp directory persists (512MB - 10GB)

Memory and CPU:
MemoryvCPUsUse Case
128 MBFractionSimple tasks
1,769 MB1 vCPUStandard workloads
3,538 MB2 vCPUsParallel processing
10,240 MB6 vCPUsMemory/CPU intensive

3. What are Lambda triggers and event sources?

Lambda Event Sources:

Synchronous (Push):
├── API Gateway
├── Application Load Balancer
├── Cognito
├── Alexa
└── CloudFront (Lambda@Edge)

Asynchronous (Push):
├── S3
├── SNS
├── EventBridge
├── CloudWatch Events
├── CodeCommit
├── IoT
└── CloudFormation

Stream-based (Poll):
├── Kinesis Data Streams
├── DynamoDB Streams
├── Amazon MQ
├── Amazon MSK
└── SQS

# S3 trigger event
{
    "Records": [{
        "eventSource": "aws:s3",
        "eventName": "ObjectCreated:Put",
        "s3": {
            "bucket": {"name": "my-bucket"},
            "object": {"key": "uploads/file.json"}
        }
    }]
}

# SQS trigger event
{
    "Records": [{
        "messageId": "xxx",
        "body": "{\"order_id\": \"123\"}",
        "attributes": {
            "ApproximateReceiveCount": "1"
        }
    }]
}

# Configure S3 trigger
lambda_client.create_event_source_mapping(
    EventSourceArn='arn:aws:s3:::my-bucket',
    FunctionName='my-function',
    Events=['s3:ObjectCreated:*']
)

4. What is cold start and how do you mitigate it?

Cold start occurs when Lambda creates a new execution environment to handle a request.

Cold Start Components:
Cold Start Timeline:
├── Download code (~50-200ms)
├── Start container (~100-200ms)
├── Initialize runtime (~100-500ms)
├── Run init code (~varies)
└── VPC ENI attachment (~500-1000ms, if VPC)

Warm Start:
└── Direct handler invocation (~1-10ms overhead)

Mitigation Strategies:
1. Provisioned Concurrency (Best)
lambda_client.put_provisioned_concurrency_config(
    FunctionName='my-function',
    Qualifier='prod',
    ProvisionedConcurrentExecutions=10
)

2. Keep Functions Warm (EventBridge)
# Scheduled ping every 5 minutes
# Not recommended for production

3. Optimize Package Size
# Smaller = faster download
# Use Lambda Layers for dependencies

4. Optimize Init Code
# Bad: Initialize inside handler
def handler(event, context):
    import pandas as pd  # Slow!
    
# Good: Initialize outside handler
import pandas as pd  # Runs once
def handler(event, context):
    pass

5. Use SnapStart (Java)
# Pre-initializes execution environment
# ~90% reduction in cold starts

6. Choose Optimal Memory
# More memory = more CPU = faster init

5. How does Lambda scaling work?

Lambda Scaling Model:

Concurrency = Requests per second * Duration in seconds

Scaling Limits:
├── Account level: 1,000 concurrent (soft limit)
├── Function level: Unreserved concurrency
├── Burst: 3,000 initial, +500/minute
└── Maximum: 10,000+ (request increase)

# Reserved Concurrency
# Guarantees capacity, limits max
lambda_client.put_function_concurrency(
    FunctionName='critical-function',
    ReservedConcurrentExecutions=100
)

# Scaling scenarios:
1. Synchronous (API Gateway)
   - Returns 429 if throttled
   - Client retries

2. Asynchronous (S3, SNS)
   - Retries twice with delays
   - Dead letter queue on failure

3. Stream (Kinesis, DynamoDB)
   - One Lambda per shard
   - Parallelization factor (1-10)
   - Batching control

# SQS Scaling
Event Source Mapping:
├── BatchSize: 1-10,000
├── MaximumBatchingWindowInSeconds: 0-300
├── MaximumConcurrency: 2-1000
└── Scales based on queue depth




6. What are Lambda Layers?

Lambda Layers package libraries, custom runtimes, or other dependencies for reuse across functions.

Layer Benefits:
- Share code across functions
- Reduce deployment package size
- Manage dependencies separately
- Up to 5 layers per function

# Create layer structure
my-layer/
└── python/
    └── lib/
        └── python3.9/
            └── site-packages/
                ├── requests/
                └── boto3/

# Package and publish layer
zip -r layer.zip python/

aws lambda publish-layer-version \
    --layer-name my-dependencies \
    --zip-file fileb://layer.zip \
    --compatible-runtimes python3.9 python3.10

# Attach layer to function
aws lambda update-function-configuration \
    --function-name my-function \
    --layers arn:aws:lambda:us-east-1:123456789012:layer:my-dependencies:1

# In code, import normally
import requests  # From layer

# Layer paths:
# /opt/python (Python)
# /opt/nodejs (Node.js)
# /opt/bin (binaries)

7. What are Lambda environment variables and secrets?

# Environment Variables
import os

def lambda_handler(event, context):
    db_host = os.environ['DB_HOST']
    api_key = os.environ['API_KEY']  # Encrypted with KMS
    
# Configure via AWS CLI
aws lambda update-function-configuration \
    --function-name my-function \
    --environment "Variables={DB_HOST=mydb.rds.amazonaws.com,ENV=prod}"

# Secrets Management - Best Practices

# Option 1: Secrets Manager (Recommended)
import boto3

secrets = boto3.client('secretsmanager')

# Cache secret outside handler
_cached_secret = None

def get_secret():
    global _cached_secret
    if _cached_secret is None:
        response = secrets.get_secret_value(SecretId='my-secret')
        _cached_secret = json.loads(response['SecretString'])
    return _cached_secret

def lambda_handler(event, context):
    secret = get_secret()
    password = secret['password']

# Option 2: Parameter Store
import boto3

ssm = boto3.client('ssm')
param = ssm.get_parameter(Name='/myapp/db/password', WithDecryption=True)
password = param['Parameter']['Value']

# Option 3: Lambda Extension for caching
# AWS Parameters and Secrets Lambda Extension
# Caches values locally, reduces API calls

8. How do you handle errors in Lambda?

Error Handling Strategies:

# 1. Try-Catch with logging
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    try:
        result = process_event(event)
        return {'statusCode': 200, 'body': json.dumps(result)}
    except ValueError as e:
        logger.error(f"Validation error: {e}")
        return {'statusCode': 400, 'body': str(e)}
    except Exception as e:
        logger.exception("Unexpected error")
        raise  # Re-raise for retry

# 2. Dead Letter Queue (DLQ)
# Configure for async invocations
aws lambda update-function-configuration \
    --function-name my-function \
    --dead-letter-config TargetArn=arn:aws:sqs:...:dlq

# 3. Retry behavior by invocation type:
Synchronous: No automatic retry (caller retries)
Asynchronous: 2 retries with delays
Stream: Retry until expiry or success

# 4. SQS Partial Batch Failure
def lambda_handler(event, context):
    batch_failures = []
    for record in event['Records']:
        try:
            process(record)
        except Exception:
            batch_failures.append({
                'itemIdentifier': record['messageId']
            })
    return {'batchItemFailures': batch_failures}

# 5. Step Functions for complex error handling
# Catch, Retry, Fallback patterns

9. What is Lambda Destinations?

Lambda Destinations route execution results to other AWS services for asynchronous invocations.

# Destination Types:
- SQS Queue
- SNS Topic
- Lambda Function
- EventBridge Event Bus

# Configure destinations
aws lambda put-function-event-invoke-config \
    --function-name my-function \
    --destination-config '{
        "OnSuccess": {
            "Destination": "arn:aws:sqs:us-east-1:123456789012:success-queue"
        },
        "OnFailure": {
            "Destination": "arn:aws:sns:us-east-1:123456789012:failure-topic"
        }
    }'

# Destination payload includes:
{
    "version": "1.0",
    "timestamp": "2024-01-15T10:30:00.000Z",
    "requestContext": {
        "requestId": "xxx",
        "functionArn": "arn:aws:lambda:...",
        "condition": "Success"  # or "RetriesExhausted"
    },
    "requestPayload": {...},  # Original event
    "responseContext": {
        "statusCode": 200
    },
    "responsePayload": {...}  # Function response
}

# Destinations vs DLQ:
# DLQ: Only failures, only SQS/SNS
# Destinations: Success & failure, more services, richer payload

10. How do you configure Lambda VPC access?

# VPC Configuration
aws lambda update-function-configuration \
    --function-name my-function \
    --vpc-config SubnetIds=subnet-xxx,subnet-yyy,SecurityGroupIds=sg-xxx

# VPC Lambda needs:
1. Subnets (private recommended)
2. Security Groups
3. NAT Gateway (for internet access)
4. VPC Endpoints (for AWS services)

# Architecture:
Private Subnet:
├── Lambda ENI
├── RDS Database
└── ElastiCache

NAT Gateway (Public Subnet):
└── Internet access for Lambda

VPC Endpoints (recommended):
├── S3 Gateway Endpoint (free)
├── DynamoDB Gateway Endpoint (free)
├── Secrets Manager Interface Endpoint
├── SQS Interface Endpoint
└── Lambda Interface Endpoint

# IAM Role needs:
{
    "Effect": "Allow",
    "Action": [
        "ec2:CreateNetworkInterface",
        "ec2:DescribeNetworkInterfaces",
        "ec2:DeleteNetworkInterface",
        "ec2:AssignPrivateIpAddresses",
        "ec2:UnassignPrivateIpAddresses"
    ],
    "Resource": "*"
}

# VPC Cold Start (improved with Hyperplane):
# Previously: 10-30 seconds
# Now: ~1 second (Hyperplane ENI)

11. What are Lambda extensions?

Extensions augment Lambda functions with monitoring, security, and governance tools.

Extension Types:

1. Internal Extensions
   - Run in same process as function
   - Share lifecycle
   
2. External Extensions
   - Run as separate process
   - Own lifecycle (init, invoke, shutdown)

Popular Extensions:
├── AWS AppConfig (feature flags)
├── AWS Parameters and Secrets
├── Datadog Agent
├── New Relic Agent
├── Lumigo
└── Custom extensions

# Custom Extension Structure
extension/
├── extensions/
│   └── my-extension (executable)
└── my-extension-lib/
    └── lib.py

# Extension Registration
POST /2020-01-01/extension/register
{
    "events": ["INVOKE", "SHUTDOWN"]
}

# Extension Event Loop
while True:
    response = requests.get(
        f"{LAMBDA_EXTENSION_API}/event/next"
    )
    event = response.json()
    
    if event['eventType'] == 'INVOKE':
        # Process during invocation
        pass
    elif event['eventType'] == 'SHUTDOWN':
        # Cleanup
        break

# Add extension layer
aws lambda update-function-configuration \
    --function-name my-function \
    --layers arn:aws:lambda:us-east-1:123456789012:layer:my-extension:1

12. How do you optimize Lambda performance?

Performance Optimization Strategies:

1. Right-size Memory
# More memory = more CPU
# Test with AWS Lambda Power Tuning
# Find cost-performance sweet spot

2. Minimize Package Size
# Remove unused dependencies
# Use Lambda Layers
# Compile to native (GraalVM, SnapStart)

3. Connection Reuse
import urllib3
http = urllib3.PoolManager()  # Outside handler

def lambda_handler(event, context):
    response = http.request('GET', 'https://api.example.com')

# For AWS SDK
import boto3
from botocore.config import Config

config = Config(
    max_pool_connections=50,
    retries={'max_attempts': 3}
)
dynamodb = boto3.client('dynamodb', config=config)

4. Async Processing
import asyncio
import aiohttp

async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        return await asyncio.gather(*tasks)

def lambda_handler(event, context):
    urls = event['urls']
    results = asyncio.run(fetch_all(urls))

5. Lazy Loading
_heavy_lib = None

def get_heavy_lib():
    global _heavy_lib
    if _heavy_lib is None:
        import heavy_lib
        _heavy_lib = heavy_lib
    return _heavy_lib

6. Use /tmp for Caching
# Cache downloaded files, computed results
# Up to 10GB available

13. What is Provisioned Concurrency?

Provisioned Concurrency pre-initializes execution environments for consistent low latency.

# Configure Provisioned Concurrency
aws lambda put-provisioned-concurrency-config \
    --function-name my-function \
    --qualifier prod \
    --provisioned-concurrent-executions 100

# Auto-scaling Provisioned Concurrency
aws application-autoscaling register-scalable-target \
    --service-namespace lambda \
    --resource-id function:my-function:prod \
    --scalable-dimension lambda:function:ProvisionedConcurrency \
    --min-capacity 5 \
    --max-capacity 100

aws application-autoscaling put-scaling-policy \
    --service-namespace lambda \
    --scalable-dimension lambda:function:ProvisionedConcurrency \
    --resource-id function:my-function:prod \
    --policy-name target-tracking \
    --policy-type TargetTrackingScaling \
    --target-tracking-scaling-policy-configuration '{
        "TargetValue": 0.7,
        "PredefinedMetricSpecification": {
            "PredefinedMetricType": "LambdaProvisionedConcurrencyUtilization"
        },
        "ScaleInCooldown": 60,
        "ScaleOutCooldown": 0
    }'

# When to use:
# - Latency-sensitive applications
# - Predictable traffic patterns
# - APIs with SLA requirements

# Cost consideration:
# Provisioned: Pay for allocated capacity
# On-demand: Pay only when executing

14. How do you monitor and debug Lambda?

Monitoring Tools:

1. CloudWatch Logs
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    logger.info(f"Request: {json.dumps(event)}")
    # Logs go to /aws/lambda/function-name

2. CloudWatch Metrics
- Invocations
- Duration
- Errors
- Throttles
- ConcurrentExecutions
- IteratorAge (streams)

3. X-Ray Tracing
# Enable in function config
aws lambda update-function-configuration \
    --function-name my-function \
    --tracing-config Mode=Active

# In code
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
patch_all()  # Auto-instrument AWS SDK

@xray_recorder.capture('process_data')
def process_data(data):
    # Creates subsegment
    pass

4. CloudWatch Lambda Insights
# Add Lambda Insights Layer
# Provides:
# - CPU, memory, network metrics
# - Cold start tracking
# - Enhanced debugging

5. Custom Metrics
import boto3
cloudwatch = boto3.client('cloudwatch')

cloudwatch.put_metric_data(
    Namespace='MyApp',
    MetricData=[{
        'MetricName': 'OrdersProcessed',
        'Value': order_count,
        'Unit': 'Count'
    }]
)

15. What is Lambda@Edge?

Lambda@Edge runs code at CloudFront edge locations for low-latency request/response manipulation.

Lambda@Edge Triggers:
├── Viewer Request: Before CloudFront forwards to origin
├── Origin Request: Before CloudFront forwards to origin
├── Origin Response: After CloudFront receives from origin
└── Viewer Response: Before CloudFront returns to viewer

# Use Cases:
- URL rewrites/redirects
- A/B testing
- Authentication at edge
- Dynamic content generation
- Header manipulation

# Example: Add security headers
def lambda_handler(event, context):
    response = event['Records'][0]['cf']['response']
    headers = response['headers']
    
    headers['strict-transport-security'] = [{
        'key': 'Strict-Transport-Security',
        'value': 'max-age=63072000'
    }]
    headers['x-content-type-options'] = [{
        'key': 'X-Content-Type-Options',
        'value': 'nosniff'
    }]
    
    return response

# Limitations:
# - Must be in us-east-1
# - Max 5 seconds (viewer), 30 seconds (origin)
# - Max 128 MB memory (viewer), 10 GB (origin)
# - No VPC access
# - No environment variables

16. How do you implement API Gateway with Lambda?

# API Gateway Integration Types:

1. Lambda Proxy (recommended)
# Full request passed to Lambda
def lambda_handler(event, context):
    # event contains:
    # - httpMethod, path, headers, queryStringParameters, body
    
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps({'message': 'Hello'})
    }

2. Lambda Integration (non-proxy)
# Request/response mapping templates
# More control, more complex

# REST API Example
import json

def lambda_handler(event, context):
    http_method = event['httpMethod']
    path = event['path']
    
    if http_method == 'GET' and path == '/users':
        return {
            'statusCode': 200,
            'body': json.dumps(get_users())
        }
    elif http_method == 'POST' and path == '/users':
        body = json.loads(event['body'])
        return {
            'statusCode': 201,
            'body': json.dumps(create_user(body))
        }

# HTTP API (faster, cheaper)
# Supports JWT authorizers
# Simpler configuration

# SAM Template
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      Runtime: python3.11
      Events:
        Api:
          Type: HttpApi
          Properties:
            Path: /users
            Method: GET




17. What are Lambda best practices for security?

Security Best Practices:

1. Least Privilege IAM
{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": ["dynamodb:GetItem", "dynamodb:PutItem"],
        "Resource": "arn:aws:dynamodb:us-east-1:123456789012:table/MyTable"
    }]
}

2. Secrets Management
# Use Secrets Manager or Parameter Store
# Never hardcode credentials
# Use IAM roles, not access keys

3. Input Validation
import json

def lambda_handler(event, context):
    # Validate input
    body = json.loads(event.get('body', '{}'))
    if not body.get('email') or '@' not in body['email']:
        return {'statusCode': 400, 'body': 'Invalid email'}

4. VPC for Sensitive Resources
# Place Lambda in VPC
# Use security groups
# Use VPC endpoints

5. Encryption
# Environment variables encrypted with KMS
# Use KMS for sensitive data
# Enable X-Ray for auditing

6. Code Signing
# Ensure only trusted code runs
aws lambda update-code-signing-config \
    --code-signing-config-arn arn:aws:lambda:...:code-signing-config:xxx \
    --allowed-publishers SigningProfileVersionArns=arn:aws:signer:...

7. Resource Policies
# Control who can invoke
{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Principal": {"Service": "apigateway.amazonaws.com"},
        "Action": "lambda:InvokeFunction",
        "Resource": "arn:aws:lambda:...",
        "Condition": {
            "ArnLike": {"AWS:SourceArn": "arn:aws:execute-api:..."}
        }
    }]
}

18. How do you handle large payloads in Lambda?

Lambda Payload Limits:
- Synchronous: 6 MB request/response
- Asynchronous: 256 KB event
- Response streaming: Up to 20 MB (Node.js)

Strategies for Large Payloads:

1. S3 for Large Data
# Store in S3, pass reference
def lambda_handler(event, context):
    bucket = event['bucket']
    key = event['key']
    
    # Download from S3
    s3 = boto3.client('s3')
    response = s3.get_object(Bucket=bucket, Key=key)
    data = json.loads(response['Body'].read())
    
    # Process and upload result
    result = process(data)
    s3.put_object(
        Bucket=bucket,
        Key=f"results/{key}",
        Body=json.dumps(result)
    )
    
    return {'resultKey': f"results/{key}"}

2. Response Streaming (Node.js)
exports.handler = awslambda.streamifyResponse(
    async (event, responseStream, context) => {
        const metadata = {
            statusCode: 200,
            headers: {'Content-Type': 'text/plain'}
        };
        responseStream = awslambda.HttpResponseStream.from(
            responseStream, metadata
        );
        for (let i = 0; i < 1000; i++) {
            responseStream.write(`Chunk \n`);
        }
        responseStream.end();
    }
);

3. Chunked Processing
# Process in batches
def lambda_handler(event, context):
    for chunk in get_chunks(event['data'], 100):
        process_chunk(chunk)

19. What is AWS SAM for Lambda?

AWS SAM (Serverless Application Model) simplifies building and deploying serverless applications.

# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My Serverless App

Globals:
  Function:
    Timeout: 30
    Runtime: python3.11
    Environment:
      Variables:
        TABLE_NAME: !Ref MyTable

Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: app.handler
      CodeUri: src/
      MemorySize: 256
      Policies:
        - DynamoDBCrudPolicy:
            TableName: !Ref MyTable
      Events:
        ApiEvent:
          Type: HttpApi
          Properties:
            Path: /items
            Method: get

  MyTable:
    Type: AWS::Serverless::SimpleTable
    Properties:
      PrimaryKey:
        Name: id
        Type: String

Outputs:
  ApiUrl:
    Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com"

# SAM CLI Commands
sam init                    # Create project
sam build                   # Build artifacts
sam local invoke           # Test locally
sam local start-api        # Local API Gateway
sam deploy --guided        # Deploy to AWS
sam logs -n MyFunction     # View logs

20. What are Lambda pricing and cost optimization strategies?

Pricing Components:
Lambda Pricing:
├── Requests: $0.20 per 1M requests
├── Duration: $0.0000166667 per GB-second
├── Provisioned Concurrency: $0.0000041667 per GB-second
└── Free Tier: 1M requests, 400,000 GB-seconds/month

Cost Calculation:
Memory: 1024 MB = 1 GB
Duration: 500ms = 0.5 seconds
Requests: 1,000,000

GB-seconds = 1 GB * 0.5s * 1,000,000 = 500,000
Cost = (500,000 *� $0.0000166667) + (1,000,000 * $0.0000002)
     = $8.33 + $0.20 = $8.53

Cost Optimization:
1. Right-size Memory
# Use AWS Lambda Power Tuning
# Find optimal memory for cost/performance

2. Optimize Duration
# Faster code = lower cost
# Connection reuse, async processing

3. Arm64 Architecture
# 20% cheaper, often faster
aws lambda update-function-configuration \
    --function-name my-function \
    --architectures arm64

4. Avoid Over-provisioning
# Monitor ConcurrentExecutions
# Set appropriate reserved concurrency

5. Use Compute Savings Plans
# 17% savings with 1-year commitment

6. Batch Processing
# Process multiple items per invocation
# Fewer invocations = lower request costs

7. Avoid Unnecessary Invocations
# Filter at source (S3 prefix, EventBridge rules)
# Combine related operations


Popular Posts