Serverless Guide
Serverless vs Containers
| Aspect | Serverless (Lambda) | Containers (ECS/K8s) |
|---|---|---|
| Scaling | Instant, per-request, to 1000s | Pod-based, minutes to scale |
| Cost | Pay per invocation + duration | Pay for reserved capacity |
| Cold starts | 50ms–2s on first request | None (always warm) |
| Max duration | 15 minutes (Lambda) | Unlimited |
| State | Stateless (use external store) | Can be stateful |
| Best for | Spiky traffic, async processing, APIs | Long-running, consistent load |
Lambda Function Patterns
// AWS Lambda handler (Node.js)
export const handler = async (event, context) => {
// event.source tells you the trigger type
// API Gateway, SQS, SNS, S3, DynamoDB Streams, EventBridge...
// For API Gateway
if (event.httpMethod) {
const body = JSON.parse(event.body || '{}');
return {
statusCode: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: 'OK', data: body })
};
}
// For SQS batch processing
if (event.Records) {
const failures = [];
for (const record of event.Records) {
try {
const msg = JSON.parse(record.body);
await processMessage(msg);
} catch (err) {
failures.push({ itemIdentifier: record.messageId });
}
}
// Return failures for partial batch response
return { batchItemFailures: failures };
}
};
# SAM template for Lambda + API Gateway
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs20.x
MemorySize: 256
Timeout: 30
Environment:
Variables:
TABLE_NAME: !Ref MyTable
Events:
Api:
Type: Api
Properties:
Path: /users
Method: post
Cold Start Reduction
| Technique | Impact | Notes |
|---|---|---|
| Provisioned Concurrency | Eliminates cold starts | Costs more; keep instances warm |
| Use ARM64 (Graviton) | ~20% faster cold starts | Also ~20% cheaper compute |
| Reduce package size | Smaller = faster init | Use tree shaking, avoid unused deps |
| Runtime: compiled (Go/Rust) | Much faster cold start vs Node/Python | Go cold start ~50ms vs Node ~300ms |
| Move init code outside handler | Reuse across warm invocations | DB connections, SDK clients |
| Lambda SnapStart (Java) | Eliminates JVM init time | Java 11+ only |