Serverless Guide

Serverless vs Containers

AspectServerless (Lambda)Containers (ECS/K8s)
ScalingInstant, per-request, to 1000sPod-based, minutes to scale
CostPay per invocation + durationPay for reserved capacity
Cold starts50ms–2s on first requestNone (always warm)
Max duration15 minutes (Lambda)Unlimited
StateStateless (use external store)Can be stateful
Best forSpiky traffic, async processing, APIsLong-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

TechniqueImpactNotes
Provisioned ConcurrencyEliminates cold startsCosts more; keep instances warm
Use ARM64 (Graviton)~20% faster cold startsAlso ~20% cheaper compute
Reduce package sizeSmaller = faster initUse tree shaking, avoid unused deps
Runtime: compiled (Go/Rust)Much faster cold start vs Node/PythonGo cold start ~50ms vs Node ~300ms
Move init code outside handlerReuse across warm invocationsDB connections, SDK clients
Lambda SnapStart (Java)Eliminates JVM init timeJava 11+ only