AWS Lambda
Introduction
AWS Lambda is a serverless compute service that runs code in response to events and automatically manages the underlying compute resources.
Key Features:
- Serverless architecture
- Automatic scaling
- Pay-per-use pricing
- Multiple runtime support
- Event-driven execution
- Integration with AWS services
Function Development
Node.js Example
exports.handler = async (event) => {
try {
const payload = JSON.parse(event.body);
const result = await processData(payload);
return {
statusCode: 200,
body: JSON.stringify(result)
};
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ error: error.message })
};
}
};
Python Example
import json
import boto3
def lambda_handler(event, context):
try:
# Process S3 event
s3 = boto3.client('s3')
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
# Get object
response = s3.get_object(Bucket=bucket, Key=key)
content = response['Body'].read().decode('utf-8')
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Successfully processed file',
'file': key
})
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps({
'error': str(e)
})
}
Event Sources
Common Triggers
Event Sources:
- API Gateway
- S3 Events
- DynamoDB Streams
- SQS Messages
- CloudWatch Events
- SNS Topics
API Gateway Integration
Resources:
MyApi:
Type: AWS::ApiGateway::RestApi
Properties:
Name: MyLambdaApi
MyLambdaFunction:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Runtime: nodejs14.x
Code:
ZipFile: |
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello from Lambda!' })
};
}
Deployment
CLI Deployment
# Create deployment package
zip -r function.zip .
# Create Lambda function
aws lambda create-function \
--function-name my-function \
--runtime nodejs14.x \
--handler index.handler \
--role arn:aws:iam::123456789012:role/lambda-role \
--zip-file fileb://function.zip
# Update function code
aws lambda update-function-code \
--function-name my-function \
--zip-file fileb://function.zip
Environment Variables
aws lambda update-function-configuration \
--function-name my-function \
--environment "Variables={DB_HOST=mydb.example.com,API_KEY=secret}"
Monitoring
CloudWatch Integration
import logging
# Set up logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info('Event: %s', event)
try:
# Process event
result = process_event(event)
logger.info('Success: %s', result)
return result
except Exception as e:
logger.error('Error: %s', e)
raise
Monitoring Metrics:
- Invocation count
- Error count
- Duration
- Throttles
- Concurrent executions
- Memory usage
Security
IAM Roles
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": "arn:aws:s3:::my-bucket/*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
Security Best Practices
Guidelines:
- Use least privilege permissions
- Encrypt environment variables
- Use VPC when needed
- Implement request validation
- Regular security updates
Best Practices
Performance Optimization
Tips:
- Reuse connections and clients
- Implement caching
- Optimize memory allocation
- Keep functions focused
- Handle errors gracefully
Cost Optimization
Strategies:
- Right-size memory allocation
- Optimize execution time
- Use provisioned concurrency when needed
- Implement appropriate timeouts
- Monitor and analyze costs