Políticas de Scaling
Tipos de Políticas
Visión General
┌─────────────────────────────────────────────────────────────┐
│ TIPOS DE POLÍTICAS │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ TARGET TRACKING (recomendado) │ │
│ │ ──────────────────────────── │ │
│ │ "Mantener CPU al 50%" │ │
│ │ AWS gestiona todo automáticamente │ │
│ │ ✅ Simple ✅ Eficaz ✅ Recomendado │ │
│ │ │ │
│ ├─────────────────────────────────────────────────────┤ │
│ │ │ │
│ │ STEP SCALING │ │
│ │ ──────────── │ │
│ │ "Si CPU 60-80% → +1, Si CPU 80%+ → +3" │ │
│ │ Respuesta proporcional a la desviación │ │
│ │ ⚠️ Más complejo ✅ Control detallado │ │
│ │ │ │
│ ├─────────────────────────────────────────────────────┤ │
│ │ │ │
│ │ SIMPLE SCALING (legacy) │ │
│ │ ─────────────────────── │ │
│ │ "Si CPU > 70% → +1" │ │
│ │ Cooldown obligatorio entre acciones │ │
│ │ ❌ Antiguo ❌ Menos reactivo │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Target Tracking - Detalles
Métricas Predefinidas
┌─────────────────────────────────────────────────────────────┐
│ MÉTRICAS TARGET TRACKING │
├─────────────────────────────────────────────────────────────┤
│ │
│ MÉTRICA OBJETIVO RECOMENDADO │
│ ──────── ───────────────── │
│ │
│ ASGAverageCPUUtilization 40-70% │
│ (CPU promedio del grupo) │
│ │
│ ASGAverageNetworkIn Según app │
│ (Tráfico de red entrante) │
│ │
│ ASGAverageNetworkOut Según app │
│ (Tráfico de red saliente) │
│ │
│ ALBRequestCountPerTarget 1000-5000 req/target │
│ (Solicitudes por instancia vía ALB) │
│ │
│ ──────────────────────────────────────────────────────── │
│ │
│ Elección de la métrica: │
│ │
│ • App CPU-bound (cálculo) → ASGAverageCPUUtilization │
│ • App I/O-bound (red) → ASGAverageNetworkIn/Out │
│ • Web/API → ALBRequestCountPerTarget │
│ │
└─────────────────────────────────────────────────────────────┘
Configuración Target Tracking
# Política basada en CPU
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name cpu-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"TargetValue": 50.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"ScaleOutCooldown": 60,
"ScaleInCooldown": 300
}'
# Política basada en solicitudes ALB
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name request-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"TargetValue": 1000.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ALBRequestCountPerTarget",
"ResourceLabel": "app/my-alb/xxx/targetgroup/my-tg/yyy"
}
}'
Métricas Personalizadas
Para necesidades específicas, puede crear una métrica personalizada de CloudWatch:
# Publicar una métrica personalizada desde la aplicación
aws cloudwatch put-metric-data \
--namespace "MyApp" \
--metric-name "QueueDepth" \
--value 150 \
--unit Count
# Política Target Tracking sobre métrica personalizada
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name queue-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"TargetValue": 100.0,
"CustomizedMetricSpecification": {
"MetricName": "QueueDepth",
"Namespace": "MyApp",
"Statistic": "Average"
}
}'
Step Scaling - Detalles
Configuración por Niveles
┌─────────────────────────────────────────────────────────────┐
│ STEP SCALING - EJEMPLO │
├─────────────────────────────────────────────────────────────┤
│ │
│ Alarma : CPUUtilization > 60% │
│ │
│ Niveles : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Desviación respecto al umbral Acción │ │
│ │ ───────────────────────────── ────── │ │
│ │ │ │
│ │ 60% ──► 70% (+0 a +10) +1 instancia │ │
│ │ 70% ──► 80% (+10 a +20) +2 instancias │ │
│ │ 80% ──► ∞ (+20 a +∞) +3 instancias │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Ejemplo concreto: │
│ • CPU al 65% → desviación = +5 → +1 instancia │
│ • CPU al 75% → desviación = +15 → +2 instancias │
│ • CPU al 90% → desviación = +30 → +3 instancias │
│ │
│ Ventaja: Respuesta proporcional a la urgencia │
│ │
└─────────────────────────────────────────────────────────────┘
Configuración CLI
# 1. Crear la alarma CloudWatch
aws cloudwatch put-metric-alarm \
--alarm-name cpu-high \
--metric-name CPUUtilization \
--namespace AWS/EC2 \
--statistic Average \
--period 60 \
--threshold 60 \
--comparison-operator GreaterThanOrEqualToThreshold \
--dimensions Name=AutoScalingGroupName,Value=my-asg \
--evaluation-periods 2 \
--alarm-actions arn:aws:autoscaling:...:scalingPolicy:...:policyName/step-scale-out
# 2. Crear la política Step Scaling
aws autoscaling put-scaling-policy \
--auto-scaling-group-name my-asg \
--policy-name step-scale-out \
--policy-type StepScaling \
--adjustment-type ChangeInCapacity \
--step-adjustments '[
{
"MetricIntervalLowerBound": 0,
"MetricIntervalUpperBound": 10,
"ScalingAdjustment": 1
},
{
"MetricIntervalLowerBound": 10,
"MetricIntervalUpperBound": 20,
"ScalingAdjustment": 2
},
{
"MetricIntervalLowerBound": 20,
"ScalingAdjustment": 3
}
]'
Scheduled Scaling
Patrones Comunes
┌─────────────────────────────────────────────────────────────┐
│ SCHEDULED SCALING - PATRONES │
├─────────────────────────────────────────────────────────────┤
│ │
│ PATRÓN 1 : Horario de oficina (9h-18h) │
│ ────────────────────────────────────── │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Lun-Vie 9h : min=5, max=20, desired=5 │ │
│ │ Lun-Vie 18h : min=2, max=5, desired=2 │ │
│ │ Sáb-Dom : min=1, max=3 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ PATRÓN 2 : E-commerce (picos y rebajas) │
│ ──────────────────────────────────────── │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Normal : min=3, max=10 │ │
│ │ Black Friday: min=20, max=50 (del 28 al 30 nov) │ │
│ │ Navidad : min=15, max=40 (15-26 dic) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ PATRÓN 3 : Procesamiento batch (noche) │
│ ──────────────────────────────────── │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Día (8h-20h) : min=2, max=5 │ │
│ │ Noche (20h-8h): min=10, max=30 (batch jobs) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Configuración
# Scale up en la mañana (Lun-Vie a las 8:30 UTC)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name my-asg \
--scheduled-action-name morning-scale-up \
--recurrence "30 8 * * MON-FRI" \
--min-size 5 \
--max-size 20 \
--desired-capacity 5
# Scale down en la tarde (Lun-Vie a las 18h UTC)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name my-asg \
--scheduled-action-name evening-scale-down \
--recurrence "0 18 * * MON-FRI" \
--min-size 2 \
--max-size 5 \
--desired-capacity 2
# Fin de semana (Sábado a las 0h)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name my-asg \
--scheduled-action-name weekend-scale-down \
--recurrence "0 0 * * SAT" \
--min-size 1 \
--max-size 3
# Evento puntual (Black Friday)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name my-asg \
--scheduled-action-name black-friday \
--start-time "2024-11-28T00:00:00Z" \
--end-time "2024-12-01T00:00:00Z" \
--min-size 20 \
--max-size 50
Combinar las Políticas
Estrategia Recomendada
┌─────────────────────────────────────────────────────────────┐
│ COMBINACIÓN DE POLÍTICAS │
├─────────────────────────────────────────────────────────────┤
│ │
│ Mejor práctica: Combinar varios tipos │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ 1. SCHEDULED (base) │ │
│ │ ───────────────── │ │
│ │ Define los min/max según patrones conocidos │ │
│ │ Ej: Más capacidad en horario de oficina │ │
│ │ │ │
│ │ + │ │
│ │ │ │
│ │ 2. TARGET TRACKING (ajuste fino) │ │
│ │ ─────────────────────────────── │ │
│ │ Ajusta dentro de los límites min/max │ │
│ │ Ej: Mantener CPU al 50% │ │
│ │ │ │
│ │ = │ │
│ │ │ │
│ │ ¡Arquitectura óptima! │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Ejemplo: │
│ • Scheduled : 9h → min:5, max:20 │
│ • Target Tracking : CPU 50% │
│ • Resultado : Entre 9h y 18h, el número de instancias │
│ varía entre 5 y 20 para mantener CPU al 50% │
│ │
└─────────────────────────────────────────────────────────────┘
Buenas Prácticas
Checklist de Configuración
┌─────────────────────────────────────────────────────────────┐
│ CHECKLIST BUENAS PRÁCTICAS │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ GENERAL │
│ ──────── │
│ ☐ Min >= 2 (alta disponibilidad) │
│ ☐ Instancias en 2+ AZ │
│ ☐ Health checks EC2 Y ELB activados │
│ ☐ Política de terminación apropiada │
│ │
│ ✅ TARGET TRACKING │
│ ───────────────── │
│ ☐ Target value no demasiado agresivo (50-70% CPU) │
│ ☐ Scale out cooldown corto (60s) │
│ ☐ Scale in cooldown más largo (300s) │
│ ☐ Warmup suficiente para la aplicación │
│ │
│ ✅ INSTANCIAS │
│ ─────────── │
│ ☐ User data idempotente y rápido │
│ ☐ AMI preconfigurada (reducir startup time) │
│ ☐ Aplicación stateless │
│ ☐ Graceful shutdown (lifecycle hooks) │
│ │
│ ❌ A EVITAR │
│ ───────── │
│ ☐ Min = Max = 1 (sin HA) │
│ ☐ Umbrales demasiado sensibles (oscilaciones) │
│ ☐ Cooldown demasiado corto (scaling muy frecuente) │
│ ☐ Sin monitoreo de métricas │
│ │
└─────────────────────────────────────────────────────────────┘
Troubleshooting
| Problema | Causa Probable | Solución |
|---|---|---|
| Scaling demasiado lento | Cooldown demasiado largo | Reducir scale out cooldown |
| Oscilaciones | Umbrales demasiado cercanos | Aumentar la diferencia entre umbrales |
| No escala | Métricas no recibidas | Verificar CloudWatch Agent |
| Scale in elimina instancias activas | Sin grace period | Añadir lifecycle hooks |
Resumen
| Tipo | Caso de uso | Complejidad |
|---|---|---|
| Target Tracking | 90% de los casos, recomendado | ⭐ Fácil |
| Scheduled | Patrones previsibles | ⭐⭐ Medio |
| Step | Respuesta proporcional | ⭐⭐⭐ Avanzado |
| Combinado | Producción óptima | ⭐⭐ Medio |
Próxima sección: Lab Auto Scaling