AWS Certified Cloud Practitioner

Post 19 of 25

76%

Complete

Cloud Architecture6 min read

AWS Cloud Practitioner #19: AWS Lambda - Serverless Compute

Domina Lambda: serverless compute, event-driven execution, pricing pay-per-invocation y casos de uso.

🎯 Lo que Aprenderás Hoy

  • Explicar qué es serverless y Lambda
  • Comprender event-driven execution
  • Calcular pricing de Lambda
  • Identificar triggers y casos de uso
  • Comparar Lambda vs. EC2

¿Qué es AWS Lambda?

Lambda permite ejecutar código sin gestionar servers.

plaintext
Traditional (EC2):
1. Provision server → 2. Deploy código → 3. Mantener server
 
Serverless (Lambda):
1. Upload código → 2. Se ejecuta cuando triggered
 
No gestionas:
❌ Servers
❌ OS patches
❌ Scaling
❌ High availability
❌ Capacity planning
 
AWS gestiona:
✅ Infrastructure
✅ Scaling (0 to 10,000 concurrent executions)
✅ Availability
✅ Maintenance

Event-Driven Execution

Lambda se ejecuta en respuesta a events:

plaintext
Trigger sources:
- S3: File uploaded
- API Gateway: HTTP request
- DynamoDB: Record inserted
- SNS/SQS: Message received
- CloudWatch Events: Schedule (cron)
- Cognito: User signup
- Kinesis: Data stream
 
Example flow:
User uploads image.jpg a S3
→ S3 trigger Lambda function
→ Lambda resize image
→ Lambda save thumbnail a S3

Lambda Function Anatomy

python
# Handler function
def lambda_handler(event, context):
    # event: Contains trigger data
    # context: Runtime info
 
    print(f"Event: {event}")
 
    # Business logic
    result = process_data(event)
 
    # Return response
    return {
        'statusCode': 200,
        'body': json.dumps(result)
    }
 
# Supported runtimes:
# - Python, Node.js, Java, Go, Ruby, .NET
# - Custom runtime (Docker container)

Configuration

plaintext
Function settings:
- Memory: 128 MB - 10,240 MB (10 GB)
- Timeout: 1 sec - 15 min
- Environment variables
- IAM execution role (permissions)
- VPC (optional, for DB access)
 
Memory → CPU allocated:
128 MB = 0.08 vCPU
1024 MB = 0.6 vCPU
1792 MB = 1 vCPU
10240 MB = 6 vCPU
 
More memory = More CPU = Faster execution

Pricing

plaintext
Pay for:
1. Number of requests
2. Duration (GB-seconds)
 
Requests:
$0.20 per 1M requests
 
Duration:
$0.0000166667 per GB-second
 
GB-second:
Memory × Execution time
Example: 512 MB × 1 second = 0.5 GB-seconds
 
Free Tier (always free):
1M requests/month
400,000 GB-seconds/month

Example Calculation

plaintext
Scenario:
- 5M invocations/month
- 256 MB memory
- 200ms average duration
 
Requests:
5M × $0.20/1M = $1.00
 
Compute:
5M × 0.2s × 0.256GB = 256,000 GB-seconds
(256,000 - 400,000 free) = 0 (within free tier)
Cost: $0.00
 
Total: $1.00/month
 
vs. EC2 t3.micro 24/7: $8.35/month
Savings: 88%

Triggers (Event Sources)

1. S3 Trigger

plaintext
Use case: Image processing
 
Setup:
S3 bucket → Event notification → Lambda
 
Lambda function:
def lambda_handler(event, context):
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']
 
    # Download image
    s3.download_file(bucket, key, '/tmp/image.jpg')
 
    # Resize
    resize_image('/tmp/image.jpg', '/tmp/thumbnail.jpg')
 
    # Upload
    s3.upload_file('/tmp/thumbnail.jpg', bucket, f'thumbnails/{key}')
 
Benefit: Automatic processing, pay only per image

2. API Gateway

plaintext
Use case: Serverless REST API
 
Request:
GET /users/123
 
API Gateway → Lambda:
def lambda_handler(event, context):
    user_id = event['pathParameters']['id']
    user = dynamodb.get_item(Key={'UserID': user_id})
 
    return {
        'statusCode': 200,
        'body': json.dumps(user)
    }
 
Response:
{
  "UserID": "123",
  "Name": "Juan"
}
 
Benefit: No servers, auto-scales, pay per request

3. Scheduled Events

plaintext
Use case: Daily backup
 
CloudWatch Event rule:
Schedule: cron(0 2 * * ? *)  # 2 AM daily
 
Lambda:
def lambda_handler(event, context):
    # Create RDS snapshot
    rds.create_db_snapshot(
        DBInstanceIdentifier='prod-db',
        DBSnapshotIdentifier=f'snapshot-{today}'
    )
 
    # Delete old snapshots (>30 days)
    delete_old_snapshots()
 
Benefit: Automated maintenance, no cron server

4. DynamoDB Streams

plaintext
Use case: Audit trail
 
DynamoDB table updated → Stream → Lambda
 
Lambda:
def lambda_handler(event, context):
    for record in event['Records']:
        if record['eventName'] == 'INSERT':
            new_item = record['dynamodb']['NewImage']
            log_to_s3(new_item)
 
Benefit: Real-time processing, decoupled

Lambda Layers

¿Qué son? Shared code/dependencies across functions.

plaintext
Problem:
10 Lambda functions usan same library (pandas)
Each function packages pandas separately
Total size: 10 × 50 MB = 500 MB
 
Solution: Lambda Layer
Create layer con pandas → Attach a 10 functions
Total size: 1 × 50 MB = 50 MB
 
Benefits:
✅ Reduce deployment package size
✅ Share code across functions
✅ Update dependency once

Lambda vs. EC2

AspectoLambdaEC2
ManagementServerlessManual
ScalingAutomaticManual/Auto Scaling
PricingPer invocationPer hour
Idle cost$0Full cost
Max duration15 minUnlimited
Use caseEvent-driven, short tasksLong-running, stateful
plaintext
Use Lambda when:
✅ Event-driven (S3 upload, API request)
✅ Short execution (<15 min)
✅ Variable load (spiky traffic)
✅ Want zero admin
 
Use EC2 when:
✅ Long-running processes
✅ Need specific OS/software
✅ Stateful applications
✅ Consistent load (cheaper with Reserved)
 
Example:
Image processing: Lambda ✅ (triggered, short)
Web server: EC2 ✅ (always on, stateful)
Daily report: Lambda ✅ (scheduled, 5 min)
Game server: EC2 ✅ (stateful, always on)

Best Practices

plaintext
1. Keep functions small:
   ✅ Single responsibility
   ✅ Fast cold starts
   ❌ Monolithic functions
 
2. Optimize memory:
   Test different memory settings
   More memory = More CPU = Faster + potentially cheaper
 
3. Use environment variables:
   DB_HOST, API_KEY en env vars
   NO hardcode
 
4. IAM least privilege:
   Function role: Only permissions needed
   Example: S3 read-only, DynamoDB write-only
 
5. Monitor con CloudWatch:
   Logs, errors, duration, throttles
 
6. Handle cold starts:
   First invocation slower (~1s)
   Keep functions warm (CloudWatch Events every 5 min) si critical
 
7. Use VPC solo si necessary:
   VPC = slower cold starts
   Only para private resource access (RDS en private subnet)
 
8. Async when possible:
   Long operations: Invoke async, send result to SQS
 
9. Error handling:
   Dead Letter Queue (DLQ) para failed invocations
 
10. Versioning:
    Lambda versions + aliases
    $LATEST, v1, v2
    Alias PROD → v2, Alias DEV → $LATEST

Limitations

plaintext
Compute:
- Max memory: 10 GB
- Max execution time: 15 min
- Max deployment package: 50 MB (zipped)
- Max /tmp storage: 10 GB
 
Concurrency:
- Default: 1,000 concurrent executions per region
- Can request increase
 
Networking:
- VPC ENI limits (cold start impact)

📝 Preparación para el Examen

Puntos Clave

Lambda:

  • 📌 Serverless: No server management
  • 📌 Event-driven: Triggered by events
  • 📌 Pricing: Per request + GB-seconds
  • 📌 Max duration: 15 minutes

Free Tier:

  • 📌 1M requests/month (always free)
  • 📌 400,000 GB-seconds/month

Triggers:

  • 📌 S3, API Gateway, DynamoDB, SNS/SQS
  • 📌 CloudWatch Events (schedules)

vs. EC2:

  • 📌 Lambda: Short, event-driven, variable
  • 📌 EC2: Long, stateful, consistent

Preguntas de Práctica

Pregunta 1:

¿Cuál es la duración máxima de una Lambda function?

A) 5 minutes B) 15 minutes C) 1 hour D) Unlimited

Success

Respuesta: B) 15 minutes

Lambda functions tienen timeout máximo de 15 minutos. Para procesos más largos, usa EC2, ECS, o Batch.

Pregunta 2:

¿Qué incluye Free Tier de Lambda?

A) 100K requests/month B) 1M requests/month C) 10M requests/month D) Unlimited

Success

Respuesta: B) 1M requests/month

Lambda Free Tier (always free): 1M requests/month + 400,000 GB-seconds compute.


🎓 Resumen

  1. Lambda: Serverless compute, event-driven
  2. Pricing: Per invocation + duration (GB-seconds)
  3. Triggers: S3, API Gateway, schedules, streams
  4. Free Tier: 1M requests + 400K GB-seconds/month
  5. Use case: Short tasks, variable load, event-driven

⏭️ Próximo Post

Post #20: SNS, SQS y Messaging Services


Tags: #AWS #CloudPractitioner #Lambda #Serverless #EventDriven #Functions #Certification

Written by Jhonny Lorenzo

Researcher at TrautsLab

Related Articles

Recent Articles

Comments