Políticas de Scaling
Tipos de Políticas
Visão Geral
┌─────────────────────────────────────────────────────────────┐
│ TIPOS DE POLÍTICAS │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ TARGET TRACKING (recomendado) │ │
│ │ ──────────────────────────── │ │
│ │ "Manter CPU em 50%" │ │
│ │ AWS gerencia tudo automaticamente │ │
│ │ ✅ Simples ✅ Eficaz ✅ Recomendado │ │
│ │ │ │
│ ├─────────────────────────────────────────────────────┤ │
│ │ │ │
│ │ STEP SCALING │ │
│ │ ──────────── │ │
│ │ "Se CPU 60-80% → +1, Se CPU 80%+ → +3" │ │
│ │ Resposta proporcional ao desvio │ │
│ │ ⚠️ Mais complexo ✅ Controle refinado │ │
│ │ │ │
│ ├─────────────────────────────────────────────────────┤ │
│ │ │ │
│ │ SIMPLE SCALING (legado) │ │
│ │ ─────────────────────── │ │
│ │ "Se CPU > 70% → +1" │ │
│ │ Cooldown obrigatório entre ações │ │
│ │ ❌ Antigo ❌ Menos responsivo │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Target Tracking - Detalhes
Métricas Pré-definidas
┌─────────────────────────────────────────────────────────────┐
│ MÉTRICAS TARGET TRACKING │
├─────────────────────────────────────────────────────────────┤
│ │
│ MÉTRICA ALVO RECOMENDADO │
│ ──────── ───────────────── │
│ │
│ ASGAverageCPUUtilization 40-70% │
│ (CPU média do grupo) │
│ │
│ ASGAverageNetworkIn Conforme app │
│ (Tráfego de rede de entrada) │
│ │
│ ASGAverageNetworkOut Conforme app │
│ (Tráfego de rede de saída) │
│ │
│ ALBRequestCountPerTarget 1000-5000 req/target │
│ (Requisições por instância via ALB) │
│ │
│ ──────────────────────────────────────────────────────── │
│ │
│ Escolha da métrica: │
│ │
│ • App CPU-bound (cálculo) → ASGAverageCPUUtilization │
│ • App I/O-bound (rede) → ASGAverageNetworkIn/Out │
│ • Web/API → ALBRequestCountPerTarget │
│ │
└─────────────────────────────────────────────────────────────┘
Configuração Target Tracking
# Política baseada em 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 baseada em requisições 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 necessidades específicas, você pode criar uma métrica personalizada no CloudWatch:
# Publicar uma métrica customizada a partir do aplicativo
aws cloudwatch put-metric-data \
--namespace "MyApp" \
--metric-name "QueueDepth" \
--value 150 \
--unit Count
# Política Target Tracking em métrica customizada
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 - Detalhes
Configuração por Níveis
┌─────────────────────────────────────────────────────────────┐
│ STEP SCALING - EXEMPLO │
├─────────────────────────────────────────────────────────────┤
│ │
│ Alarme : CPUUtilization > 60% │
│ │
│ Níveis : │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Desvio em relação ao limite Ação │ │
│ │ ────────────────────────── ────── │ │
│ │ │ │
│ │ 60% ──► 70% (+0 a +10) +1 instância │ │
│ │ 70% ──► 80% (+10 a +20) +2 instâncias │ │
│ │ 80% ──► ∞ (+20 a +∞) +3 instâncias │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Exemplo prático: │
│ • CPU em 65% → desvio = +5 → +1 instância │
│ • CPU em 75% → desvio = +15 → +2 instâncias │
│ • CPU em 90% → desvio = +30 → +3 instâncias │
│ │
│ Vantagem: Resposta proporcional à urgência │
│ │
└─────────────────────────────────────────────────────────────┘
Configuração CLI
# 1. Criar o alarme 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. Criar a 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
Padrões Comuns
┌─────────────────────────────────────────────────────────────┐
│ SCHEDULED SCALING - PADRÕES │
├─────────────────────────────────────────────────────────────┤
│ │
│ PADRÃO 1 : Horário comercial (9h-18h) │
│ ────────────────────────────────────── │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Seg-Sex 9h : min=5, max=20, desired=5 │ │
│ │ Seg-Sex 18h : min=2, max=5, desired=2 │ │
│ │ Sáb-Dom : min=1, max=3 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ PADRÃO 2 : E-commerce (picos e promoções) │
│ ──────────────────────────────────────── │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Normal : min=3, max=10 │ │
│ │ Black Friday: min=20, max=50 (de 28 a 30 nov) │ │
│ │ Natal : min=15, max=40 (15-26 dez) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ PADRÃO 3 : Processamento batch (noite) │
│ ──────────────────────────────────── │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ Dia (8h-20h) : min=2, max=5 │ │
│ │ Noite (20h-8h): min=10, max=30 (batch jobs) │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
Configuração
# Scale up pela manhã (Seg-Sex às 8h30 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 à noite (Seg-Sex às 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
# Final de semana (Sábado às 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 pontual (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
Combinando as Políticas
Estratégia Recomendada
┌─────────────────────────────────────────────────────────────┐
│ COMBINAÇÃO DE POLÍTICAS │
├─────────────────────────────────────────────────────────────┤
│ │
│ Melhor prática: Combinar vários tipos │
│ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ 1. SCHEDULED (base) │ │
│ │ ───────────────── │ │
│ │ Define min/max conforme padrões conhecidos │ │
│ │ Ex: Mais capacidade no horário comercial │ │
│ │ │ │
│ │ + │ │
│ │ │ │
│ │ 2. TARGET TRACKING (ajuste fino) │ │
│ │ ─────────────────────────────── │ │
│ │ Ajusta dentro dos limites min/max │ │
│ │ Ex: Manter CPU em 50% │ │
│ │ │ │
│ │ = │ │
│ │ │ │
│ │ Arquitetura ideal! │ │
│ │ │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
│ Exemplo: │
│ • Scheduled: 9h → min:5, max:20 │
│ • Target Tracking: CPU 50% │
│ • Resultado: Entre 9h e 18h, o número de instâncias │
│ varia entre 5 e 20 para manter CPU em 50% │
│ │
└─────────────────────────────────────────────────────────────┘
Boas Práticas
Checklist de Configuração
┌─────────────────────────────────────────────────────────────┐
│ CHECKLIST BOAS PRÁTICAS │
├─────────────────────────────────────────────────────────────┤
│ │
│ ✅ GERAL │
│ ──────── │
│ ☐ Min >= 2 (alta disponibilidade) │
│ ☐ Instâncias em 2+ AZ │
│ ☐ Health checks EC2 E ELB ativados │
│ ☐ Termination policy apropriada │
│ │
│ ✅ TARGET TRACKING │
│ ───────────────── │
│ ☐ Target value não muito agressivo (50-70% CPU) │
│ ☐ Scale out cooldown curto (60s) │
│ ☐ Scale in cooldown mais longo (300s) │
│ ☐ Warmup suficiente para o aplicativo │
│ │
│ ✅ INSTÂNCIAS │
│ ─────────── │
│ ☐ User data idempotente e rápido │
│ ☐ AMI pré-configurada (reduzir startup time) │
│ ☐ Aplicação stateless │
│ ☐ Graceful shutdown (lifecycle hooks) │
│ │
│ ❌ EVITAR │
│ ───────── │
│ ☐ Min = Max = 1 (sem HA) │
│ ☐ Limiares muito sensíveis (oscilações) │
│ ☐ Cooldown muito curto (scaling muito frequente) │
│ ☐ Sem monitoramento das métricas │
│ │
└─────────────────────────────────────────────────────────────┘
Troubleshooting
| Problema | Causa Provável | Solução |
|---|---|---|
| Scaling muito lento | Cooldown muito longo | Reduzir scale out cooldown |
| Oscilações | Limiares muito próximos | Aumentar a diferença entre limiares |
| Não faz scaling | Métricas não recebidas | Verificar CloudWatch Agent |
| Scale in mata instâncias ativas | Sem grace period | Adicionar lifecycle hooks |
Resumo
| Tipo | Caso de uso | Complexidade |
|---|---|---|
| Target Tracking | 90% dos casos, recomendado | ⭐ Fácil |
| Scheduled | Padrões previsíveis | ⭐⭐ Médio |
| Step | Resposta proporcional | ⭐⭐⭐ Avançado |
| Combinado | Produção ideal | ⭐⭐ Médio |
Próxima seção: Lab Auto Scaling