Serverless Computing with AWS Lambda
Run Code Without Servers β Automatically Scalable and Event-Driven
AWS Lambda is at the heart of serverless architectureβit allows developers to run backend code without provisioning or managing servers. You just write the function, deploy it, and AWS handles the rest: scalability, availability, and infrastructure.
This chapter provides deep insights, real use cases, architecture diagrams, and live code examples in Python and Node.js.
β‘ What is AWS Lambda?
AWS Lambda is a compute service that runs your code in response to events and automatically manages the underlying infrastructure.
- No servers to manage
- You pay only for the compute time you consume
- Automatically scales from zero to thousands of requests per second
- Supports multiple runtimes: Python, Node.js, Java, Go, .NET
π§± Key Concepts in Lambda
Term | Description |
---|---|
Function | The code you upload or write inline |
Event | The trigger (e.g., HTTP request, S3 upload) |
Handler | The function entry point (e.g., lambda_handler ) |
Runtime | Language environment (e.g., Python 3.9) |
Timeout | Max execution time (up to 15 mins) |
Memory | Adjustable from 128MB to 10GB (affects CPU) |
Concurrency | Number of simultaneous executions |
Cold Start | Initial latency when Lambda starts a new container |
How AWS Lambda Works β Architecture Diagram (ASCII)
[Event Source]
(S3 / API Gateway / DynamoDB / Schedule)
β
+-------------+
| AWS Lambda |
+-------------+
β
[Your Code Executes]
β
[Other AWS Services or Response]
Common Event Sources (Triggers)
Source | Example Use Case |
---|---|
S3 | Process image upload, resize |
API Gateway | Backend for web/mobile apps |
CloudWatch Events | Scheduled cron jobs |
DynamoDB Streams | React to DB changes |
SQS | Queue processing |
SNS | Notification-based triggers |
Step Functions | Serverless workflows |
β AWS supports dozens of event sources, both native and third-party.
Creating a Lambda Function (Console & CLI)
β Using Console (Quick Steps):
- Go to AWS Lambda β Create function
- Choose Author from Scratch
- Name:
image-processor
- Runtime:
Python 3.9
- Permissions: Create a new role with S3 access
- Click Create Function
- Add code + test event
- Save and Deploy
β Using AWS CLI
zip function.zip index.py
aws lambda create-function \
--function-name my-function \
--runtime python3.9 \
--role arn:aws:iam::123456789012:role/my-lambda-role \
--handler index.lambda_handler \
--zip-file fileb://function.zip
Example Lambda Code
πΈ Python (Resizing an Image in S3)
import boto3
from PIL import Image
import io
def lambda_handler(event, context):
s3 = boto3.client('s3')
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
response = s3.get_object(Bucket=bucket, Key=key)
image = Image.open(response['Body'])
image.thumbnail((128, 128))
buffer = io.BytesIO()
image.save(buffer, 'JPEG')
buffer.seek(0)
s3.put_object(Bucket=bucket, Key=f"thumbs/{key}", Body=buffer)
return {"status": "Thumbnail created"}
πΉ Node.js (Return JSON API Response)
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: "Hello from Lambda!" }),
};
};
Lambda Layers β Reusable Code and Libraries
Layers are ZIP archives of libraries or dependencies that can be shared across Lambda functions.
- Use for: Python packages (e.g., Pandas), image libraries, Node.js modules
- Speeds up deployment & promotes reuse
aws lambda publish-layer-version \
--layer-name my-layer \
--zip-file fileb://layer.zip \
--compatible-runtimes python3.9
Lambda Limits (as of 2025)
Feature | Limit |
---|---|
Timeout | 15 minutes |
Memory | 128MB β 10GB |
Package size (zip) | 50MB (direct) / 250MB (with S3) |
Concurrency (default) | 1000 per account (can increase) |
Environment variables | 4KB |
π§ Use Provisioned Concurrency to reduce cold start latency.
Monitoring Lambda Functions
Tool | What It Shows |
---|---|
CloudWatch Logs | stdout + error logs |
CloudWatch Metrics | Invocations, Duration, Errors, Throttles |
X-Ray | Trace execution path |
Lambda Insights | Memory usage, CPU, execution details |
β Always enable logs and metrics for production functions.
π Security & Permissions
- Lambda assumes an IAM Role to access resources (e.g., S3, DynamoDB)
- Follow least privilege when creating the role
- Use environment variables + KMS for secrets
- Set VPC access only if required (adds latency)
β Real-World Use Cases
Industry | Use Case |
---|---|
E-commerce | Order processing (event-driven) |
Media/Publishing | Image/video conversion |
SaaS Platforms | API backend without managing servers |
IoT | Sensor event processing |
Analytics | Real-time ETL pipelines with Kinesis + Lambda |
DevOps | Auto-stop EC2s, monitor events, automate cleanups |
Best Practices
Practice | Why It Matters |
---|---|
Use short timeouts | Prevent hanging functions |
Keep package size small | Reduces cold start |
Use layers for dependencies | Code reuse and manageability |
Monitor throttling & retries | To avoid data loss |
Avoid infinite loops | Costs can spike fast |
Use async handlers | Better performance with APIs |
Implement dead-letter queues (DLQ) | To catch failed invocations |
Summary
Feature | Description |
---|---|
Serverless | No servers to manage |
Pay-per-execution | Billed by usage (ms) |
Event-driven | Triggered by S3, API Gateway, Cron, etc. |
Multi-language | Python, Node.js, Java, Go, .NET |
Fast scaling | 1000s of requests per second |
Observability | CloudWatch, X-Ray, Lambda Insights |
Security | IAM roles, VPC control, encrypted env vars |
π‘ Explore More AWS Tools & Resources
Educational AI Tutor
Get instant AWS-related answers and explanations using AI.
Interview Question Generator
Generate AWS interview questions for practice and preparation.
AWS Practice Quiz
Test your AWS knowledge with timed quizzes and scoring.
AWS Interview Questions
Browse frequently asked AWS interview questions with answers.