SkillSprout
Chapter 4 · Lesson 1
Advanced
7 min read

Auto Scaling and High Availability Patterns

Overview

Amazon EC2 Auto Scaling keeps a fleet at the right size and replaces unhealthy instances automatically. An Auto Scaling group (ASG) spans multiple Availability Zones, uses a launch template to know what to launch, and scales between a minimum and maximum capacity based on policies.

Think of an ASG as a restaurant manager who keeps the right number of staff on shift: calling in extra waiters at lunch rush, sending people home when it is quiet, and instantly replacing anyone who falls sick. Multi-AZ placement is like spreading staff across several buildings so one power cut does not close the business.

For DOP-C02 the details matter: how health checks work, scaling policy types, lifecycle hooks for custom actions, instance refresh for rolling AMI updates, warm pools for fast scale-out, and how deployments and ASGs interact.

Key Concepts

  • An ASG spans at least two AZs for high availability and rebalances instances to keep AZs even.
  • Health checks: EC2 (default), ELB (recommended behind a load balancer) and custom; a health check grace period gives new instances time to start.
  • Scaling policies: target tracking (simplest), step, simple, scheduled and predictive scaling (ML based on history).
  • Lifecycle hooks pause instances in Pending:Wait or Terminating:Wait so you can run scripts, register or drain, with heartbeat timeouts.
  • Instance refresh replaces instances in a rolling manner with MinHealthyPercentage and optional checkpoints, auto rollback and skip matching.
  • Warm pools keep pre-initialised stopped or running instances to cut scale-out latency for slow-to-boot apps.
  • Mixed instances policy combines On-Demand and Spot across several instance types with allocation strategies like price-capacity-optimized.
  • Scale-in protection, termination policies and cooldowns / instance warm-up control which instances are removed and how quickly metrics settle.

Detailed Notes

Launch templates and ASG definition

yaml
WebASG:
  Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    MinSize: "2"
    MaxSize: "12"
    DesiredCapacity: "4"
    VPCZoneIdentifier: [!Ref PrivA, !Ref PrivB, !Ref PrivC]
    HealthCheckType: ELB
    HealthCheckGracePeriod: 180
    TargetGroupARNs: [!Ref WebTargetGroup]
    MixedInstancesPolicy:
      InstancesDistribution:
        OnDemandBaseCapacity: 2
        OnDemandPercentageAboveBaseCapacity: 25
        SpotAllocationStrategy: price-capacity-optimized
      LaunchTemplate:
        LaunchTemplateSpecification:
          LaunchTemplateId: !Ref WebLaunchTemplate
          Version: !GetAtt WebLaunchTemplate.LatestVersionNumber
        Overrides:
          - InstanceType: m6i.large
          - InstanceType: m6a.large
          - InstanceType: m7g.large

Scaling policy types

PolicyHow it worksUse
Target trackingMaintain a metric target (e.g. 50% CPU, RequestCountPerTarget)Default choice
Step scalingDifferent adjustments for alarm breach sizesLarge traffic swings
Simple scalingOne adjustment then cooldownLegacy
ScheduledChange capacity at set timesKnown patterns
PredictiveForecasts load from 14 days of history; can pre-scaleCyclical traffic

Scale on business or queue metrics for workers: publish a custom metric such as messages visible per instance, or use SQS backlog per instance with target tracking.

Health checks and replacement

With HealthCheckType: ELB, an instance that fails load balancer health checks is marked unhealthy and replaced; EC2 checks alone only detect hardware or hypervisor failure. Set a grace period longer than boot and bootstrap time to avoid replacement loops. Use aws autoscaling set-instance-health --health-status Unhealthy from automation to trigger replacement.

Lifecycle hooks

bash
aws autoscaling put-lifecycle-hook --auto-scaling-group-name web \
  --lifecycle-hook-name drain-and-backup \
  --lifecycle-transition autoscaling:EC2_INSTANCE_TERMINATING \
  --heartbeat-timeout 300 --default-result CONTINUE \
  --notification-target-arn $TOPIC_ARN --role-arn $ROLE_ARN
aws autoscaling complete-lifecycle-action --lifecycle-hook-name drain-and-backup \
  --auto-scaling-group-name web --lifecycle-action-result CONTINUE --instance-id i-0abc123

Common uses: upload logs before termination, deregister from service discovery, run an SSM Automation, and wait for CodeDeploy on launch. Hook events go to EventBridge, SQS or SNS. Heartbeat can be extended up to 48 hours or 100 times the timeout.

Instance refresh

bash
aws autoscaling start-instance-refresh --auto-scaling-group-name web \
  --preferences '{"MinHealthyPercentage":90,"InstanceWarmup":120,"CheckpointPercentages":[20,50],"CheckpointDelay":300,"AutoRollback":true}'

This rolls the fleet onto a new launch template version or AMI. Checkpoints pause after a portion to let you validate; AutoRollback reverts on failure or alarm. Pair it with a pipeline: bake an AMI with EC2 Image Builder, update the launch template, start the refresh.

Warm pools

A warm pool holds instances in Stopped, Running or Hibernated state after bootstrap. On scale-out, instances move from the pool to the group in seconds, with you paying only for storage if stopped. Combine with lifecycle hooks to finish initialisation.

Multi-AZ and capacity considerations

  • Use subnets in three AZs where possible so losing one AZ keeps 67% capacity.
  • Size for N+1 AZ failure: if two AZs remain, each must absorb extra load or scaling must keep up.
  • Enable capacity rebalancing for Spot to launch replacements when an interruption notice arrives.
  • Use AZ rebalancing and Zonal shift / ARC zonal autoshift to move traffic from an impaired AZ.

Immutable infrastructure

Do not patch in place; bake a new AMI or container image, update the launch template and replace instances. Store the AMI ID in an SSM parameter and reference it with resolve:ssm so templates always get the latest approved image.

Monitoring

Group metrics (GroupInServiceInstances, GroupDesiredCapacity), warm pool metrics and activity history reveal scaling issues. Common failure: instances launch and terminate repeatedly because of a failing health check, a bad launch template (missing role or AMI), or subnets lacking capacity; ASG activity history shows the error.

Scaling policy choices and rollout controls

PolicyBehaviourBest for
Target trackingHolds a metric (CPU, ALB RequestCountPerTarget) near a targetMost steady workloads
Step scalingAdds or removes capacity by alarm breach sizeSpiky load with custom alarms
ScheduledChanges capacity at known timesPredictable peaks
PredictiveForecasts from 14 days of historyCyclical traffic, long warm-up
  • Instance refresh replaces instances after a launch template change with MinHealthyPercentage, InstanceWarmup, checkpoints and automatic rollback on alarms.
  • Lifecycle hooks pause launch or termination so you can run bootstrap or drain tasks, with a heartbeat timeout and a default result of CONTINUE or ABANDON.
  • Warm pools keep pre-initialised stopped instances to shorten scale-out time.
  • Mixed instances policies combine On-Demand base capacity with Spot and several instance types, using capacity-optimised allocation to lower interruption risk.
  • Set ELB health checks on the group so unhealthy targets are replaced, and use a health check grace period that exceeds bootstrap time to prevent launch loops.

Real World Example

Scenario: a ticketing site faces sudden demand. The web tier uses an ASG across three AZs with target tracking on ALB RequestCountPerTarget, scheduled actions before known on-sales and predictive scaling for daily cycles. A warm pool of pre-initialised instances cuts scale-out from four minutes to forty seconds.

Weekly AMIs are built with Image Builder; the pipeline starts an instance refresh with checkpoints at 20% and automatic rollback if the 5XX alarm fires. A termination lifecycle hook flushes in-memory carts to DynamoDB before an instance exits.

Architecture Diagram

Multi-AZ Auto Scaling group with lifecycle hook
Architecture
AWS Cloud
Users
VPC
ALBhealth checks

Auto Scaling group

InstanceAZ a
InstanceAZ b
InstanceAZ c
EventBridge
Hook handler

Instances spread across AZs; hooks and health checks manage lifecycle.

  1. 1A scaling policy raises desired capacity when a metric breaches its target.
  2. 2New instances launch across AZs from the launch template and enter Pending:Wait if a hook exists.
  3. 3A handler completes initialisation and the instance enters service behind the ALB.
  4. 4ELB health checks replace failing instances automatically.
  5. 5On scale-in a terminating hook drains and flushes data before the instance is removed.

Best Practices

  • ✓Use ELB health checks and a grace period longer than bootstrap time.
  • ✓Prefer target tracking; add predictive and scheduled scaling for known patterns.
  • ✓Spread across three AZs and size capacity for the loss of one.
  • ✓Bake immutable AMIs and roll out with instance refresh plus checkpoints and rollback.
  • ✓Use warm pools and lifecycle hooks for slow-starting applications.

Common Interview Questions

Exam Tips

DOP-C02 focus

  • ASG behind ALB must use ELB health checks to replace instances failing the application check.
  • "Run custom action at launch/terminate" = lifecycle hooks.
  • "Roll out a new AMI with minimal effort" = instance refresh.
  • "Predictable daily spikes" = scheduled or predictive scaling.

Finished this lesson?

0 of 44 lessons done · 0% of the course