Skip to main content

Configuring Auto Scaling Groups for EC2 Fleets

Configure Auto Scaling Groups with Launch Templates, target tracking policies, health checks, and CloudWatch metrics to scale EC2 fleets on demand.

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
Remember

Set 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.

flowchart TD A([Users]) --> B[Application Load Balancer] B --> C[Instance AZ-a] B --> D[Instance AZ-b] E[Auto Scaling Group] -.->|Launches and replaces| C E -.->|Launches and replaces| D B -.->|Health status| E classDef user fill:#8B5CF6,color:#ffffff classDef lb fill:#326CE5,color:#ffffff classDef ec2 fill:#10B981,color:#ffffff classDef asg fill:#F97316,color:#ffffff class A user class B lb class C,D ec2 class E asg
Remember

Enable 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
Tip

Run 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.

Tip

Have 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:

Bash
#!/bin/bash
dnf install -y nginx stress-ng
echo "<h1>Server: $(hostname -f)</h1>" > /usr/share/nginx/html/index.html
systemctl enable --now nginx
Step 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
Bash
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 table

Both 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
Bash
aws autoscaling terminate-instance-in-auto-scaling-group \
--instance-id i-0abc123def4567890 \
--no-should-decrement-desired-capacity \
--region ap-south-1
# Watch the replacement launch
aws autoscaling describe-scaling-activities \
--auto-scaling-group-name devops-web-asg \
--region ap-south-1 --max-items 5

Within 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.

Bash
stress-ng --cpu 2 --timeout 600s

After 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
Bash
aws autoscaling delete-auto-scaling-group \
--auto-scaling-group-name devops-web-asg \
--force-delete --region ap-south-1

Then 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 Mistake

Setting 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 Mistake

Leaving 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 Mistake

Forgetting 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.

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS Compute and Auto Scaling

All 6 Topics

Frequently Asked Questions

Is Configuring Auto Scaling Groups for EC2 Fleets free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring Auto Scaling Groups for EC2 Fleets topic cover?

Configure Auto Scaling Groups with Launch Templates, target tracking policies, health checks, and CloudWatch metrics to scale EC2 fleets on demand.

Found a mistake, an outdated step or a broken link?