AWS Lambda: Serverless Computing
AWS Lambda lets you run code without provisioning or managing servers. You upload your code, set a trigger, and Lambda runs it when the trigger fires.
Why Serverless?
Traditional servers require: provisioning, OS updates, security patches, scaling configuration, and capacity planning. Serverless eliminates all of this.
| Aspect | Traditional Server | AWS Lambda | |--------|:-----------------:|:----------:| | Provisioning | Hours to days | Milliseconds | | Scaling | Manual or auto-scaling config | Automatic | | Cost | Pay per hour (idle or not) | Pay per request + compute time | | Maintenance | OS updates, security patches | None (AWS managed) | | Cold start | N/A | ~100ms-1s (first invocation) |
What Is AWS Lambda?
Lambda is a Function-as-a-Service (FaaS) platform. Key concepts:
| Concept | Description | |---------|-------------| | Function | Your code (Python, Node.js, Java, Go, etc.) | | Trigger | Event that invokes your function | | Event | Data passed to the function on invocation | | Execution role | IAM role granting permissions to other AWS services | | Timeout | Max execution time (default 3s, max 900s/15min) | | Memory | 128 MB to 10,240 MB (CPU proportional to memory) |
How Lambda Works
Trigger Sources
| Trigger Type | Example Use Case | |:-------------|-----------------| | API Gateway | REST API endpoint -> Lambda handles request | | S3 Event | File upload -> Lambda processes the file | | DynamoDB Streams | Database change -> Lambda reacts | | SQS Queue | Message in queue -> Lambda processes it | | SNS Topic | Notification -> Lambda forwards or processes | | CloudWatch Events | Scheduled task (cron) -> Lambda runs periodically | | SES | Email received -> Lambda processes the email |
Execution Model
Event occurs (e.g., file uploaded to S3)
-> AWS detects the event
-> Lambda allocates a container
-> Downloads your code
-> Runs the handler function with event data
-> Returns response or performs action
-> Container stays warm for ~5-15 minutes
Building Your First Lambda
Basic Lambda Function
# lambda_function.py
import json
def lambda_handler(event, context):
"""
Main Lambda handler function.
event: Trigger event data (dict)
context: Runtime information object
"""
print(f"Received event: {json.dumps(event)}")
# Process the event
name = event.get("name", "World")
message = f"Hello, {name}!"
return {
"statusCode": 200,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
"body": json.dumps({"message": message})
}
API Gateway Integration
When Lambda is triggered by API Gateway, the event has a specific structure:
def lambda_handler(event, context):
# API Gateway event structure
http_method = event["httpMethod"]
path = event["path"]
query_params = event.get("queryStringParameters", {})
body = json.loads(event.get("body", "{}"))
headers = event.get("headers", {})
print(f"{http_method} {path}")
return {
"statusCode": 200,
"body": json.dumps({"method": http_method, "path": path}),
}
S3 Event Integration
def lambda_handler(event, context):
"""Process S3 file uploads"""
for record in event["Records"]:
bucket = record["s3"]["bucket"]["name"]
key = record["s3"]["object"]["key"]
size = record["s3"]["object"]["size"]
print(f"File uploaded: s3://{bucket}/{key} ({size} bytes)")
# Process the file based on its type
if key.endswith(".jpg") or key.endswith(".png"):
print(f"New image detected: {key}")
# Trigger image processing pipeline
elif key.endswith(".csv"):
print(f"New data file detected: {key}")
# Trigger data processing pipeline
Deployment Options
Option 1: AWS Console (manual)
- Open AWS Lambda Console
- Click "Create function"
- Choose runtime (Python 3.12)
- Paste code in the inline editor
- Click "Deploy"
Option 2: AWS CLI
zip function.zip lambda_function.py
aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip
Option 3: Terraform
resource "aws_lambda_function" "my_function" {
filename = "function.zip"
function_name = "my-function"
role = aws_iam_role.lambda.arn
handler = "lambda_function.lambda_handler"
runtime = "python3.12"
timeout = 30
memory_size = 256
}
Option 4: AWS CDK
import * as lambda_ from "aws-cdk-lib/aws-lambda";
const fn = new lambda_.Function(this, "MyFunction", {
runtime: lambda_.Runtime.PYTHON_3_12,
handler: "lambda_function.lambda_handler",
code: lambda_.Code.fromAsset("./lambda"),
timeout: Duration.seconds(30),
memorySize: 256,
});
Best Practices
| Practice | Why | |----------|-----| | Set appropriate timeout | Prevents runaway functions | | Set minimum memory (128 MB) | Reduces cost for simple functions | | Use environment variables for config | Keeps secrets out of code | | Add structured logging | Makes debugging easier (JSON format) | | Handle errors gracefully | Return meaningful error responses | | Keep functions small | Single-responsibility per function | | Use DLQ for async invocations | Captures failed events for retry |
The Vibe Coding Approach
"Create an AWS Lambda function in Python triggered by API Gateway. Parse query parameters, process the request, and return JSON response with appropriate status codes."
The AI will generate the complete Lambda handler with proper event parsing.
Summary
AWS Lambda is the foundation of serverless computing on AWS. It eliminates server management, scales automatically, and charges only for actual usage.
Key takeaways:
- Lambda runs code in response to events, no server management needed
- Multiple trigger sources: API Gateway, S3, DynamoDB, SQS, SNS, CloudWatch
- Pay per request + compute duration (not per hour)
- Automatic scaling from zero to thousands of concurrent executions
- Cold start adds latency to first invocation (~100ms-1s)
- Timeout: max 15 minutes, memory: 128 MB to 10,240 MB
- Deploy via Console, CLI, Terraform, CDK, or SAM
- Keep functions focused on single responsibilities
What's Next: API Gateway + Lambda
The next chapter shows how to build a complete REST API using API Gateway and Lambda, including CRUD operations with DynamoDB.