Sub topic 19
Scaling out: Auto Scaling groups and load balancers
This chapter assumes you can launch an instance with the CLI, you understand security groups and subnets, and you know how user data and IAM instance profiles work. Scaling is a lighter topic in this tutorial, so the chapter explains the working model and the common errors. It does not cover every option.
Scaling up and scaling out
Scaling up means moving to a larger instance type. It is simple, but it needs a stop and start, it has an upper limit, and one instance is still a single point of failure.
Scaling out means running more instances of the same kind and spreading work across them. Two AWS services do this together:
- An Auto Scaling group (ASG) keeps a chosen number of instances running and replaces unhealthy ones. It can add or remove instances as demand changes.
- An Elastic Load Balancing (ELB) load balancer gives clients one stable address and sends each request to a healthy instance.
Scaling out only works well when instances are interchangeable. Any instance must be able to answer any request, and none of them should hold data that exists nowhere else.
Launch templates
An ASG needs a recipe for new instances. That recipe is a launch template. It stores the settings you would otherwise pass to run-instances: AMI, instance type, key pair, security groups, user data, instance profile, and metadata options.
Because the ASG launches instances without you, everything must be automatic. A new instance has to configure itself from the AMI and user data alone. If you set up a server by hand over SSH, a replacement instance will not have those changes.
cat > template-data.json <<'EOF'
{
"ImageId": "ami-0123456789abcdef0",
"InstanceType": "t3.micro",
"SecurityGroupIds": ["sg-0123456789abcdef0"],
"MetadataOptions": {"HttpTokens": "required"}
}
EOF
aws ec2 create-launch-template \
--launch-template-name web-template \
--launch-template-data file://template-data.jsonLaunch templates are versioned. Changing a template creates a new version, and the ASG uses the version you point it to, such as $Latest or $Default. Existing instances do not change when you update a template. Only newly launched instances use the new version.
Creating an Auto Scaling group
An ASG has three size settings: minimum, maximum, and desired capacity. The group keeps the instance count at the desired capacity and never leaves the minimum and maximum bounds.
You also give it subnets. Choose subnets in different Availability Zones, and the group spreads instances across them. If one zone has a problem, the group launches replacements in the remaining zones.
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name web-asg \
--launch-template LaunchTemplateName=web-template,Version='$Latest' \
--min-size 2 \
--max-size 6 \
--desired-capacity 2 \
--vpc-zone-identifier "subnet-0123456789abcdef0,subnet-0fedcba9876543210"With a minimum of 2 and subnets in two zones, losing one instance or one zone still leaves capacity while replacements start.
Load balancers and target groups
Elastic Load Balancing offers several types. The two you meet first are:
| Type | Works at | Typical use |
|---|---|---|
| Application Load Balancer (ALB) | HTTP and HTTPS (layer 7) | Web apps, routing by path or host name |
| Network Load Balancer (NLB) | TCP, UDP, TLS (layer 4) | Very high throughput, static IP addresses, non-HTTP protocols |
A load balancer sends traffic to a target group, which is a set of targets plus a health check. The health check requests a path such as / on each target. A target that fails repeatedly stops receiving traffic until it passes again.
Attach the ASG to the target group so new instances register themselves and terminated instances are removed:
aws autoscaling attach-traffic-sources \
--auto-scaling-group-name web-asg \
--traffic-sources Identifier=arn:aws:elasticloadbalancing:us-east-1:111122223333:targetgroup/web-tg/0123456789abcdef,Type=elbv2Network rules need two layers. The load balancer has its own security group that allows port 80 or 443 from the internet. The instance security group should allow the application port only from the load balancer's security group, not from 0.0.0.0/0. Instances then cannot be reached directly from outside.
Health checks and replacement
By default an ASG uses EC2 health checks, which look at the instance status checks from the monitoring chapter. A web server can crash while the instance still passes those checks, so the ASG would keep it.
Turn on ELB health checks for the group so the ASG also replaces instances that the load balancer marks unhealthy:
aws autoscaling update-auto-scaling-group \
--auto-scaling-group-name web-asg \
--health-check-type ELB \
--health-check-grace-period 120The grace period is the time after launch during which the ASG ignores failing health checks. Set it longer than your user data bootstrap takes. If it is too short, the ASG terminates instances that are still installing software, then launches new ones that fail the same way. That loop is a common error.
Scaling policies
You can change capacity by hand with set-desired-capacity, on a schedule, or automatically. The simplest automatic option is a target tracking policy. You pick a metric and a target value, and the group adds or removes instances to keep the metric near it.
aws autoscaling put-scaling-policy \
--auto-scaling-group-name web-asg \
--policy-name cpu-50 \
--policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ASGAverageCPUUtilization"
},
"TargetValue": 50.0
}'This keeps average CPU across the group near 50 percent. Scale-in is deliberately slower than scale-out, which prevents instances from being added and removed repeatedly.
Scaling policies rely on CloudWatch metrics. Basic monitoring reports every five minutes, so reactions can lag. Use the metric that reflects your load. For web traffic, ALBRequestCountPerTarget is often better than CPU.
Cost and common errors
Launching more instances raises cost, and the load balancer itself is billed by the hour and by usage. Setting a sensible maximum is your cost cap.
- Stateful instances. Data on one instance's EBS volume or instance store disappears when the ASG terminates it. Keep state in a database, object storage, or a shared service.
- Wrong subnets. Instances in subnets with no route to the load balancer's subnets, or in only one zone, remove the benefit of the group.
- Security group mismatch. Health checks fail if the instance group does not allow traffic from the load balancer.
- Short grace period. Described above.
- Manual changes to instances. They are lost on replacement. Change the launch template instead.
Cleaning up
Delete the group first, because it would otherwise relaunch instances you terminate. Then delete the load balancer resources.
aws autoscaling delete-auto-scaling-group \
--auto-scaling-group-name web-asg \
--force-delete
aws ec2 delete-launch-template --launch-template-name web-template--force-delete terminates the group's instances. Delete the load balancer and target group separately with aws elbv2 delete-load-balancer and aws elbv2 delete-target-group.
Exercise
An ASG launches instances that run a web server through user data. Each new instance is terminated after about two minutes, and the group keeps launching more. The user data takes about four minutes to finish. The group uses ELB health checks with a 60-second grace period. What is wrong, and how do you fix it?
Show answer
The grace period is shorter than the bootstrap time. The load balancer health check fails while the web server is still installing, so the ASG marks the instance unhealthy and replaces it. Raise the health check grace period above the bootstrap time (for example to 300 seconds), or shorten the bootstrap by baking software into a custom AMI.
Exercise
Why should the instance security group allow the application port from the load balancer's security group instead of from 0.0.0.0/0?
Show answer
Referencing the load balancer's security group means only traffic that passes through the load balancer can reach the instances. Clients cannot connect to instances directly, and the rule keeps working when the load balancer's IP addresses change.