EC2 Auto Scaling
Amazon EC2 Auto Scaling keeps the right number of instances running. You define an Auto Scaling group (ASG) with a minimum, a maximum and a desired capacity; the group launches or terminates instances to match, replaces unhealthy ones, and spreads them across Availability Zones.
The pieces
| Piece | Purpose |
|---|---|
| Launch template | What to launch: AMI, instance type, security groups, user data, IAM role |
| Auto Scaling group | Where and how many: subnets (AZs), min/max/desired, attached target groups |
| Scaling policies | When to change the desired capacity |
| Health checks | EC2 status checks and (optionally) the load balancer's health checks |
aws autoscaling create-auto-scaling-group --auto-scaling-group-name web-asg \
--launch-template LaunchTemplateName=web-lt,Version='$Latest' \
--min-size 2 --max-size 10 --desired-capacity 2 \
--vpc-zone-identifier "subnet-0aa11bb22cc33dd44,subnet-0ee55ff66aa77bb88" \
--target-group-arns arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/web-tg/6d0ecf831eec9f09 \
--health-check-type ELB --health-check-grace-period 120
aws autoscaling put-scaling-policy --auto-scaling-group-name web-asg \
--policy-name cpu50 --policy-type TargetTrackingScaling \
--target-tracking-configuration '{"PredefinedMetricSpecification":{"PredefinedMetricType":"ASGAverageCPUUtilization"},"TargetValue":50}'Scaling policies
| Policy | How it works |
|---|---|
| Target tracking | Keep a metric near a target, like "average CPU 50%". The simplest and usually the best choice |
| Step scaling | Add/remove a number of instances depending on how far an alarm threshold is breached |
| Scheduled | Change capacity at fixed times ("10 instances on weekdays 08:00") |
| Predictive | Forecasts daily/weekly patterns from history and scales ahead of time |
Model: target tracking
Target tracking computes the capacity that would bring the metric back to the target: desired = ceil(current_capacity × metric / target), clamped to min and max. In this simulation the total CPU work arrives in "instance-percent" (400 means four instances' worth at 100%).
import math
MIN, MAX, TARGET = 2, 10, 50.0
load = [120, 150, 260, 400, 520, 610, 480, 300, 160, 90] # total CPU work, in % of one instance
capacity = 2
for minute, work in enumerate(load):
cpu = work / capacity
desired = math.ceil(capacity * cpu / TARGET)
desired = max(MIN, min(MAX, desired))
action = "scale out" if desired > capacity else "scale in" if desired < capacity else ""
print(f"t={minute:>2} capacity {capacity:>2} avg CPU {cpu:5.1f}% -> desired {desired:>2} {action}")
capacity = desiredt= 0 capacity 2 avg CPU 60.0% -> desired 3 scale out
t= 1 capacity 3 avg CPU 50.0% -> desired 3
t= 2 capacity 3 avg CPU 86.7% -> desired 6 scale out
t= 3 capacity 6 avg CPU 66.7% -> desired 8 scale out
t= 4 capacity 8 avg CPU 65.0% -> desired 10 scale out
t= 5 capacity 10 avg CPU 61.0% -> desired 10
t= 6 capacity 10 avg CPU 48.0% -> desired 10
t= 7 capacity 10 avg CPU 30.0% -> desired 6 scale in
t= 8 capacity 6 avg CPU 26.7% -> desired 4 scale in
t= 9 capacity 4 avg CPU 22.5% -> desired 2 scale in
The group grows as the load rises and shrinks again afterwards, but never below the minimum of 2 (one per AZ for availability). Real Auto Scaling waits for new instances to warm up and scales in more cautiously than it scales out, so it does not react every minute like this simplified model.
Model: keeping capacity balanced across AZs
When the group launches instances it picks the AZ with the fewest; when it terminates, it removes from the AZ with the most (then, by default, the instance with the oldest launch template). If an AZ fails, its instances are replaced in the healthy AZs.
azs = {"eu-west-1a": [], "eu-west-1b": [], "eu-west-1c": []}
counter = 0
def launch(n):
global counter
for _ in range(n):
az = min(azs, key=lambda a: (len(azs[a]), a))
counter += 1
azs[az].append(f"i-{counter:02d}")
def terminate(n):
for _ in range(n):
az = max(azs, key=lambda a: (len(azs[a]), a))
azs[az].pop(0) # the oldest instance in that AZ
def show(label):
print(f"{label:<26}", {az[-2:]: ids for az, ids in azs.items()})
launch(4); show("launch 4")
launch(3); show("launch 3 more")
terminate(2); show("scale in by 2")
lost = len(azs.pop("eu-west-1b")) # the AZ becomes unavailable
show("AZ 1b fails")
launch(lost); show(f"replace {lost} in healthy AZs")launch 4 {'1a': ['i-01', 'i-04'], '1b': ['i-02'], '1c': ['i-03']}
launch 3 more {'1a': ['i-01', 'i-04', 'i-07'], '1b': ['i-02', 'i-05'], '1c': ['i-03', 'i-06']}
scale in by 2 {'1a': ['i-04', 'i-07'], '1b': ['i-02', 'i-05'], '1c': ['i-06']}
AZ 1b fails {'1a': ['i-04', 'i-07'], '1c': ['i-06']}
replace 2 in healthy AZs {'1a': ['i-04', 'i-07', 'i-09'], '1c': ['i-06', 'i-08']}
Note: For this to work the group must be configured with subnets in several AZs. An ASG with one subnet gives you self-healing but no protection against an AZ outage.
Lifecycle hooks and instance refresh
- Lifecycle hooks pause an instance in
Pending:WaitorTerminating:Waitso a script can install software or drain logs first. - Instance refresh replaces all instances gradually after you change the launch template (a rolling deployment).
- Warm pools keep pre-initialised stopped instances ready for faster scale-out.
Test yourself
An ASG has min 2, max 6 and target tracking on 50% CPU. The current 4 instances average 90% CPU. What desired capacity does target tracking aim for?
- 4
- 6
- 8
- 2
What does a launch template define?
- How many instances to run
- What to launch: AMI, instance type, security groups, user data
- The scaling schedule
- The DNS name
Which policy type is usually the simplest effective choice?
- Manual scaling
- Step scaling
- Target tracking
- Scheduled scaling