08-04 Serverless Computing Required

Serverless computing represents the next evolution in cloud abstraction, where developers focus purely on code while the cloud provider manages all infrastructure, including servers, containers, and scaling.

What is Serverless Computing?

Definition

Serverless computing is a cloud execution model where:

  • You don’t manage servers or containers
  • Code runs in response to events
  • You pay only for actual execution time
  • Infrastructure scales automatically

[!NOTE] “Serverless” doesn’t mean no servers

Servers still exist, but they’re completely abstracted away. You never see, configure, or manage them.

Key Characteristics

  • No server management: No OS patches, no capacity planning
  • Event-driven: Code executes in response to triggers
  • Automatic scaling: From zero to thousands of concurrent executions
  • Pay-per-use: Billed by execution time (milliseconds) and memory
  • Stateless: Each function execution is independent

Serverless vs Containers vs VMs

┌──────────────────────────────────────────────────┐
│  Traditional VMs                                 │
│  You manage: OS, runtime, scaling, patching     │
│  Granularity: Hours                              │
└──────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────┐
│  Containers (Docker, Kubernetes)                 │
│  You manage: Container images, orchestration     │
│  Granularity: Seconds to minutes                 │
└──────────────────────────────────────────────────┘

┌──────────────────────────────────────────────────┐
│  Serverless (AWS Lambda, Azure Functions)        │
│  You manage: Just your code                      │
│  Granularity: Milliseconds                       │
└──────────────────────────────────────────────────┘
Aspect VMs Containers Serverless
Management Full control Container orchestration None
Scaling Manual/Auto-scaling groups Kubernetes/Swarm Automatic
Billing Per hour/month Per hour Per 100ms
Startup Minutes Seconds Milliseconds
Idle Cost Always paying Paying for running containers Zero

Examples of Serverless Platforms

AWS Fargate

  • Serverless container platform
  • Run containers without managing servers
  • Works with Amazon ECS and EKS
  • You define container specs, AWS handles infrastructure

AWS Lambda

  • Function-as-a-Service (FaaS)
  • Run code without provisioning servers
  • Event-driven execution
  • Supports multiple languages

Other Platforms

  • Azure Functions: Microsoft’s FaaS offering
  • Google Cloud Functions: Google’s FaaS
  • Cloudflare Workers: Edge computing platform
  • Vercel/Netlify Functions: Frontend-focused serverless

AWS Lambda Deep Dive

What is AWS Lambda?

AWS Lambda removes container details and allows you to write functions:

  • Upload code as a function
  • Configure triggers (events)
  • AWS handles everything else

Supported Programming Environments

  • Node.js (JavaScript/TypeScript)
  • Python
  • Java
  • C# (.NET)
  • Go
  • Ruby
  • Custom runtimes (via Lambda Layers)

Event Sources

Functions can be triggered by various events:

HTTP Requests

API Gateway → Lambda Function
User makes HTTP request → Function executes → Returns response

AWS Services

  • S3: File upload/delete
  • DynamoDB: Database changes
  • SNS/SQS: Message queues
  • CloudWatch: Scheduled events (cron)
  • Kinesis: Stream processing

IoT and Mobile

  • IoT Core: Device messages
  • Cognito: User authentication events
  • Mobile: App backend logic

Lambda Function Structure

Python example:

def lambda_handler(event, context):
    """
    event: Contains data about the triggering event
    context: Provides runtime information
    """
    # Your code here
    name = event.get('name', 'World')
    
    return {
        'statusCode': 200,
        'body': f'Hello, {name}!'
    }

Node.js example:

exports.handler = async (event) => {
    const name = event.name || 'World';
    
    return {
        statusCode: 200,
        body: JSON.stringify({
            message: `Hello, ${name}!`
        })
    };
};

Creating a Lambda Function

1. Choose Language

Select from supported runtimes (Python 3.11, Node.js 18, etc.)

2. Define Role

IAM role with permissions for:

  • CloudWatch Logs (logging)
  • Other AWS services your function needs

3. Select Template (Optional)

  • Blank function
  • API Gateway proxy
  • S3 object processing
  • DynamoDB stream processing

4. Write/Upload Code

Option A: Inline editor

# Edit directly in AWS Console
def lambda_handler(event, context):
    return {'statusCode': 200, 'body': 'Hello!'}

Option B: Upload ZIP

# Package function with dependencies
pip install requests -t .
zip -r function.zip .
# Upload via console or CLI

Option C: Container image

FROM public.ecr.aws/lambda/python:3.11
COPY app.py ${LAMBDA_TASK_ROOT}
CMD ["app.lambda_handler"]

5. Configure Settings

  • Memory: 128 MB to 10 GB
  • Timeout: Up to 15 minutes
  • Environment variables: Configuration
  • VPC: Optional network access

6. Test

Use test events to invoke function:

{
  "name": "Alice",
  "action": "greet"
}

Local Development with SAM CLI

AWS SAM (Serverless Application Model) enables local testing:

# Install SAM CLI
brew install aws-sam-cli

# Initialize project
sam init

# Test locally
sam local invoke MyFunction -e event.json

# Start local API
sam local start-api

# Deploy to AWS
sam deploy --guided

API Gateway Integration

Purpose

API Gateway provides a simple way to:

  • Associate URLs with Lambda functions
  • Create RESTful APIs
  • Handle HTTP methods (GET, POST, PUT, DELETE)
  • Enable CORS (Cross-Origin Resource Sharing)
  • Manage API keys and throttling

Example Setup

┌─────────────────────────────────────────────┐
│  Client (Browser/Mobile)                    │
└────────────────┬────────────────────────────┘
                 │ HTTPS Request
                 ↓
┌─────────────────────────────────────────────┐
│  API Gateway                                │
│  GET  /users      → Lambda: listUsers       │
│  POST /users      → Lambda: createUser      │
│  GET  /users/{id} → Lambda: getUser         │
└────────────────┬────────────────────────────┘
                 │ Invoke
                 ↓
┌─────────────────────────────────────────────┐
│  Lambda Functions                           │
│  - Parse request                            │
│  - Business logic                           │
│  - Return response                          │
└─────────────────────────────────────────────┘

API Gateway Features

  • Request validation: Check parameters before invoking Lambda
  • Response transformation: Modify responses
  • Caching: Cache responses for performance
  • Throttling: Rate limiting
  • Authentication: API keys, IAM, Cognito, custom authorizers

Typical Serverless Architecture

┌──────────────┐
│   CloudFront │  CDN for static content
│   (CDN)      │
└──────┬───────┘
       │
┌──────▼───────┐
│   S3 Bucket  │  Static website hosting
│   (Frontend) │  (HTML, CSS, JS)
└──────┬───────┘
       │ API calls
┌──────▼───────────┐
│  API Gateway     │  RESTful API
└──────┬───────────┘
       │
┌──────▼───────────┐
│  Lambda Functions│  Business logic
│  - Auth          │
│  - CRUD ops      │
│  - Processing    │
└──────┬───────────┘
       │
┌──────▼───────────┐
│  DynamoDB        │  NoSQL database
│  (Database)      │
└──────────────────┘

Example: Serverless Web Application

Components:

  1. S3 + CloudFront: Host static frontend
  2. API Gateway: Expose REST API
  3. Lambda: Handle business logic
  4. DynamoDB: Store data
  5. Cognito: User authentication
  6. CloudWatch: Logging and monitoring

Lambda Pricing

Cost Model

You pay for:

  1. Number of requests: $0.20 per 1M requests
  2. Duration: $0.0000166667 per GB-second

Example Calculation

Function specs:
- Memory: 512 MB (0.5 GB)
- Execution time: 200ms (0.2 seconds)
- Requests: 1 million per month

Cost calculation:
Requests: 1M × $0.20/1M = $0.20
Duration: 1M × 0.5 GB × 0.2s × $0.0000166667 = $1.67

Total: $1.87/month

Free Tier

AWS Lambda free tier includes:

  • 1M free requests per month
  • 400,000 GB-seconds of compute time per month

Benefits of Serverless

No infrastructure management

  • No servers to provision or maintain
  • No OS patches or updates

Automatic scaling

  • Scales from 0 to thousands instantly
  • Handles traffic spikes automatically

Cost-effective

  • Pay only for actual usage
  • No idle capacity costs

Faster time to market

  • Focus on code, not infrastructure
  • Rapid deployment

Built-in high availability

  • Multi-AZ deployment by default
  • Automatic failover

Challenges and Considerations

Cold Starts

  • Problem: First invocation after idle period is slow
  • Impact: 100ms - 1s latency
  • Solutions:
    • Keep functions warm with scheduled pings
    • Use provisioned concurrency
    • Optimize package size

Execution Limits

  • Timeout: Maximum 15 minutes
  • Memory: Maximum 10 GB
  • Deployment package: 50 MB (zipped), 250 MB (unzipped)
  • Concurrent executions: 1000 (default, can be increased)

Vendor Lock-in

  • Code often tied to specific cloud provider
  • Migration can be complex
  • Consider using frameworks like Serverless Framework or SAM

Debugging and Monitoring

  • Harder to debug than traditional apps
  • Rely on logging (CloudWatch Logs)
  • Use distributed tracing (X-Ray)
  • Monitor cold starts and errors

Microservices and Serverless

Serverless fits perfectly with microservices architecture:

┌─────────────────────────────────────────┐
│  Monolithic Application                 │
│  - One large codebase                   │
│  - Deployed as single unit              │
│  - Scales entire application            │
└─────────────────────────────────────────┘

                  ↓ Decompose

┌──────────┐  ┌──────────┐  ┌──────────┐
│ User     │  │ Product  │  │ Order    │
│ Service  │  │ Service  │  │ Service  │
│ (Lambda) │  │ (Lambda) │  │ (Lambda) │
└──────────┘  └──────────┘  └──────────┘
     ↓             ↓             ↓
┌──────────┐  ┌──────────┐  ┌──────────┐
│ User DB  │  │Product DB│  │ Order DB │
└──────────┘  └──────────┘  └──────────┘

Benefits:

  • Independent deployment
  • Technology diversity
  • Fault isolation
  • Easier scaling

Best Practices

1. Keep Functions Small and Focused

# ❌ BAD: One function does everything
def lambda_handler(event, context):
    if event['action'] == 'create_user':
        # 100 lines of code
    elif event['action'] == 'delete_user':
        # 100 lines of code
    # ...

# ✅ GOOD: Separate functions
def create_user(event, context):
    # Focused logic

def delete_user(event, context):
    # Focused logic

2. Minimize Package Size

  • Use layers for shared dependencies
  • Remove unnecessary files
  • Use lightweight libraries

3. Use Environment Variables

import os

DB_HOST = os.environ['DB_HOST']
API_KEY = os.environ['API_KEY']

4. Implement Proper Error Handling

def lambda_handler(event, context):
    try:
        # Your code
        return {'statusCode': 200, 'body': 'Success'}
    except Exception as e:
        print(f"Error: {e}")
        return {'statusCode': 500, 'body': 'Error'}

5. Use Dead Letter Queues

  • Handle failed executions
  • Retry logic
  • Alert on failures

Summary

Serverless computing represents the highest level of cloud abstraction:

  • No infrastructure management: Focus purely on code
  • Event-driven: Functions respond to triggers
  • Auto-scaling: Handle any load automatically
  • Cost-effective: Pay only for execution time
  • AWS Lambda: Leading FaaS platform
  • Perfect for microservices: Independent, scalable functions

Serverless is ideal for:

  • APIs and web backends
  • Data processing pipelines
  • Scheduled tasks
  • Event-driven workflows
  • IoT backends

Further Reading

← Back to Chapter Home