Costos y optimización
Pricing, spot, right-sizing y budgets
AWS cobra por uso, no por capacidad. Lambda pagas por ejecución (tiempo + memoria), EC2 pagas por hora, DynamoDB por read/write units, S3 por GB almacenado y requests. Sin disciplina, costos crecen exponencialmente: una función Lambda invocada accidentalmente 1M veces cuesta miles. La optimización empieza antes de desplegar: modelar costos en el diseño, monitorear después.
On-Demand es el precio base: pagas por hora/segundo sin compromiso. Es caro si usas máquinas grandes 24/7. Reserved Instances (RI) comprometerte por 1 o 3 años por descuento de 30-70%. Savings Plans (más flexible que RI) aplican a EC2 y Fargate. Spot Instances (hasta 90% descuento) son máquinas no utilizadas que AWS reclama en cualquier momento: ideales para jobs batch, no para producción sensible.
Right-sizing es ajustar la instancia al uso real. Una t3.large pagando 8 horas/día por 30 GB de RAM pero solo usando 2 GB es derroche. Usa CloudWatch para medir CPU/RAM reales, baja de tamaño, y reinicia. AWS Compute Optimizer sugiere automáticamente. Un T-series (burstable) es mejor que General Purpose si no necesitas poder sostenido.
Para aplicaciones batch y entrenamientos de ML, Spot Instances ahorran 70-90%: precio bajo porque AWS puede terminarlos sin aviso. Configura un interruption-handler Lambda que guarde checkpoints a S3 antes de morir. Para datos críticos, mezcla On-Demand + Spot: 10% On-Demand para baseline, 90% Spot para escala.
AWS Budgets alerta cuando gastos superan un umbral. Crea una alarma a 80% del presupuesto mensual, otra a 100% para frenar. Cost Allocation Tags organizan costos por proyecto, ambiente, equipo. Sin tags, no sabes qué servicio gasta más. Habilita Cost Explorer, examina Top 10 servicios, negotia con proveedores si una línea es sospechosa.
Los errores comunes son: (1) no monitorear costos (un error genera $10K de gasto antes de notarlo), (2) infraestructura de prueba olvidada en producción (instancias 24/7 no usadas), (3) no usar Auto Scaling (pagas por picos aunque sea raro), (4) DynamoDB sin límites (una query rota lee 1B items), (5) replicación multi-región innecesaria (triple costo sin beneficio).
# === AWS Pricing Models & Cost Optimization ===
import boto3
from datetime import datetime, timedelta
ce = boto3.client('ce') # Cost Explorer
budgets = boto3.client('budgets')
cloudwatch = boto3.client('cloudwatch')
# === 1. ESTIMATE COSTS BEFORE DEPLOYMENT ===
# EC2 On-Demand example:
# t3.large: $0.083/hour × 730 hours/month = $60
# t3.xlarge: $0.166/hour × 730 = $121
# Use CloudWatch to decide: measure CPU/RAM before sizing up
def estimate_ec2_cost(instance_type, hours_per_month=730):
prices = {
't3.micro': 0.0104,
't3.small': 0.0208,
't3.medium': 0.0416,
't3.large': 0.0832,
'm5.large': 0.096,
'm5.xlarge': 0.192
}
return prices[instance_type] * hours_per_month
print(f'On-Demand t3.large: ${estimate_ec2_cost("t3.large"):.2f}/month')
print(f'On-Demand m5.xlarge: ${estimate_ec2_cost("m5.xlarge"):.2f}/month')
# Reserved Instance (1-year): ~40% discount
ri_price = estimate_ec2_cost('t3.large') * 0.6 * 12
print(f'Reserved (1yr) t3.large: ${ri_price:.2f}/year')
# Spot Instance (70% discount)
spot_price = estimate_ec2_cost('t3.large') * 0.3
print(f'Spot t3.large: ${spot_price:.2f}/month (interruptible)')
# === 2. CREATE BUDGET WITH ALERTS ===
budgets.create_budget(
AccountId='123456789',
Budget={
'BudgetName': 'ML-Pipeline-Monthly',
'BudgetLimit': {'Amount': '5000', 'Unit': 'USD'},
'TimeUnit': 'MONTHLY',
'BudgetType': 'COST'
},
NotificationsWithSubscribers=[
{
'Notification': {
'NotificationType': 'FORECASTED',
'ComparisonOperator': 'GREATER_THAN',
'Threshold': 80
},
'Subscribers': [
{'SubscriptionType': 'EMAIL', 'Address': 'ops@example.com'}
]
}
]
)
# === 3. TAG RESOURCES FOR COST ALLOCATION ===
ec2 = boto3.client('ec2')
ec2.create_tags(
Resources=['i-0123456789abcdef0'],
Tags=[
{'Key': 'Project', 'Value': 'MLPipeline'},
{'Key': 'Environment', 'Value': 'prod'},
{'Key': 'CostCenter', 'Value': 'AI-Engineering'},
{'Key': 'Lifecycle', 'Value': 'permanent'} # vs 'temporary'
]
)
# === 4. USE COST EXPLORER TO ANALYZE SPENDING ===
response = ce.get_cost_and_usage(
TimePeriod={
'Start': (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d'),
'End': datetime.now().strftime('%Y-%m-%d')
},
Granularity='MONTHLY',
Metrics=['UnblendedCost'],
GroupBy=[
{'Type': 'DIMENSION', 'Key': 'SERVICE'}, # Group by service (EC2, Lambda, etc)
]
)
for result in response['ResultsByTime']:
print(f"Period: {result['TimePeriod']['Start']}")
for group in result['Groups']:
service = group['Keys'][0]
cost = float(group['Metrics']['UnblendedCost']['Amount'])
print(f" {service}: ${cost:.2f}")
# === 5. AUTO SCALING POLICY (EC2) ===
autoscaling = boto3.client('autoscaling')
autoscaling.create_auto_scaling_group(
AutoScalingGroupName='ml-pipeline-asg',
LaunchTemplate={'LaunchTemplateName': 'ml-template'},
MinSize=1,
MaxSize=10,
DesiredCapacity=2
)
# Scale by CPU usage
autoscaling.put_scaling_policy(
AutoScalingGroupName='ml-pipeline-asg',
PolicyName='scale-up-cpu',
PolicyType='TargetTrackingScaling',
TargetTrackingConfiguration={
'TargetValue': 70.0,
'PredefinedMetricSpecification': {'PredefinedMetricType': 'ASGAverageCPUUtilization'},
'DisableScaleIn': False
}
)
# === 6. SPOT INSTANCE WITH INTERRUPTION HANDLING ===
# EC2 launches Spot, but saves to S3 before termination
ec2_code = '''
import boto3, signal, json
s3 = boto3.client('s3')
def handle_interruption(signum, frame):
# Save checkpoint before dying
with open('/tmp/checkpoint.json', 'w') as f:
json.dump({'step': 100, 'data': [...]}, f)
s3.upload_file('/tmp/checkpoint.json', 'my-bucket', 'checkpoints/latest.json')
exit(0)
signal.signal(signal.SIGTERM, handle_interruption)
# Train model, save progress every step
'''
# === 7. LAMBDA COST ESTIMATION ===
# Pricing: $0.0000002 per millisecond + $0.20 per 1M requests
def estimate_lambda_cost(invocations_per_day, avg_duration_ms, memory_mb=128):
requests_per_month = invocations_per_day * 30
total_ms_per_month = requests_per_month * avg_duration_ms
request_cost = (requests_per_month / 1_000_000) * 0.20
compute_cost = (total_ms_per_month / 1_000_000) * 0.0000002 * (memory_mb / 128)
return request_cost + compute_cost
print(f'Lambda 1K invocations/day, 100ms avg, 512 MB: ${estimate_lambda_cost(1000, 100, 512):.2f}/month')
# === 8. MONITOR LAMBDA COSTS ===
cloudwatch.put_metric_alarm(
AlarmName='Lambda-Throttle-Cost-Alert',
MetricName='Throttles',
Namespace='AWS/Lambda',
Statistic='Sum',
Period=300,
Threshold=10, # alert on 10+ throttles in 5 min
ComparisonOperator='GreaterThanThreshold',
AlarmActions=['arn:aws:sns:...']
)Katas (5)
Debugging lab
Detecta y corrige el error en el código.
- 6.15.5.1
# EC2 instance running 24/7, but only used 2 hours/day m5.2xlarge at $0.384/hour × 730 hours/month = $280/month wasted
- 6.15.5.2
# Lambda function invoked 1M times/day, costs exploding # No memory optimization, no throttling response = lambda_client.invoke(FunctionName='process', Memory=1024) # fixed 1GB
- 6.15.5.3
# No budget or cost tracking # Bill surprise: $15K after running query en DynamoDB
- 6.15.5.4
# Training job needs 100 hours, pausing every 8 hours # Using m5.4xlarge On-Demand: $1.536/hour × 100 = $153
- 6.15.5.5
# Application scales from 1 to 1000 requests/min without warning # Buys m5.4xlarge permanently; mostly idle Desired capacity: 10 # always running 10 instances
- 6.15.5.6
# Multi-region replication for 'future-proofing' # Replica en US-EAST, EU-WEST, AP-SOUTHEAST # Costo triplicado sin usuarios en esos lugares