Serverless Architecture: Pros, Cons, and When to Use It
Discover when serverless architecture is the right choice for your application, with practical examples and cost analysis.
Jean-Pierre Broeders
Freelance DevOps Engineer
Serverless Architecture: Pros, Cons, and When to Use It
Serverless has become one of the hottest buzzwords in cloud computing. But what does it actually mean, and when should you use it? In this post, I'll dive into the reality of serverless architecture with concrete examples and practical advice.
What Is Serverless Really?
Despite the name, serverless still runs on servers - you just don't have to manage them. Instead of keeping a VM or container running 24/7, you only pay for the actual compute time you use.
Key characteristics:
- Event-driven: Code is triggered by events (HTTP requests, database changes, file uploads)
- Auto-scaling: Automatically scales from 0 to thousands of instances
- Pay-per-use: Only pay for actual executions
- Managed infrastructure: Cloud provider handles servers, patching, scaling
Popular Serverless Platforms
AWS Lambda
The pioneer and market leader. Supports Python, Node.js, Go, Java, .NET, Ruby.
// AWS Lambda function (Node.js)
export const handler = async (event) => {
const body = JSON.parse(event.body);
// Business logic here
const result = await processData(body);
return {
statusCode: 200,
body: JSON.stringify({ success: true, data: result })
};
};
Azure Functions
Microsoft's serverless platform with seamless .NET integration.
// Azure Function (C#)
[FunctionName("ProcessOrder")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
ILogger log)
{
var body = await new StreamReader(req.Body).ReadToEndAsync();
var order = JsonConvert.DeserializeObject<Order>(body);
await ProcessOrderAsync(order);
return new OkObjectResult(new { success = true });
}
Google Cloud Functions
Google's offering, strong in data processing and ML workflows.
When Is Serverless The Right Choice?
✅ Perfect Use Cases
1. Event-driven workflows
- Webhook endpoints
- File processing (upload → resize image → save)
- Background jobs triggered by queue messages
2. Variable workloads
- Traffic spikes (e.g., ticket sale events)
- Periodic batch jobs (nightly data processing)
- Unpredictable usage patterns
3. Rapid prototyping
- MVPs and proof of concepts
- Experiments without infrastructure overhead
- Quick integrations between services
4. Mobile app backends
- REST API endpoints
- Push notification handlers
- Authentication flows
❌ When NOT to Use Serverless
1. Long-running processes
- Lambda has a max execution time of 15 minutes
- Video encoding, ML training → use containers
2. Constant high throughput
- If you have 24/7 traffic, serverless becomes more expensive than dedicated infrastructure
- Break-even point is often around 30-40% constant CPU utilization
3. Low latency requirements
- Cold starts can take 1-3 seconds
- Critical real-time apps → use always-on instances
4. Complex state management
- Serverless functions are stateless
- Stateful apps need external storage (databases, Redis)
Real-World Example: Image Processing Pipeline
A practical example where serverless excels:
# Architecture
User uploads image → S3 bucket → triggers Lambda →
→ Resize image (3 sizes) →
→ Generate thumbnails →
→ Extract metadata →
→ Save to database →
→ Send notification
# AWS SAM template
Resources:
ImageBucket:
Type: AWS::S3::Bucket
Properties:
NotificationConfiguration:
LambdaConfigurations:
- Event: s3:ObjectCreated:*
Function: !GetAtt ProcessImageFunction.Arn
ProcessImageFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: nodejs18.x
Handler: index.handler
Timeout: 60
MemorySize: 1024
Environment:
Variables:
THUMBNAIL_SIZES: "150,300,600"
Benefits here:
- Scales automatically with upload volume
- No idle costs when there are no uploads
- No server management
Cost: The Truth
Serverless marketing says "super cheap", but that's not always true.
AWS Lambda pricing (example):
- $0.20 per 1 million requests
- $0.0000166667 per GB-second compute
Scenario 1: Low traffic API (startup)
- 100,000 requests/month
- Avg 200ms duration, 512MB memory
- Cost: ~$1/month → ✅ Very cheap
Scenario 2: High traffic app (scale-up)
- 50 million requests/month
- Avg 500ms duration, 1GB memory
- Cost: ~$400/month → ⚠️ Dedicated server might be cheaper
Best Practices
1. Minimize cold starts
// Keep dependencies minimal
// Reuse connections outside handler
const db = require('./db'); // Initialized once
exports.handler = async (event) => {
// Handler stays lean
return db.query(event.query);
};
2. Use environment variables
# Don't hardcode configs
DATABASE_URL=postgres://...
API_KEY=secret123
STAGE=production
3. Implement proper error handling
exports.handler = async (event) => {
try {
return await processEvent(event);
} catch (error) {
console.error('Error:', error);
// Send to error tracking (Sentry, etc.)
throw error; // Let Lambda retry
}
};
4. Monitor and optimize
- Watch CloudWatch metrics (duration, errors, throttles)
- Optimize memory allocation (more memory = faster CPU)
- Use distributed tracing (X-Ray)
Conclusion
Serverless is not a silver bullet, but a powerful tool in your architecture toolkit. It shines for event-driven workloads with variable traffic, but isn't always the cheapest or fastest option for constant high-traffic scenarios.
My advice:
- Start serverless for new projects (fast iteration)
- Monitor costs and performance from day 1
- Migrate to dedicated infrastructure when economically sensible
- Use hybrid: serverless for peaks, containers for baseline
This approach gives you flexibility, cost efficiency, and the ability to scale your architecture as your needs evolve.
