AWS Lambda — Serverless Functions
Why AWS Lambda Matters
AWS Lambda is the pioneer of serverless computing. It lets you run code without provisioning or managing servers. You pay only for compute time when your code is running. Lambda is the foundation of serverless architectures on AWS and integrates with dozens of AWS services.
Why this matters for your career:
- Serverless is one of the fastest-growing cloud computing paradigms
- Lambda skills are required for AWS Solutions Architect certifications
- Serverless architectures reduce operational costs by 60-90%
- Event-driven applications are the modern standard for cloud-native development
What Is AWS Lambda?
A Lambda function is a piece of code that runs in response to an event. AWS manages the underlying infrastructure — you just upload your code and define triggers.
Key Characteristics
| Feature | Description | |---------|-------------| | Execution environment | Managed by AWS, no server access | | Language support | Node.js, Python, Java, Go, Ruby, C#, Rust | | Maximum execution time | 15 minutes (900 seconds) | | Memory range | 128 MB to 10,240 MB | | Ephemeral storage | 512 MB to 10,240 MB (/tmp) | | Concurrent executions | 1,000 (soft limit, can be increased) | | Invocation rate | Depends on trigger type | | Cold start latency | 100ms-1s (varies by runtime and memory) |
Basic Lambda Function (Python)
import json
def lambda_handler(event, context):
"""
event: Input data from the trigger
context: Runtime information (request ID, function name, etc.)
"""
print(f"Received event: {json.dumps(event)}")
name = event.get('queryStringParameters', {}).get('name', 'World')
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'message': f'Hello, {name}!',
'functionName': context.function_name,
'awsRequestId': context.aws_request_id
})
}
Common Triggers
| Trigger | Description | Use Case | |---------|-------------|----------| | API Gateway | HTTP requests | REST API endpoints | | S3 | Bucket events (upload, delete) | Image processing, file validation | | DynamoDB Streams | Table changes | Real-time data processing | | SQS | Queue messages | Decoupled microservices | | SNS | Topic notifications | Fan-out notifications | | EventBridge | Scheduled events (cron) | Scheduled tasks, cleanup jobs | | CloudWatch Logs | Log subscription | Log analysis and alerting |
Creating a Lambda Function
Via AWS Console
- Open AWS Lambda Console
- Click "Create function"
- Choose "Author from scratch"
- Name:
hello-world - Runtime: Python 3.12
- Permissions: Create a new basic execution role
- Click "Create function"
- Paste your code in the inline editor
- Click "Deploy"
- Click "Test" to run with a sample event
Via AWS CLI
# Create a deployment package
zip -r function.zip lambda_function.py
# Create the Lambda function
aws lambda create-function \
--function-name hello-world \
--runtime python3.12 \
--role arn:aws:iam::123456789012:role/lambda-execution-role \
--handler lambda_function.lambda_handler \
--zip-file fileb://function.zip
# Invoke the function
aws lambda invoke \
--function-name hello-world \
--payload '{"queryStringParameters": {"name": "Alice"}}' \
response.json
# View logs
aws logs describe-log-groups --log-group-name-prefix /aws/lambda/hello-world
Via Serverless Framework
# serverless.yml
service: hello-world
provider:
name: aws
runtime: python3.12
region: us-east-1
functions:
hello:
handler: lambda_function.lambda_handler
events:
- httpApi:
path: /hello
method: GET
npm install -g serverless
serverless deploy
Lambda Best Practices
| Practice | Reason | |----------|--------| | Keep functions small and single-purpose | Easier to test, debug, and maintain | | Set appropriate memory (CPU scales with memory) | Higher memory = faster execution (and higher cost) | | Minimize cold starts | Use provisioned concurrency for latency-sensitive functions | | Use environment variables for configuration | No hardcoded values | | Implement idempotency | Duplicate events should not cause duplicate side effects | | Handle errors gracefully | Use DLQ (Dead Letter Queue) for failed invocations | | Log structured JSON | Easier log analysis with CloudWatch Logs Insights | | Optimize package size | Smaller deployment packages = faster cold starts |
Cold Starts Explained
When a Lambda function is invoked after being idle, AWS needs to initialize a new execution environment:
Cold start: Download code → Initialize runtime → Run handler
↓ ↓ ↓
100-300ms 50-200ms Execution time
↓ ↓ ↓
Total cold start: ~200ms-1s (depends on runtime and package size)
Warm start: If the same function is invoked again within minutes, the environment is reused and there is no initialization overhead.
Strategies to Reduce Cold Starts
| Strategy | Effectiveness | Cost Impact | |----------|--------------|-------------| | Increase memory (CPU) | Moderate | Higher per-invocation cost | | Use provisioned concurrency | High | Pay for reserved concurrency | | Use SnapStart (Java only) | High (reduces init by 90%) | No extra cost | | Minimize deployment package | Moderate | None | | Use lightweight runtimes (Node.js, Python) | Moderate | None |
Lambda Limits
| Limit | Default | Can Be Increased | |-------|---------|-----------------| | Memory | 128 MB - 10,240 MB | ✅ Yes | | Ephemeral storage (/tmp) | 512 MB | ✅ Yes (up to 10 GB) | | Execution timeout | 3 seconds | ✅ Yes (up to 900s / 15 min) | | Deployment package size | 50 MB (zipped), 250 MB (unzipped) | ❌ No | | Concurrent executions | 1,000 | ✅ Yes (request to AWS) | | Environment variables | 4 KB total | ❌ No | | Function layers | 5 layers | ❌ No |
Summary
AWS Lambda is the foundation of serverless computing on AWS. It runs code in response to events, scales automatically, and charges only when your code runs. Master Lambda functions, triggers, cold starts, and best practices to build efficient serverless applications.
Key takeaways:
- Lambda runs code in response to events without managing servers
- Supported languages: Python, Node.js, Java, Go, Ruby, C#, Rust
- Maximum execution time: 15 minutes
- Common triggers: API Gateway, S3, DynamoDB Streams, SQS, EventBridge
- Cold starts add latency — optimize with provisioned concurrency or SnapsStart
- Keep functions small and single-purpose
- Set environment variables for configuration, never hardcode
- Use structured JSON logging for CloudWatch Logs Insights
What's Next: API Gateway + Lambda
The next chapter connects API Gateway to Lambda to build REST APIs — defining routes, integrating with Lambda, handling CORS, and deploying APIs.