Lambda — Serverless Functions
Write code, forget servers — event-driven functions that scale to zero and cost nothing when idle
Skills taught: aws.lambda, aws.lambda-triggers, aws.lambda-layers, aws.cold-start, aws.lambda-pricing, aws.serverless
What makes Lambda different
With EC2, you pay for a server even when it's doing nothing. With Lambda, you pay only when your code runs — and only for the duration it runs (billed in 1ms increments). Lambda scales from 0 to 10,000 concurrent executions automatically, with no configuration. There's no OS to patch, no server to maintain, no auto-scaling groups to configure. You upload code; AWS handles everything else.
Writing your first Lambda function
// Lambda receives an event and returns a response
// The event shape depends on the trigger (API Gateway, S3, SQS, etc.)
// Example: HTTP API trigger via API Gateway
import { APIGatewayProxyHandlerV2 } from 'aws-lambda';
export const handler: APIGatewayProxyHandlerV2 = async (event) => {
console.log('Event:', JSON.stringify(event, null, 2));
const name = event.queryStringParameters?.name ?? 'World';
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: `Hello, ${name}!` }),
};
};
// Example: S3 trigger — runs when a file is uploaded
import { S3Handler } from 'aws-lambda';
export const processUpload: S3Handler = async (event) => {
for (const record of event.Records) {
const bucket = record.s3.bucket.name;
const key = record.s3.object.key;
console.log(`Processing: s3://${bucket}/${key}`);
// resize image, extract metadata, trigger workflow...
}
};
// Example: Scheduled trigger (like cron) — runs on a schedule
import { ScheduledHandler } from 'aws-lambda';
export const dailyReport: ScheduledHandler = async (event) => {
// Runs daily at 8am UTC
console.log('Generating daily report...');
};
Deploying Lambda functions
# Method 1: Direct zip upload
npm run build # compile TypeScript to JS
zip -r function.zip dist/ node_modules/
aws lambda create-function \
--function-name my-api \
--runtime nodejs20.x \
--handler dist/handler.handler \
--zip-file fileb://function.zip \
--role arn:aws:iam::123456789:role/lambda-execution-role
# Update after code changes:
aws lambda update-function-code \
--function-name my-api \
--zip-file fileb://function.zip
# Method 2: Container image (for complex dependencies)
# Build and push to ECR, then point Lambda at the image:
aws lambda update-function-code \
--function-name my-api \
--image-uri 123456789.dkr.ecr.ap-south-1.amazonaws.com/my-app:latest
# Invoke manually for testing
aws lambda invoke \
--function-name my-api \
--payload '{"queryStringParameters":{"name":"Alice"}}' \
response.json
cat response.json
# View logs (Lambda logs go to CloudWatch)
aws logs tail /aws/lambda/my-api --follow
Common Lambda triggers
TRIGGER WHEN INVOKED COMMON USE
─────────────────────────────────────────────────────────────────
API Gateway HTTP HTTP request to your endpoint REST/GraphQL APIs
API Gateway WebSocket WebSocket connect/message Real-time features
S3 File uploaded/deleted/modified Image processing, ETL
SQS Message added to queue Async job processing
SNS Notification published Fan-out, alerts
EventBridge Scheduled or custom event Cron jobs, workflows
DynamoDB Streams Table item changed Real-time sync, CDC
Cognito User auth event Post-confirmation flows
CloudFront Edge location request Edge compute
ALB Load balancer request API endpoints
Cold starts and performance
COLD START: The first invocation after a period of inactivity
What happens:
1. AWS allocates a compute environment (container)
2. Loads your function code and dependencies
3. Runs the initialization code (outside handler)
4. THEN runs your handler
Cold start duration (2026 benchmarks):
- Node.js 20 with simple handler: 50-200ms
- Node.js with heavy dependencies (AWS SDK, ORM): 500ms-2s
- Java / .NET: 2-10s (JVM warmup)
- Container-based Lambda: 1-5s
Mitigation strategies:
1. Provisioned concurrency: pre-warm N instances
→ Always warm, no cold starts, higher cost
2. Minimize package size (tree-shake, remove unused deps)
3. Move expensive init (DB connections) OUTSIDE the handler:
// Init outside handler = runs once per container, not per invocation
const db = new DatabasePool({ ... }); // ← OUTSIDE
export const handler = async (event) => {
// db is already connected on warm invocations
const users = await db.query('SELECT * FROM users');
};
Pricing — when Lambda saves money
PRICING (2026):
Requests: $0.20 per 1M invocations (first 1M/month FREE)
Duration: $0.0000166667 per GB-second
(128MB function running 100ms = 0.0128 GB-sec = $0.000000213)
EXAMPLE: API with 10M requests/month, avg 200ms, 256MB memory
Requests: 10M × $0.20/M = $2.00
Duration: 10M × 0.2s × 0.256GB × $0.0000166667 = $8.53
Total: ~$10.53/month
COMPARISON: EC2 t4g.small running 24/7 = $12/month
→ Lambda is cheaper for sporadic traffic
→ EC2 is cheaper for constant high-throughput traffic
Lambda wins at:
< 1M requests/month (nearly free)
Spiky/unpredictable traffic (auto-scales, no idle cost)
Event-driven workloads (S3, queues, schedules)
EC2 wins at:
Constant high-throughput APIs (1000+ req/sec steady state)
Long-running processes (> 15 minutes — Lambda max timeout)
Stateful workloads (WebSocket servers, etc.)
Frequently Asked Questions
Can Lambda replace all my backend servers?
For many use cases, yes. Lambda is excellent for REST APIs, async processing, scheduled jobs, and event handlers. But Lambda has hard limits: 15-minute max execution time, 10GB max memory, ephemeral filesystem. It's also not ideal for WebSocket servers (connection state), very high throughput (cold starts, pricing), or workloads needing persistent local filesystem access. Lambda + API Gateway covers 80% of web API use cases.