AWS Certified Cloud Practitioner
Post 19 of 25
76%
Complete
AWS Cloud Practitioner #19: AWS Lambda - Serverless Compute
Domina Lambda: serverless compute, event-driven execution, pricing pay-per-invocation y casos de uso.
Recommended Prerequisites
For the best learning experience, we recommend reading these posts first:
🎯 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.
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
✅ MaintenanceEvent-Driven Execution
Lambda se ejecuta en respuesta a events:
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 S3Lambda Function Anatomy
# 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
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 executionPricing
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/monthExample Calculation
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
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 image2. API Gateway
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 request3. Scheduled Events
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 server4. DynamoDB Streams
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, decoupledLambda Layers
¿Qué son? Shared code/dependencies across functions.
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 onceLambda vs. EC2
| Aspecto | Lambda | EC2 |
|---|---|---|
| Management | Serverless | Manual |
| Scaling | Automatic | Manual/Auto Scaling |
| Pricing | Per invocation | Per hour |
| Idle cost | $0 | Full cost |
| Max duration | 15 min | Unlimited |
| Use case | Event-driven, short tasks | Long-running, stateful |
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
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 → $LATESTLimitations
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
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
Respuesta: B) 1M requests/month
Lambda Free Tier (always free): 1M requests/month + 400,000 GB-seconds compute.
🎓 Resumen
- Lambda: Serverless compute, event-driven
- Pricing: Per invocation + duration (GB-seconds)
- Triggers: S3, API Gateway, schedules, streams
- Free Tier: 1M requests + 400K GB-seconds/month
- 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
Related Articles
AWS Cloud Practitioner #18: DynamoDB - NoSQL Serverless
Aprende DynamoDB: base de datos NoSQL serverless, key-value/document store, escalamiento automático y casos de uso.
AWS Cloud Practitioner #1: De Servidores Físicos a la Nube
Aprende qué es cloud computing y las diferencias entre IaaS, PaaS y SaaS con una metodología bottom-up que construye tu conocimiento paso a paso.
AWS Cloud Practitioner #2: Infraestructura Global AWS - Regions, AZs y Edge Locations
Descubre cómo AWS distribuye su infraestructura globalmente y aprende a elegir la región correcta para tus aplicaciones usando metodología bottom-up.
AWS Cloud Practitioner #3: Superpoderes de la Nube - Elasticity, Scalability y HA
Comprende las ventajas clave de cloud computing: elasticity, scalability, high availability y agility. Aprende cómo AWS implementa estos conceptos.