EC2
04 / 08

Auto Scaling & Load Balancing

Auto Scaling & Load Balancing

Auto Scaling Groups (ASG) combined with Application Load Balancers (ALB) are the standard pattern for elastic, highly available EC2 deployments. Understanding Launch Templates, scaling policies, and target groups is essential.

Launch Templates & Auto Scaling Groups

# Create a Launch Template (replaces Launch Configurations — use LT)
aws ec2 create-launch-template \
  --launch-template-name web-server-lt \
  --version-description "v1" \
  --launch-template-data '{
    "ImageId": "ami-0c02fb55956c7d316",
    "InstanceType": "t3.medium",
    "KeyName": "my-key",
    "SecurityGroupIds": ["sg-0a1b2c3d4e5f67890"],
    "UserData": $(base64 -w0 bootstrap.sh),
    "IamInstanceProfile": {"Name": "my-ec2-role"},
    "TagSpecifications": [{
      "ResourceType": "instance",
      "Tags": [{"Key": "Name", "Value": "web-server"}]
    }]
  }'

# Create Auto Scaling Group
aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name web-asg \
  --launch-template "LaunchTemplateName=web-server-lt,Version=1" \
  --min-size 2 \
  --max-size 10 \
  --desired-capacity 3 \
  --vpc-zone-identifier "subnet-aaa111,subnet-bbb222,subnet-ccc333" \
  --target-group-arns arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/web-tg/abc123 \
  --health-check-type ELB \
  --health-check-grace-period 300

# Update desired capacity manually
aws autoscaling set-desired-capacity \
  --auto-scaling-group-name web-asg \
  --desired-capacity 5

# Describe instances in ASG
aws autoscaling describe-auto-scaling-instances \
  --query "AutoScalingInstances[?AutoScalingGroupName=='web-asg']"

Scaling Policies

# Target Tracking — simplest, most common (like a thermostat)
# Automatically adds/removes instances to keep a metric at a target value
aws autoscaling put-scaling-policy \
  --auto-scaling-group-name web-asg \
  --policy-name cpu-target-tracking \
  --policy-type TargetTrackingScaling \
  --target-tracking-configuration '{
    "PredefinedMetricSpecification": {
      "PredefinedMetricType": "ASGAverageCPUUtilization"
    },
    "TargetValue": 60.0,
    "ScaleInCooldown": 300,
    "ScaleOutCooldown": 60
  }'

# Step Scaling — fine-grained control with CloudWatch alarms
# Scale out by 2 when CPU > 70%, by 4 when CPU > 85%

# Scheduled Scaling — predictable load patterns
aws autoscaling put-scheduled-update-group-action \
  --auto-scaling-group-name web-asg \
  --scheduled-action-name scale-up-morning \
  --recurrence "0 8 * * MON-FRI" \
  --desired-capacity 6 \
  --min-size 4

aws autoscaling put-scheduled-update-group-action \
  --auto-scaling-group-name web-asg \
  --scheduled-action-name scale-down-night \
  --recurrence "0 20 * * *" \
  --desired-capacity 2 \
  --min-size 2

# Instance refresh — rolling update of instances (e.g. after LT change)
aws autoscaling start-instance-refresh \
  --auto-scaling-group-name web-asg \
  --preferences "MinHealthyPercentage=90,InstanceWarmup=300"

ALB, Target Groups & Blue/Green Deploy

# Load Balancer types:
# ALB (Application LB) — HTTP/HTTPS, path/host-based routing, WebSockets, gRPC
# NLB (Network LB)     — TCP/UDP, ultra-low latency, static IPs, millions of requests/sec
# CLB (Classic LB)     — legacy, do not use for new projects

# Create ALB
aws elbv2 create-load-balancer \
  --name web-alb \
  --subnets subnet-public-aaa111 subnet-public-bbb222 \
  --security-groups sg-alb123 \
  --scheme internet-facing \
  --type application

# Create Target Group
aws elbv2 create-target-group \
  --name web-tg \
  --protocol HTTP \
  --port 8080 \
  --vpc-id vpc-0abc123 \
  --health-check-path /health \
  --health-check-interval-seconds 15 \
  --healthy-threshold-count 2 \
  --unhealthy-threshold-count 3 \
  --target-type instance

# Create Listener with forward rule
aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:...:loadbalancer/app/web-alb/abc \
  --protocol HTTPS --port 443 \
  --certificates "CertificateArn=arn:aws:acm:us-east-1:123:certificate/abc" \
  --default-actions "Type=forward,TargetGroupArn=arn:aws:...:targetgroup/web-tg/abc"

# Blue/Green deployment with ASG:
# 1. Create green ASG with new Launch Template version
# 2. Register green ASG with same ALB target group
# 3. Wait for green instances to pass health checks
# 4. Shift traffic by updating listener rules (weighted target groups)
# 5. Deregister blue ASG from target group, then terminate

# Weighted target groups (canary / gradual shift)
aws elbv2 modify-listener \
  --listener-arn arn:aws:...:listener/app/web-alb/abc \
  --default-actions Type=forward,ForwardConfig='{
    "TargetGroups": [
      {"TargetGroupArn": "arn:...:targetgroup/blue-tg/111", "Weight": 80},
      {"TargetGroupArn": "arn:...:targetgroup/green-tg/222", "Weight": 20}
    ]
  }'

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free