Sub topic 8
Auto Scaling Groups That Span AZs
This chapter assumes you know how to create VPC subnets in several Availability Zones (AZs), how an Application Load Balancer (ALB) uses target groups, and how to read a CloudFormation template. An Auto Scaling group (ASG) keeps a set of EC2 instances running at the size you ask for. When you give it subnets in more than one AZ, it also becomes your main tool for keeping compute spread across failure domains.
What an ASG does for availability
An ASG gives you three things that matter for high availability:
- Replacement. If an instance fails a health check, the group terminates it and launches a new one.
- Distribution. The group spreads instances across the AZs you configure.
- Elasticity. The group changes the instance count in response to scaling policies or schedules.
The AZs an ASG uses come from the subnets in its VPCZoneIdentifier list. Each subnet lives in exactly one AZ, so the subnet list is your AZ list. Putting two private subnets in different AZs is the minimum for surviving the loss of one zone.
A multi-AZ group in CloudFormation
The template below defines a group of two to six instances in two private subnets. It registers instances with a target group and uses the load balancer's health checks.
Resources:
WebAsg:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
MinSize: "2"
MaxSize: "6"
DesiredCapacity: "2"
VPCZoneIdentifier:
- !Ref PrivateSubnetA
- !Ref PrivateSubnetB
LaunchTemplate:
LaunchTemplateId: !Ref WebLaunchTemplate
Version: !GetAtt WebLaunchTemplate.LatestVersionNumber
TargetGroupARNs:
- !Ref WebTargetGroup
HealthCheckType: ELB
HealthCheckGracePeriod: 120Key properties:
VPCZoneIdentifierlists the subnets. Do not also setAvailabilityZonesunless it matches those subnets. With subnets, the subnets decide the zones.LaunchTemplatewith a version pins the instance configuration.LatestVersionNumbermakes CloudFormation update the group when the template changes.TargetGroupARNsattaches the group to the load balancer, so new instances receive traffic once they pass health checks and terminated instances are deregistered.HealthCheckType: ELBis explained in the next section.HealthCheckGracePeriodgives a new instance time to boot before health checks count against it.
Health checks: EC2 versus ELB
By default an ASG uses only EC2 health checks. These detect that the instance is stopped, terminated, or failing its system status checks. They do not detect an application that has crashed or hung on a running instance.
With HealthCheckType: ELB, the group also treats an instance as unhealthy when the target group reports it unhealthy. The group then replaces it. This is what you want for a web tier.
Set the grace period longer than your real boot and warm-up time. If it is too short, the group can terminate instances that were still starting, which produces a launch-and-terminate loop. If it is too long, a broken instance stays in service longer before replacement.
How the group balances across AZs
The group tries to keep the instance count roughly equal in each AZ. With a desired capacity of 6 and three subnets, you get 2 instances in each zone.
When the group must launch or terminate instances, it follows a pattern:
- On scale-out, it launches into the AZ with the fewest instances.
- On scale-in, it picks the AZ with the most instances, then applies its termination policy inside that zone.
- If an AZ is unhealthy or lacks capacity, the group launches in another AZ, so the counts become uneven.
Step 3 is the AZ rebalancing behavior. When the unhealthy AZ recovers, the group notices the imbalance and rebalances by launching new instances in the underfilled zone, then terminating older instances in the overfilled one. Launching happens first, so capacity does not dip. You may briefly see the group exceed its desired capacity during rebalancing.
The AZRebalance process is one of the group's suspendable processes. Suspending it stops rebalancing, which some stateful workloads want. For a stateless web tier, leave it on.
The load balancer side
The ASG controls where instances run. The load balancer controls where requests go. Both must agree. If your ALB has nodes in two AZs, but your ASG only uses subnets in one, the second AZ's load balancer node has no healthy targets in its own zone. With cross-zone load balancing on (the ALB default), it can still send traffic to the other zone, but you have lost the redundancy you wanted.
For Network Load Balancers, cross-zone load balancing is off by default. Without it, each load balancer node sends traffic only to targets in its own AZ. If the ASG ends up uneven, the AZ with fewer instances receives the same share of traffic as the others and can be overloaded. Enable it on the target group when you cannot guarantee equal capacity per zone:
aws elbv2 modify-target-group-attributes \
--target-group-arn "$TARGET_GROUP_ARN" \
--attributes Key=load_balancing.cross_zone.enabled,Value=trueCross-zone traffic through an NLB can add inter-AZ data transfer charges, so weigh that against the balance benefit. Chapter material on cost covers this trade-off.
Sizing for AZ loss
Spreading instances across AZs does not by itself keep you available. You also need enough capacity left after a zone disappears.
Consider a group across 3 AZs that needs 6 instances' worth of capacity at peak. If you run 6 instances (2 per AZ) and one zone fails, you lose a third of capacity. The remaining 4 instances must absorb the full load.
To survive the loss of one of N zones at full load, the capacity per zone must satisfy:
- Total instances = required instances × N / (N − 1)
For 6 required instances in 3 AZs, you need 9 instances, or 3 per zone. With 2 AZs, you need to run double the required capacity. The more AZs you use, the lower the overhead of this headroom. Chapter material on static stability expands on why you should provision this in advance instead of relying on the group to launch replacements during an incident.
| AZs used | Instances needed per 6 required | Overhead |
|---|---|---|
| 2 | 12 | 100% |
| 3 | 9 | 50% |
| 4 | 8 | 33% |
Set MinSize to a value that already includes this headroom. Setting MinSize low and expecting scaling to fix things relies on launches succeeding during the failure, when other customers may also be shifting capacity.
Scaling policies and multiple AZs
Target tracking policies, such as keeping average CPU at 50% or request count per target at a fixed value, work on the group as a whole. If one AZ fails and the survivors become hot, the metric rises and the group scales out in the remaining AZs. That is useful, but it is reactive. It takes minutes for metrics to cross a threshold, for instances to launch, and for health checks to pass.
Prefer ALBRequestCountPerTarget for web tiers where request cost is uniform, since it responds to load directly. Use a CPU target when the work is compute-bound.
Instance diversity and capacity errors
An AZ can run short of a specific instance type. A group using a single type can fail to launch in that AZ. A mixed instances policy lets the group choose among several instance types, which reduces the chance of an InsufficientInstanceCapacity error. Use several types of similar size and architecture, and avoid pinning to one.
Use AZ IDs rather than names when you need to reason about physical zones across accounts, since zone names are mapped differently per account. You can list the mapping with:
aws ec2 describe-availability-zones \
--query 'AvailabilityZones[].[ZoneName,ZoneId]' \
--output tableCommon mistakes
- Subnets in one AZ only. The group is healthy but has no zonal redundancy.
- Default EC2 health checks. A hung application never gets replaced.
- Short grace period. The group kills instances still booting.
- MinSize equal to the exact peak need. One AZ loss drops you below capacity.
- Stateful instances. If instances hold sessions or local data, replacing them loses it. Keep the tier stateless, as the earlier chapter describes.
- Mismatched subnets. The ASG uses subnets that the load balancer does not have enabled for the same AZ, so targets in that AZ receive no traffic.
Checking the result
After deployment, confirm the spread:
aws autoscaling describe-auto-scaling-groups \
--auto-scaling-group-names WebAsg \
--query 'AutoScalingGroups[0].Instances[].[InstanceId,AvailabilityZone,HealthStatus]' \
--output tableLook for an even distribution across zones and all instances Healthy.
Exercise
A web tier must handle 8 instances' worth of load at peak and survive the loss of one AZ with no loss of capacity. The ASG uses 3 AZs. How many instances should it run, how should they be distributed, and which health check type should it use?
Show answer
Required × N / (N − 1) = 8 × 3 / 2 = 12 instances, distributed 4 per AZ. If one AZ fails, the remaining 8 instances still carry the full peak load. Use HealthCheckType ELB so instances whose application fails the load balancer health check are replaced, with a grace period longer than the instance warm-up time.
Exercise
Your ASG has subnets in two AZs behind a Network Load Balancer with cross-zone load balancing off. During an incident, the group launches replacements only in AZ A, leaving 6 instances in AZ A and 2 in AZ B. What happens to traffic, and what setting changes it?
Show answer
Each NLB node sends traffic only to targets in its own AZ, so AZ B's 2 instances receive about half of the traffic and can be overloaded while AZ A's 6 are underused. Enabling cross-zone load balancing on the target group (loadbalancing.crosszone.enabled=true) spreads requests across all 8 instances, at the cost of possible inter-AZ data transfer charges.