Lesson 2 of 2 Elastic Load Balancing and Auto Scaling

Matching Capacity to Demand with EC2 Auto Scaling

This lesson explains how EC2 Auto Scaling keeps the right number of instances running, replacing unhealthy ones and adjusting capacity to demand.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe how launch templates, capacity limits and scaling policies control an Auto Scaling group.
  • Explain how health check types and the health check grace period decide when instances are replaced.
  • Describe how a new launch template version is rolled out to existing instances.

Auto Scaling groups and policies

An Auto Scaling group launches instances from a launch template and keeps capacity between a minimum and a maximum. Its desired capacity is the number of instances it maintains at any moment, and scaling policies change that number within the range.

A target tracking policy works like a thermostat: you choose a metric and a target value, such as average CPU at 50%, and Auto Scaling creates the CloudWatch alarms and adds or removes instances to keep the metric near the target. It suits most workloads and needs the least tuning. A step scaling policy is driven by alarms that you create, and adds or removes different numbers of instances depending on how far the metric has moved past the threshold, for example two instances above 70% CPU and four above 90%. It gives finer control when the response must vary with the size of the breach.

Scheduled actions change the minimum, maximum or desired capacity at set times, which suits predictable patterns, such as adding capacity before business hours. Predictive scaling goes further by forecasting load from past traffic and launching instances in advance. The following table summarises the main policy types.

PolicyHow it worksUse for
Target trackingHolds a metric, such as average CPU or ALB requests per target, at a chosen valueMost workloads
StepAdds or removes capacity at alarm thresholdsFine-grained control
ScheduledChanges capacity at set timesPredictable patterns

Example. Keep average CPU near 50%. Auto Scaling creates and manages the alarms itself. For a web tier, ALBRequestCountPerTarget often tracks load more closely than CPU.

aws autoscaling put-scaling-policy --auto-scaling-group-name orders-asg \
  --policy-name cpu50 --policy-type TargetTrackingScaling \
  --target-tracking-configuration '{
    "PredefinedMetricSpecification": {"PredefinedMetricType": "ASGAverageCPUUtilization"},
    "TargetValue": 50.0
  }'

Health and lifecycle

An Auto Scaling group replaces instances that it considers unhealthy. By default, it uses only EC2 status checks, which detect hardware and operating system failures but not an application that has stopped responding. Turning on ELB health checks for the group makes it also replace any instance that the load balancer marks unhealthy, for example because the application returns errors on its health check path.

A new instance needs time to boot and start the application, and during that time it fails health checks. The health check grace period tells Auto Scaling to ignore health check results for a set number of seconds after launch. If it is shorter than the start-up time, new instances are terminated as unhealthy before they are ready, and the group launches and terminates instances in an endless cycle.

Lifecycle hooks pause an instance as it launches or terminates, so that custom actions can run. A launch hook can wait while a script installs software or registers the instance with another system; a termination hook can wait while logs or data are copied off the instance. The instance continues when the action calls complete-lifecycle-action or the hook's timeout expires. Because Auto Scaling adds and removes instances at any time, applications on them must be stateless, keeping sessions and data in services such as ElastiCache, DynamoDB or Amazon S3.

Rolling out a new version

Instances in an Auto Scaling group are launched from a launch template, so a new application version or operating system image is released by creating a new version of the template. Existing instances keep running the old version until they are replaced. An instance refresh replaces them gradually: it terminates and relaunches instances in batches while keeping a minimum healthy percentage of capacity in service, and it can pause at checkpoints and roll back automatically if CloudWatch alarms fire.

Alternatively, AWS CodeDeploy can deploy application code to the instances of an Auto Scaling group, either in place or with a blue/green deployment that creates a new group and moves the load balancer to it. CodeDeploy is the better choice when only the application changes and lifecycle hooks are needed to validate the release; an instance refresh suits changes to the image or launch template itself.

Scenario questions

Run an Auto Scaling group

Exam skills 4.3.1 · 4.2.5

Practise health checks, lifecycle hooks and rollouts for Auto Scaling groups.

Log in to try this activity Interactive activities are free with an account.
Worked example

Instances terminated before they finish starting

An application takes four minutes to start. After a scale-out, new instances are marked unhealthy and terminated in a loop, so capacity never grows.

CauseFix
The health check grace period is 60 secondsRaise it above the start-up time, for example 300 seconds
The scaling policy reacts to the new instances' lack of metricsSet default instance warm-up so they are not counted until ready
Start-up work runs at launchBake software into the AMI to start faster

With a longer grace period and warm-up, new instances join the load balancer only once healthy, and the target tracking policy holds CPU at its target.

Check yourself

Which scaling policy keeps average CPU utilisation near 50% without defining step adjustments?

Show answer

A target tracking policy. It adds or removes instances to keep the metric at the target value.

Exam Tips

Remember for the exam

  • To keep average CPU at 50%, use a target tracking scaling policy.
  • If new instances are terminated before they finish booting, increase the health check grace period.
  • To copy logs off an instance before it terminates, use a termination lifecycle hook.
  • To replace all instances gradually with a new AMI, run an instance refresh.