Summary
Complete guide to serverless architecture for interviews. Covers FaaS, BaaS, event-driven patterns, and cloud-native design. Essential for designing cost-effective, auto-scaling applications.
Core Concepts
What is Serverless?
- Definition: Cloud computing model where cloud provider manages infrastructure
- Key Point: You don't manage servers, just write and deploy code
- Billing: Pay only for actual usage (compute time, requests)
FaaS vs BaaS
- FaaS (Function as a Service): Run code without managing servers (Lambda, Cloud Functions)
- BaaS (Backend as a Service): Use pre-built backend services (Auth0, Firebase)
Key Components
1. Functions
// AWS Lambda Example
exports.handler = async (event) => {
return {
statusCode: 200,
body: JSON.stringify({ message: 'Hello!' })
};
};
2. API Gateway
- Routes HTTP requests to functions
- Handles authentication, rate limiting, CORS
- Examples: AWS API Gateway, Azure API Management
3. Event Sources
- HTTP: API Gateway triggers
- Queue: SQS, SNS messages
- Storage: S3 uploads, DynamoDB streams
- Schedule: CloudWatch Events, cron jobs
- Stream: Kinesis, Kafka
4. Storage Services
- NoSQL: DynamoDB, Cosmos DB
- Object Storage: S3, Azure Blob
- Cache: ElastiCache, Redis
Architecture Patterns
1. Event-Driven Pattern
User → API Gateway → Lambda → DynamoDB
↓
SNS → Lambda → S3
2. Microservices Pattern
/users → Lambda A → DynamoDB
/orders → Lambda B → RDS
/payments → Lambda C → External API
3. CQRS Pattern
Write: API → Lambda → DynamoDB
Read: API → Lambda → ElasticSearch
4. Fan-Out Pattern
// Trigger multiple functions
await Promise.all([
sns.publish({ TopicArn: 'email-topic', Message: data }),
sns.publish({ TopicArn: 'sms-topic', Message: data }),
sns.publish({ TopicArn: 'analytics-topic', Message: data })
]);
🔧 Best Practices
1. Function Design
- Single Responsibility: One function = one task
- Stateless: No local state between invocations
- Idempotent: Same input → same output
- Small Size: Keep deployment packages minimal
2. Performance Optimization
// Connection pooling outside handler
const db = new DynamoDB.DocumentClient();
exports.handler = async (event) => {
// Reuse connection
return await db.get(params).promise();
};
3. Error Handling
exports.handler = async (event) => {
try {
const result = await processData(event);
return { statusCode: 200, body: JSON.stringify(result) };
} catch (error) {
console.error(error);
return { statusCode: 500, body: 'Internal Error' };
}
};
4. Security
- IAM Roles: Least privilege principle
- Environment Variables: Store secrets encrypted
- API Keys: Use API Gateway for rate limiting
- VPC: Isolate functions when needed
Scaling & Limits
Auto-Scaling
- Concurrent Executions: 1000 default (AWS)
- Burst Limits: 3000 initial burst
- Reserved Concurrency: Guarantee capacity
Common Limits (AWS Lambda)
- Execution time: 15 minutes max
- Memory: 128 MB - 10 GB
- Payload size: 6 MB (sync), 256 KB (async)
- Deployment package: 50 MB (zipped)
💰 Cost Optimization
1. Pricing Model
Cost = (Requests × Price per request) + (GB-seconds × Price per GB-second)
2. Optimization Strategies
- Right-size memory: More memory = faster = potentially cheaper
- Minimize cold starts: Keep functions warm
- Use caching: Reduce function invocations
- Batch processing: Process multiple items per invocation
🚨 Common Pitfalls
1. Cold Starts
// Minimize with:
let connection; // Reuse connections
exports.handler = async (event) => {
if (!connection) {
connection = await createConnection();
}
// Use connection
};
2. Vendor Lock-in
- Solution: Use abstraction layers (Serverless Framework)
- Multi-cloud: Design with portability in mind
3. Debugging Challenges
- Solution: Structured logging, distributed tracing
- Tools: AWS X-Ray, Azure Application Insights
Development Tools
Frameworks
- Serverless Framework: Multi-cloud deployment
- SAM (Serverless Application Model): AWS-specific
- Terraform: Infrastructure as Code
Local Development
# serverless.yml example
service: my-service
provider:
name: aws
runtime: nodejs14.x
functions:
hello:
handler: handler.hello
events:
- http:
path: hello
method: get
📝 Common Interview Questions
Design Questions
Q: Design a URL shortener using serverless
A: API Gateway → Lambda → DynamoDB (store mappings) → CloudFront (cache)Q: Design an image processing pipeline
A: S3 upload → Lambda trigger → Process → Store in S3 → Update DynamoDBQ: Design a real-time notification system
A: API Gateway → Lambda → SNS/SQS → Lambda → WebSocket/Push
Technical Questions
Q: How to handle long-running tasks?
A: Use Step Functions, SQS + Lambda, or break into smaller tasksQ: How to manage state?
A: External storage (DynamoDB, S3), Step Functions for workflowsQ: How to ensure reliability?
A: Dead letter queues, retries, circuit breakers, idempotency
Pros vs Cons
Pros
- ✅ No server management
- ✅ Auto-scaling
- ✅ Pay-per-use
- ✅ Quick deployment
- ✅ Focus on business logic
Cons
- ❌ Vendor lock-in
- ❌ Cold starts
- ❌ Limited execution time
- ❌ Debugging complexity
- ❌ Not suitable for all workloads
When to Use Serverless
Good Use Cases
- Event-driven processing
- APIs with variable traffic
- Scheduled tasks/cron jobs
- Webhooks
- Data transformation
- IoT data processing
Poor Use Cases
- Long-running computations
- WebSocket connections (limited)
- High-performance computing
- Applications needing persistent connections
Monitoring & Observability
Key Metrics
- Invocation count: Function usage
- Duration: Execution time
- Errors: Failed invocations
- Throttles: Rate limit hits
- Cold starts: Initialization frequency
Tools
// Structured logging
console.log(JSON.stringify({
requestId: context.requestId,
event: 'user_login',
userId: userId,
timestamp: new Date().toISOString()
}));
🌐 Major Providers Comparison
| Feature | AWS Lambda | Azure Functions | Google Cloud Functions |
|---|---|---|---|
| Languages | Node, Python, Java, Go, .NET | C#, Node, Python, Java | Node, Python, Go, Java |
| Max Timeout | 15 min | 10 min | 9 min |
| Max Memory | 10 GB | 14 GB | 8 GB |
| Triggers | 200+ | 20+ | 10+ |
Advanced Concepts
1. Lambda Layers
functions:
myFunction:
handler: handler.main
layers:
- arn:aws:lambda:region:account:layer:shared-libs:1
2. Step Functions
{
"StartAt": "CheckInventory",
"States": {
"CheckInventory": {
"Type": "Task",
"Resource": "arn:aws:lambda:REGION:ACCOUNT:function:CheckInventory",
"Next": "ProcessOrder"
}
}
}
3. Edge Computing
- Lambda@Edge: Run functions at CloudFront locations
- Cloudflare Workers: Global edge functions
Quick Tips for Interviews
- Always mention trade-offs: No solution is perfect
- Consider scale: Design for growth
- Think about costs: Serverless isn't always cheaper
- Security first: Never forget IAM and encryption
- Know the limits: Execution time, payload size, etc.
📚 Key Takeaways
- Serverless = No server management + Pay-per-use
- Best for: Event-driven, variable workloads, microservices
- Key challenges: Cold starts, vendor lock-in, debugging
- Success factors: Good monitoring, proper error handling, cost awareness
- Design principle: Stateless, event-driven, loosely coupled
Remember: In interviews, demonstrate understanding of both benefits and limitations. Show how you'd architect solutions considering real-world constraints.