
Self-Healing Web Tier with ALB and Auto Scaling Groups
Build a multi-AZ web tier with an ALB and Auto Scaling group, enable ELB health checks, tune the grace period, then break it to watch it heal itself.
A web server can be running, pass every EC2 status check, and still serve nothing but 500 errors. If your Auto Scaling group only listens to EC2, it will keep that broken instance in service, and your users will keep hitting it. The fix is a small configuration change that most default setups skip: turning on Elastic Load Balancing (ELB) health checks and sizing the health check grace period correctly.
In this post we build a multi-AZ web tier with an Application Load Balancer (ALB) and an Auto Scaling group (ASG), then break it on purpose to watch it heal itself.
Why EC2 Health Checks Are Not Enough
By default, Amazon EC2 Auto Scaling only replaces an instance when EC2 reports it as unhealthy or unreachable. That covers hardware failures and stopped instances, but it says nothing about your application. A crashed web process, a full disk that breaks your app, or a bad deploy all leave the instance in the
running state.When you turn on ELB health checks, the ASG also replaces any instance that an attached load balancer reports as unhealthy. The load balancer probes your application over HTTP, so it detects failures that EC2 cannot see.
That raises a new question: how long should the ASG wait before it trusts those probes on a brand new instance? That is the job of the grace period, and we cover it after the architecture.
The Architecture
The ALB spreads traffic across targets in two Availability Zones (AZs). The ASG launches instances into subnets in those same AZs and registers them with an ALB target group. Two signals feed back into the ASG: EC2 status checks and ELB health checks.
The ASG keeps the instance count at the desired capacity and spreads it across AZs. If an AZ becomes impaired, the ASG launches replacements in the healthy one.
Build It
You need the AWS CLI v2 and permissions to create networking, IAM, EC2, and load balancer resources. Instead of relying on the default VPC, we create a dedicated VPC with two public subnets in different AZs, so the lab is self-contained and easy to remove. The variables set here are reused in every later command, including cleanup.
# Pick the first two AZs in the current RegionAZ_A=$(aws ec2 describe-availability-zones --query 'AvailabilityZones[0].ZoneName' --output text)AZ_B=$(aws ec2 describe-availability-zones --query 'AvailabilityZones[1].ZoneName' --output text)
# Dedicated VPC (DNS resolution through the Amazon DNS server is on by default)VPC_ID=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 \ --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=web-tier-vpc}]' \ --query Vpc.VpcId --output text)
# One public subnet per AZ; create-subnet has no flag for public IPs, so we enable# auto-assign afterward. Instances need one to reach the internet and SSM.SUBNET_A=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.1.0/24 \ --availability-zone $AZ_A --query Subnet.SubnetId --output text)SUBNET_B=$(aws ec2 create-subnet --vpc-id $VPC_ID --cidr-block 10.0.2.0/24 \ --availability-zone $AZ_B --query Subnet.SubnetId --output text)aws ec2 modify-subnet-attribute --subnet-id $SUBNET_A --map-public-ip-on-launchaws ec2 modify-subnet-attribute --subnet-id $SUBNET_B --map-public-ip-on-launch
# Internet gateway attached to the VPCIGW_ID=$(aws ec2 create-internet-gateway --query InternetGateway.InternetGatewayId --output text)aws ec2 attach-internet-gateway --internet-gateway-id $IGW_ID --vpc-id $VPC_ID
# Route table that sends internet-bound traffic to the gateway, associated with both subnetsRT_ID=$(aws ec2 create-route-table --vpc-id $VPC_ID \ --query RouteTable.RouteTableId --output text)aws ec2 create-route --route-table-id $RT_ID \ --destination-cidr-block 0.0.0.0/0 --gateway-id $IGW_IDaws ec2 associate-route-table --route-table-id $RT_ID --subnet-id $SUBNET_Aaws ec2 associate-route-table --route-table-id $RT_ID --subnet-id $SUBNET_BNext we create two security groups. The ALB accepts HTTP from anywhere, and the instances accept HTTP only from the ALB's security group. Because our instances have public IPs, this matters: nobody can reach them directly, and the ALB remains the only way in.
# Security group for the ALB: HTTP from anywhereALB_SG_ID=$(aws ec2 create-security-group --group-name web-tier-alb-sg \ --description "Web tier ALB" --vpc-id $VPC_ID --query GroupId --output text)aws ec2 authorize-security-group-ingress --group-id $ALB_SG_ID \ --protocol tcp --port 80 --cidr 0.0.0.0/0
# Security group for the instances: HTTP only from the ALB's security groupWEB_SG_ID=$(aws ec2 create-security-group --group-name web-tier-instance-sg \ --description "Web tier instances" --vpc-id $VPC_ID --query GroupId --output text)aws ec2 authorize-security-group-ingress --group-id $WEB_SG_ID \ --protocol tcp --port 80 --source-group $ALB_SG_IDThe instances also need an IAM role so we can run commands on them later through Systems Manager (SSM). The role trusts EC2, carries the
AmazonSSMManagedInstanceCore managed policy, and is exposed to instances through an instance profile.# Role EC2 can assume, with SSM access so we can run commands on instances lateraws iam create-role --role-name web-tier-role --assume-role-policy-document '{ "Version":"2012-10-17", "Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}'aws iam attach-role-policy --role-name web-tier-role \ --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
# Instance profile that carries the role to the instancesaws iam create-instance-profile --instance-profile-name web-tier-profileaws iam add-role-to-instance-profile --instance-profile-name web-tier-profile \ --role-name web-tier-roleThe launch template defines what each instance looks like. The user data installs Apache and writes a page that shows the instance ID, which lets us see the load balancer rotate between instances. It also creates a
/health page that we can later delete to simulate an application failure.# User data: install Apache, serve the instance ID, and expose /healthcat > userdata.sh <<'EOF'#!/bin/bashdnf install -y httpdTOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \ -H "X-aws-ec2-metadata-token-ttl-seconds: 60")ID=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \ http://169.254.169.254/latest/meta-data/instance-id)echo "Hello from $ID" > /var/www/html/index.htmlecho "ok" > /var/www/html/healthsystemctl enable --now httpdEOF
AMI_ID=$(aws ssm get-parameter \ --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 \ --query Parameter.Value --output text)
# Launch template referencing the AMI, security group, and base64 user dataaws ec2 create-launch-template --launch-template-name web-tier-lt \ --launch-template-data "{ \"ImageId\": \"$AMI_ID\", \"InstanceType\": \"t3.micro\", \"SecurityGroupIds\": [\"$WEB_SG_ID\"], \"IamInstanceProfile\": {\"Name\": \"web-tier-profile\"}, \"UserData\": \"$(base64 -w0 userdata.sh)\" }"Now the load balancer pieces. The target group health check points at
/health , which is the endpoint the ALB will probe. The listener forwards all HTTP traffic to the target group.# Target group whose health check probes /health every 15 secondsTG_ARN=$(aws elbv2 create-target-group --name web-tier-tg --protocol HTTP --port 80 \ --vpc-id $VPC_ID --health-check-path /health \ --health-check-interval-seconds 15 \ --healthy-threshold-count 2 --unhealthy-threshold-count 2 \ --query 'TargetGroups[0].TargetGroupArn' --output text)
# Internet-facing ALB across both subnetsALB_ARN=$(aws elbv2 create-load-balancer --name web-tier-alb \ --subnets $SUBNET_A $SUBNET_B --security-groups $ALB_SG_ID \ --query 'LoadBalancers[0].LoadBalancerArn' --output text)
# Listener forwards port 80 traffic to the target groupaws elbv2 create-listener --load-balancer-arn $ALB_ARN --protocol HTTP --port 80 \ --default-actions Type=forward,TargetGroupArn=$TG_ARNThe ASG is where the self-healing behavior is configured. Two flags matter:
--health-check-type ELB makes the ASG act on load balancer health, and --health-check-grace-period 120 gives new instances two minutes to boot before their ELB status counts. Because the CLI defaults the grace period to 0 seconds, you must set it explicitly.# ASG across both AZs, attached to the target groupaws autoscaling create-auto-scaling-group \ --auto-scaling-group-name web-tier-asg \ --launch-template LaunchTemplateName=web-tier-lt,Version='$Latest' \ --min-size 2 --max-size 4 --desired-capacity 2 \ --vpc-zone-identifier "$SUBNET_A,$SUBNET_B" \ --target-group-arns $TG_ARN \ --health-check-type ELB \ --health-check-grace-period 120 # Time for Apache to install before ELB status countsAfter a couple of minutes,
curl the ALB DNS name repeatedly and you should see responses from two different instance IDs.ALB_DNS=$(aws elbv2 describe-load-balancers --load-balancer-arns $ALB_ARN \ --query 'LoadBalancers[0].DNSName' --output text)curl -s http://$ALB_DNS/
## expect a different instance id in response each time## i.e. Hello from i-abcdefg123456With the tier running, we can test the part that matters: what happens when something breaks.
Break It and Watch It Heal
We simulate an application failure by removing the
/health page on one instance. EC2 still sees a perfectly healthy machine, but the ALB now gets a 404 from the health check. This command uses SSM Run Command, which works because of the instance profile we attached.# Pick one instance in the ASGINSTANCE_ID=$(aws autoscaling describe-auto-scaling-groups \ --auto-scaling-group-names web-tier-asg \ --query 'AutoScalingGroups[0].Instances[0].InstanceId' --output text)
# Delete the health page so the ALB sees failures while EC2 sees a healthy hostaws ssm send-command --instance-ids $INSTANCE_ID \ --document-name AWS-RunShellScript \ --parameters 'commands=["rm -f /var/www/html/health"]'Within about a minute the target becomes
unhealthy , and the ASG then terminates it and launches a replacement. You can follow along with these two commands.# Target health as the ALB sees itaws elbv2 describe-target-health --target-group-arn $TG_ARN
# ASG activity history shows the termination and replacement with the reasonaws autoscaling describe-scaling-activities --auto-scaling-group-name web-tier-asg \ --max-items 3Self-healing only works if new instances get a fair chance to start, which brings us to the grace period.
Set the Grace Period to Match Your Boot Time
The grace period is the minimum time the ASG keeps a new instance in service before it can terminate it for failing health checks. ELB health checks begin when the instance registers with the load balancer, so a slow-starting application will fail its first probes. Without a grace period, the ASG would terminate the instance, launch another one, and repeat in a loop that never produces a healthy instance.
- The console default is 300 seconds, while the CLI and SDK default is 0 seconds, which turns the grace period off.
- The grace period applies to newly launched instances, instances returning from standby, and instances you attach manually.
- During the grace period, an instance that leaves the EC2
runningstate is still marked unhealthy and replaced immediately.
- Setting the value too high delays detection of real failures.
A practical way to pick the value is to measure how long your instance takes to pass its first ELB health check, then add a margin. If you use lifecycle hooks to hold instances until they are initialized, you can set the grace period to 0.
Best Practices
- Use
--health-check-type ELBfor any ASG behind a load balancer, since EC2 checks alone cannot see application failures.
- Point the target group health check at an endpoint that verifies real dependencies when it is cheap to do so, and keep it fast.
- Set the grace period from measured boot time. A value that is too short causes replacement loops, and one that is too long hides real failures.
- Also set the default instance warmup , which the documentation strongly recommends, so scaling metrics ignore instances that are still starting.
- Spread the ASG across at least two AZs so a single AZ failure does not remove all capacity.
- Tune the target group thresholds (interval and unhealthy count) to balance detection speed against false positives.
Clean Up
Delete the resources in reverse order to avoid charges. Deleting the ASG with
--force-delete also terminates its instances.aws autoscaling delete-auto-scaling-group --auto-scaling-group-name web-tier-asg --force-deleteaws elbv2 delete-load-balancer --load-balancer-arn $ALB_ARNWait for the ALB to finish deleting before removing the target group. The CLI waiter polls every 15 seconds and returns once the load balancer no longer exists.
aws elbv2 wait load-balancers-deleted --load-balancer-arns $ALB_ARNaws elbv2 delete-target-group --target-group-arn $TG_ARNaws ec2 delete-launch-template --launch-template-name web-tier-ltaws ec2 delete-security-group --group-id $WEB_SG_ID # May need a retry until ENIs are releasedaws ec2 delete-security-group --group-id $ALB_SG_ID # Delete after the instance group, which references itaws iam remove-role-from-instance-profile --instance-profile-name web-tier-profile --role-name web-tier-roleaws iam delete-instance-profile --instance-profile-name web-tier-profileaws iam detach-role-policy --role-name web-tier-role --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCoreaws iam delete-role --role-name web-tier-roleThen remove the network, following the order in the VPC deletion guide . Subnets can only be deleted once the instances and load balancer ENIs are gone, so retry if you see a dependency error.
aws ec2 delete-subnet --subnet-id $SUBNET_A # May need a retry until ENIs are releasedaws ec2 delete-subnet --subnet-id $SUBNET_Baws ec2 delete-route-table --route-table-id $RT_IDaws ec2 detach-internet-gateway --internet-gateway-id $IGW_ID --vpc-id $VPC_IDaws ec2 delete-internet-gateway --internet-gateway-id $IGW_IDaws ec2 delete-vpc --vpc-id $VPC_IDSelf-Healing Comes Down to Two Settings
A multi-AZ ASG behind an ALB only heals application failures when two things are true: the ASG listens to the load balancer through ELB health checks, and the grace period matches how long your instances take to start. With those set, a broken application is removed from rotation by the ALB and replaced by the ASG without anyone being paged.
To see it for yourself, build the lab above, delete the health page on one instance, and read the scaling activity history, which records the reason for the replacement. Then measure your own boot time and set the grace period from that number.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article