Lab : Configuração de Auto Scaling
Objetivo do Lab
Projetar e configurar uma solução completa de Auto Scaling para uma aplicação web com padrões de tráfego variáveis.
Parte 1 : Cenário
Contexto
NewsPortal é um site de notícias que experimenta picos de tráfego imprevisíveis durante breaking news. A equipe técnica deseja automatizar o scaling para:
- Manter a performance durante os picos
- Reduzir custos durante horários de baixo movimento
Dados de Tráfego
┌─────────────────────────────────────────────────────────────┐
│ PADRÕES DE TRÁFEGO NEWSPORTAL │
├─────────────────────────────────────────────────────────────┤
│ │
│ DIA NORMAL │
│ ─────────────── │
│ │
│ Visitantes ▲ │
│ │ ┌────┐ │
│ 50,000 ─┤ ┌┘ └┐ │
│ │ ┌┘ └┐ ┌──┐ │
│ 30,000 ─┤ ┌──┘ └──────┘ └┐ │
│ │ ┌──┘ └──┐ │
│ 10,000 ─┤──┘ └── │
│ │ │
│ └─────┬─────┬─────┬─────┬─────┬─────► Hora │
│ 6h 9h 12h 18h 21h │
│ │
│ BREAKING NEWS (imprevisível) │
│ ─────────────────────────── │
│ │
│ Visitantes ▲ │
│ │ ▲ Pico repentino x10 │
│ 200,000 ─┤ ╱╲ │
│ │ ╱ ╲ │
│ 100,000 ─┤ ╱ ╲ │
│ │ ╱ ╲ │
│ 20,000 ─┤──────╱ ╲────────── │
│ │ │
│ └─────────────────────────────────► Tempo │
│ │
└─────────────────────────────────────────────────────────────┘
Requisitos
| Aspecto | Requisito |
|---|---|
| Disponibilidade | 99.9% |
| Tempo de resposta | < 500ms (P95) |
| Capacidade min | 5.000 visitantes/min |
| Capacidade máx | 200.000 visitantes/min |
| Orçamento | Otimizar custos fora dos picos |
Parte 2 : Exercícios de Design
Exercício 2.1 : Dimensionamento
Sabendo que uma instância t3.medium pode suportar 500 requisições/segundo, calcule:
| Pergunta | Sua Resposta |
|---|---|
| Instâncias mínimas (normal) | ? |
| Instâncias para pico x10 | ? |
| Mínimo recomendado para HA | ? |
| Máximo recomendado | ? |
💡 Solução
Tráfego normal: 50.000 visitantes/min = 833 req/seg
Instâncias necessárias: 833 / 500 = 2 instâncias
Tráfego pico x10: 200.000 visitantes/min = 3.333 req/seg
Instâncias necessárias: 3.333 / 500 = 7 instâncias (arredondado)
Mínimo recomendado: 2 (HA Multi-AZ)
Máximo recomendado: 10 (margem de segurança)
Desired initial: 2
Exercício 2.2 : Escolha da Política
Qual(is) política(s) de scaling você recomenda e por quê?
| Política | Apropriada? | Justificativa |
|---|---|---|
| Target Tracking CPU | ? | ? |
| Target Tracking Requests | ? | ? |
| Scheduled | ? | ? |
| Step Scaling | ? | ? |
💡 Solução
| Política | Apropriada? | Justificativa |
|---|---|---|
| Target Tracking CPU | ⚠️ Parcial | Útil, mas CPU nem sempre correlaciona com requisições |
| Target Tracking Requests | ✅ SIM | Diretamente ligado ao tráfego de usuários |
| Scheduled | ⚠️ Parcial | Padrões dia/noite previsíveis, mas não breaking news |
| Step Scaling | ✅ SIM | Resposta rápida a picos repentinos |
Recomendação: Combinar Target Tracking (requests) + Scheduled (base)
Exercício 2.3 : Configuração do Launch Template
Complete a configuração do Launch Template:
# Launch Template Configuration
LaunchTemplateName: newsportal-lt
# À completar:
AMI: _______________
InstanceType: _______________
SecurityGroupIds:
- _______________
KeyName: _______________
UserData: |
#!/bin/bash
_______________
_______________
_______________
💡 Solução
LaunchTemplateName: newsportal-lt
AMI: ami-0123456789 (Amazon Linux 2, pré-configurada)
InstanceType: t3.medium
SecurityGroupIds:
- sg-web-servers
KeyName: newsportal-key
UserData: |
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
# Ou deploy do app via CodeDeploy
aws s3 cp s3://newsportal-deploy/latest.tar.gz /tmp/
tar -xzf /tmp/latest.tar.gz -C /var/www/html/
Exercício 2.4 : Configuração do ASG
Complete a configuração do Auto Scaling Group:
AutoScalingGroupName: newsportal-asg
# Capacidade
MinSize: ___
MaxSize: ___
DesiredCapacity: ___
# Rede (mínimo 2 AZ)
VPCZoneIdentifier:
- _______________
- _______________
# Health Checks
HealthCheckType: _______________
HealthCheckGracePeriod: ___
# Target Group
TargetGroupARNs:
- _______________
💡 Solução
AutoScalingGroupName: newsportal-asg
MinSize: 2
MaxSize: 10
DesiredCapacity: 2
VPCZoneIdentifier:
- subnet-private-az-a
- subnet-private-az-b
HealthCheckType: ELB # Usa health checks do ALB
HealthCheckGracePeriod: 300 # 5 minutos para inicialização do app
TargetGroupARNs:
- arn:aws:elasticloadbalancing:...:targetgroup/newsportal-tg/xxx
Parte 3 : Configuração das Políticas
Exercício 3.1 : Target Tracking
Crie uma política Target Tracking para manter 1000 requisições por target:
# Complete o comando
aws autoscaling put-scaling-policy \
--auto-scaling-group-name newsportal-asg \
--policy-name _______________ \
--policy-type _______________ \
--target-tracking-configuration '{
"TargetValue": ___,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "_______________",
"ResourceLabel": "app/newsportal-alb/xxx/targetgroup/newsportal-tg/yyy"
},
"ScaleOutCooldown": ___,
"ScaleInCooldown": ___
}'
💡 Solução
aws autoscaling put-scaling-policy \
--auto-scaling-group-name newsportal-asg \
--policy-name request-target-tracking \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"TargetValue": 1000.0,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ALBRequestCountPerTarget",
"ResourceLabel": "app/newsportal-alb/xxx/targetgroup/newsportal-tg/yyy"
},
"ScaleOutCooldown": 60,
"ScaleInCooldown": 300
}'
Exercício 3.2 : Scheduled Scaling
Configure o scaling agendado para os padrões dia/noite:
# Morning scale up (8h UTC, Seg-Sex)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name newsportal-asg \
--scheduled-action-name _______________ \
--recurrence "_______________ " \
--min-size ___ \
--max-size ___
# Evening scale down (22h UTC, todos os dias)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name newsportal-asg \
--scheduled-action-name _______________ \
--recurrence "_______________" \
--min-size ___ \
--max-size ___
💡 Solução
# Morning scale up (8h UTC, Seg-Sex)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name newsportal-asg \
--scheduled-action-name morning-scale-up \
--recurrence "0 8 * * MON-FRI" \
--min-size 3 \
--max-size 10
# Evening scale down (22h UTC, todos os dias)
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name newsportal-asg \
--scheduled-action-name evening-scale-down \
--recurrence "0 22 * * *" \
--min-size 2 \
--max-size 5
Parte 4 : Monitoramento e Alertas
Exercício 4.1 : CloudWatch Dashboard
Liste as métricas essenciais para monitorar:
| Métrica | Namespace | Limite de Alerta |
|---|---|---|
| ? | AWS/EC2 | ? |
| ? | AWS/ApplicationELB | ? |
| ? | AWS/AutoScaling | ? |
| ? | Custom | ? |
💡 Solução
| Métrica | Namespace | Limite de Alerta |
|---|---|---|
| CPUUtilization | AWS/EC2 | > 80% |
| TargetResponseTime | AWS/ApplicationELB | > 500ms |
| RequestCount | AWS/ApplicationELB | apenas informativo |
| HealthyHostCount | AWS/ApplicationELB | < 2 |
| GroupDesiredCapacity | AWS/AutoScaling | apenas informativo |
| GroupInServiceInstances | AWS/AutoScaling | < min |
| HTTPCode_Target_5XX_Count | AWS/ApplicationELB | > 10/min |
Exercício 4.2 : Alerta de Scaling
Crie um alerta SNS para notificar durante eventos de scaling:
# 1. Criar o tópico SNS
aws sns create-topic --name _______________
# 2. Assinar por email
aws sns subscribe \
--topic-arn arn:aws:sns:...:_______________ \
--protocol email \
--notification-endpoint _______________
# 3. Configurar notificações do ASG
aws autoscaling put-notification-configuration \
--auto-scaling-group-name newsportal-asg \
--topic-arn arn:aws:sns:...:_______________ \
--notification-types \
"autoscaling:EC2_INSTANCE_LAUNCH" \
"autoscaling:EC2_INSTANCE_TERMINATE" \
"_______________"
💡 Solução
# 1. Criar o tópico SNS
aws sns create-topic --name newsportal-scaling-alerts
# 2. Assinar por email
aws sns subscribe \
--topic-arn arn:aws:sns:us-east-1:123456789:newsportal-scaling-alerts \
--protocol email \
--notification-endpoint ops@newsportal.com
# 3. Configurar notificações do ASG
aws autoscaling put-notification-configuration \
--auto-scaling-group-name newsportal-asg \
--topic-arn arn:aws:sns:us-east-1:123456789:newsportal-scaling-alerts \
--notification-types \
"autoscaling:EC2_INSTANCE_LAUNCH" \
"autoscaling:EC2_INSTANCE_TERMINATE" \
"autoscaling:EC2_INSTANCE_LAUNCH_ERROR"
Parte 5 : Testes de Validação
Plano de Teste
| Teste | Método | Resultado Esperado |
|---|---|---|
| Scale Out | Gerar carga | Novas instâncias em < 5 min |
| Scale In | Parar carga | Redução após cooldown |
| Failover | Terminar instância | Substituição automática |
| Health Check | Parar app | Instância marcada como unhealthy |
Script de Teste de Carga
#!/bin/bash
# test-load.sh - Simular um pico de tráfego
ALB_DNS="newsportal-alb-xxx.region.elb.amazonaws.com"
DURATION=300 # 5 minutos
CONCURRENCY=100
echo "Iniciando teste de carga..."
echo "URL: http://$ALB_DNS"
echo "Duração: $DURATION segundos"
echo "Concorrência: $CONCURRENCY"
# Usar Apache Bench ou hey
hey -z ${DURATION}s -c $CONCURRENCY http://$ALB_DNS/
echo "Teste finalizado. Verifique CloudWatch e ASG."
Checklist de Validação
┌─────────────────────────────────────────────────────────────┐
│ CHECKLIST DE VALIDAÇÃO │
├─────────────────────────────────────────────────────────────┤
│ │
│ ☐ Scale out funcionando (novas instâncias) │
│ ☐ Scale in funcionando (instâncias terminadas) │
│ ☐ Health checks do ALB detectam falhas │
│ ☐ Instâncias unhealthy substituídas automaticamente │
│ ☐ Notificações SNS recebidas │
│ ☐ Métricas visíveis no CloudWatch │
│ ☐ Ações agendadas respeitadas │
│ ☐ Tempo de resposta mantido < 500ms sob carga │
│ │
└─────────────────────────────────────────────────────────────┘
Entregável Final
Documento a Produzir
- Arquitetura de Auto Scaling (diagrama)
- Configuração completa (Launch Template + ASG)
- Políticas de scaling (Target Tracking + Scheduled)
- Plano de monitoramento (métricas + alertas)
- Resultados dos testes (screenshots do CloudWatch)
Critérios de Avaliação
| Critério | Pontos |
|---|---|
| Dimensionamento correto | /15 |
| Configuração completa do ASG | /25 |
| Políticas adequadas ao cenário | /20 |
| Monitoramento e alertas | /15 |
| Testes documentados | /15 |
| Qualidade do documento | /10 |
| Total | /100 |
Próxima semana: MÓDULO 10 - Route 53