Overview and What You Will Learn
An Auto Scaling Group (ASG) is a managed fleet of EC2 instances that grows when demand rises, shrinks when it falls, and replaces any instance that fails its health check. You set the rules once and AWS does the rest. In this lab you build an ASG behind a load balancer, prove it self-heals, and watch a target tracking policy scale out under CPU load.
By the end you will be able to:
- Explain minimum, desired and maximum capacity
- Build a Launch Template that defines exactly what the ASG launches
- Connect an ASG to an Application Load Balancer for self-healing
- Choose between target tracking, step, scheduled and predictive scaling
- Scale on the right metric: CPU, requests per target or queue backlog
- Explain warmup, cooldown, lifecycle hooks, termination policy and Instance Refresh
Why This Matters in Production
A food delivery app such as Swiggy might run 4 instances on a normal Tuesday and see traffic jump tenfold when an IPL final starts. Without automation the instances saturate, latency climbs, and by the time an engineer adds servers the moment has passed. An ASG adds capacity within minutes with no human involved.
It also protects quiet hours. If an instance crashes at 3 AM, the ASG notices, terminates it and launches a replacement. The ASG itself is free, and you pay only for the instances it creates.
Core Principles
What Are Minimum, Desired, and Maximum Capacity in an ASG?
Every ASG is defined by three numbers. Minimum is the floor the group never drops below, maximum is the ceiling it never exceeds, and desired is the target count right now. Scaling policies change the desired number, and the ASG launches or terminates instances to match it, always staying between minimum and maximum.
| Setting | Example | Meaning |
|---|---|---|
| Minimum | 2 | Never fewer than this |
| Desired | 4 | Current target |
| Maximum | 10 | Hard cost ceiling |
RememberSet the minimum to at least 2 and spread the group across 2 Availability Zones. A minimum of 1 means one AZ problem takes the app down until a replacement boots.
What Is a Launch Template and Why Use One?
A Launch Template is the blueprint the ASG uses for every new instance, so every instance is identical. It stores the AMI, instance type, security groups, IAM instance profile, key pair, user data and storage settings, and it supports versions. Launch Configurations are the legacy predecessor and are no longer available to newer accounts, so always use Launch Templates.
A custom AMI with your app already installed makes new instances ready in about a minute or two, while a base AMI plus a long user data script can take 5 to 10 minutes. Faster boot means faster scaling and less overshoot, so bake your AMI whenever you can.
How Do an ASG and a Load Balancer Work Together?
The load balancer spreads traffic and checks instance health, and the ASG controls how many instances exist and replaces failures. When the ASG launches an instance it registers it with the target group, and traffic starts once the health check passes. When an instance fails the check, traffic stops, the ASG terminates it, and a replacement launches.
RememberEnable the ELB health check type on the ASG. The default EC2 check only confirms the instance is running, not that your app responds, so a crashing app looks healthy. Also set a health check grace period long enough for the instance to boot.
How Does CloudWatch Trigger Auto Scaling?
CloudWatch watches a metric and the ASG acts on it. With simple and step policies you create the alarms yourself, and with target tracking the ASG creates and manages the alarms for you. A scale-out alarm raises desired capacity, and a scale-in alarm lowers it.
Which metric you scale on matters more than the policy type:
| Metric | Best for |
|---|---|
| Average CPU utilization | Compute-bound apps |
| ALB request count per target | Web APIs behind an ALB |
| Queue backlog per instance | Queue workers |
| Custom metric | Business-specific load |
For a web API, keeping request count per target near a chosen value tracks real load better than CPU. For a queue worker, CPU says little. Publish a custom backlog-per-instance metric, calculated as queue depth divided by the number of running instances, and track a target such as 100 messages per worker.
Which Auto Scaling Policy Should You Use?
Start with target tracking, and add the others only for specific needs. Target tracking holds a metric near a value you pick, much like a thermostat. Step scaling gives different responses to different alarm severities. Scheduled scaling changes capacity at known times, and predictive scaling forecasts load from history and adds capacity ahead of it.
| Policy | Use it when |
|---|---|
| Target tracking | You want a metric held near a target |
| Step scaling | Mild and severe spikes need different responses |
| Scheduled | Traffic follows a known clock, like a market open |
| Predictive | Daily or weekly patterns repeat |
- Target tracking example: keep average CPU at 50 percent
- Step scaling example: CPU 50 to 70 percent adds 1 instance, 70 to 90 percent adds 3, above 90 percent adds 5
- Scheduled example: raise desired capacity before a weekday 9:15 AM market open and lower it after close
- Predictive: learns from up to 14 days of history to forecast load and launch instances ahead of the surge, and works best with regular patterns
TipRun predictive scaling in forecast-only mode first to compare its forecast with real traffic before letting it act.
What Are Cooldown and Instance Warmup?
Both stop the ASG from launching more instances before the first batch has started helping. Simple scaling policies use a cooldown, which defaults to 300 seconds, during which further scaling is blocked. Target tracking and step scaling use instance warmup instead, which tells the ASG how long a new instance takes to start contributing to metrics so that it does not count half-ready instances.
- Without these controls, the ASG keeps adding instances while earlier ones are still booting
- Set warmup to match your real boot time, and shorten boot time with a custom AMI
What Are ASG Lifecycle Hooks?
A lifecycle hook pauses an instance in a wait state so your code can run before the instance joins the fleet or before it is terminated. On launch the instance waits in Pending:Wait while you pull secrets, register with service discovery or warm a cache. Then you signal completion and the instance moves to InService, so the load balancer sends no traffic until initialisation is done. Hooks have a timeout, so send the completion or heartbeat signal in time.
How Does an ASG Choose Which Instance to Terminate?
On scale-in the ASG first balances across Availability Zones by picking from the AZ with the most instances. Within that zone the default policy favours instances using the oldest launch template or configuration, then breaks any remaining ties on other criteria. You can switch to OldestInstance, NewestInstance or another policy, and you can protect specific instances from scale-in.
How Does Instance Refresh Roll Out a New Launch Template?
Instance Refresh replaces instances in batches while keeping a minimum percentage of the fleet healthy, so you can ship a new AMI with no downtime. Updating a Launch Template does not change running instances, and only newly launched ones use the new version. Start a refresh with a minimum healthy percentage such as 90 percent and the ASG replaces instances gradually, waiting for health checks as it goes.
TipHave the ASG use the latest or default template version, then run an Instance Refresh after each template change.
Detailed Step-by-Step Practical Lab
This lab uses Amazon Linux 2023 in ap-south-1. Amazon Linux 2 is end of life, so do not use it for new work.
Step 1: Create a target group and load balancer
In EC2, create a target group named devops-web-tg with target type Instances, protocol HTTP and port 80, and a health check path of /. Then create an internet-facing Application Load Balancer named devops-web-alb across two public subnets in different AZs, with a listener on port 80 forwarding to devops-web-tg.
Step 2: Create the Launch Template
In EC2, create a Launch Template named devops-web-lt with Amazon Linux 2023, instance type t3.micro, your web security group (allowing port 80 from the load balancer), and this user data:
dnf install -y nginx stress-ngecho "<h1>Server: $(hostname -f)</h1>" > /usr/share/nginx/html/index.htmlsystemctl enable --now nginxStep 3: Create the Auto Scaling Group
Create an ASG named devops-web-asg using devops-web-lt, in subnets from 2 different AZs. Attach it to devops-web-tg, and turn on ELB health checks with a grace period of 120 seconds. Set capacity to minimum 2, desired 2 and maximum 5.
Step 4: Add a target tracking policy
In the ASG, add a Target tracking scaling policy on Average CPU utilization with a target value of 50 and an instance warmup of 120 seconds. The ASG creates the CloudWatch alarms itself.
Step 5: Verify the fleet
aws autoscaling describe-auto-scaling-groups \ --auto-scaling-group-names devops-web-asg \ --region ap-south-1 \ --query 'AutoScalingGroups[0].Instances[].[InstanceId,LifecycleState,HealthStatus]' \ --output tableBoth instances should show InService and Healthy. Open the load balancer DNS name in a browser and refresh to see the server name change.
Step 6: Test self-healing
aws autoscaling terminate-instance-in-auto-scaling-group \ --instance-id i-0abc123def4567890 \ --no-should-decrement-desired-capacity \ --region ap-south-1 # Watch the replacement launchaws autoscaling describe-scaling-activities \ --auto-scaling-group-name devops-web-asg \ --region ap-south-1 --max-items 5Within a few minutes a replacement instance launches, registers with the target group and passes its health check.
Step 7: Generate CPU load and watch scale-out
Connect to one instance with Session Manager or SSH and run a CPU stress test.
stress-ng --cpu 2 --timeout 600sAfter a few minutes, average CPU passes 50 percent and the policy raises desired capacity. Watch Activity history and the Monitoring tab. When the test ends, CPU falls and the group scales back in more slowly than it scaled out.
Step 8: Clean up
aws autoscaling delete-auto-scaling-group \ --auto-scaling-group-name devops-web-asg \ --force-delete --region ap-south-1Then delete the Launch Template, the load balancer and the target group.
Production Best Practices & Common Pitfalls
- Minimum of 2 across 2 AZs: One instance in one AZ is a single point of failure.
- Use ELB health checks: EC2 checks miss application failures.
- Bake your AMI: Boot in about a minute and scale precisely.
- Start with target tracking: Add scheduled or predictive scaling only for known patterns.
- Scale on a meaningful metric: Requests per target for web, backlog per instance for queues.
- Set a maximum your budget can afford: It is the cap on cost during a spike or a runaway scaling bug.
- Use Launch Templates with versions: Run Instance Refresh after every change.
- Consider mixed instances and Spot: Mixed instance types and Spot capacity can lower cost for fault-tolerant workloads.
Common MistakeSetting minimum to 1 and keeping the group in one AZ. A single AZ event takes the whole app down until the ASG replaces the instance.
Common MistakeLeaving the default EC2 health check on an application fleet. An instance can run while the app returns errors on every request, and the ASG never replaces it.
Common MistakeForgetting to update running instances after a Launch Template change. Without an Instance Refresh, old instances run the old version indefinitely.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Describe groups | aws autoscaling describe-auto-scaling-groups |
| Recent activity | aws autoscaling describe-scaling-activities --auto-scaling-group-name <name> |
| Change capacity | aws autoscaling set-desired-capacity --auto-scaling-group-name <name> --desired-capacity 4 |
| Start refresh | aws autoscaling start-instance-refresh --auto-scaling-group-name <name> |
| List policies | aws autoscaling describe-policies --auto-scaling-group-name <name> |
| Protect an instance | aws autoscaling set-instance-protection --auto-scaling-group-name <name> --instance-ids <id> --protected-from-scale-in |
| Problem | Likely cause and fix |
|---|---|
| Instances keep being replaced | Grace period too short or app failing health checks. Lengthen it and check logs. |
| Does not scale out | Already at maximum, or metric not reaching the target. Check limits and metrics. |
| Scales out too far | Warmup shorter than boot time. Match warmup to real boot time. |
| New instances never healthy | Security group blocks the load balancer or wrong health check path. |
| Old version still running | No Instance Refresh after template update. Start one. |
| Launch fails | Instance type capacity or quota problem. Add types or request a quota increase. |