EC2 Auto Scaling and Elastic Load Balancing
Overview
An Auto Scaling group (ASG) keeps the right number of EC2 instances running, replacing unhealthy ones and adding or removing capacity as demand changes. An Elastic Load Balancer (ELB) spreads traffic across those instances and stops sending requests to unhealthy ones. Together they are the foundation of a self-healing web tier.
Imagine a supermarket with a manager who opens extra checkout lanes when queues grow (Auto Scaling) and a greeter who directs shoppers to open lanes only (load balancer). If a till breaks, the greeter stops sending people there and the manager replaces it.
As SysOps administrator you are judged on how you configure, tune and troubleshoot this pair: why instances keep being terminated, why scaling is slow, and why a target shows "unhealthy".
Key Concepts
- An ASG uses a launch template (AMI, type, SG, role, user data) and has min / desired / max capacity across multiple AZs.
- Scaling policies: target tracking (preferred), step, simple, scheduled and predictive scaling.
- Health checks: EC2 status by default; enable ELB health checks so the ASG replaces instances failing the load balancer check.
- Cooldowns and instance warm-up stop scaling from over-reacting while new instances boot.
- Lifecycle hooks pause launch/terminate so you can run scripts (e.g. drain, register, backup logs).
- Instance refresh performs rolling replacement when the launch template changes; warm pools pre-initialise instances.
- ALB (Layer 7: path/host routing, WebSockets), NLB (Layer 4: static IP, TLS passthrough, extreme performance), GWLB (appliances).
- Connection draining (deregistration delay, default 300 s) lets in-flight requests finish.
Detailed Notes
Scaling policy types
| Policy | Behaviour | When to use |
|---|---|---|
| Target tracking | Keeps a metric near a target (e.g. CPU 50%) | Default choice |
| Step scaling | Different adjustments for alarm breach size | Fine-grained reaction |
| Scheduled | Change min/max/desired at set times | Known peaks (9 a.m. launch) |
| Predictive | ML forecast of cyclical load | Regular daily/weekly patterns |
aws autoscaling put-scaling-policy --auto-scaling-group-name web-asg \
--policy-name cpu50 --policy-type TargetTrackingScaling \
--target-tracking-configuration '{
"PredefinedMetricSpecification":{"PredefinedMetricType":"ASGAverageCPUUtilization"},
"TargetValue":50.0}'
aws autoscaling put-scheduled-update-group-action --auto-scaling-group-name web-asg \
--scheduled-action-name morning --recurrence "0 8 * * 1-5" --min-size 4 --desired-capacity 6
For ALB-fronted groups, ALBRequestCountPerTarget often reflects load better than CPU.
Health checks and replacement
aws autoscaling update-auto-scaling-group --auto-scaling-group-name web-asg \
--health-check-type ELB --health-check-grace-period 300
The grace period must be longer than boot + app start time, otherwise instances are killed in a loop. To debug a failing instance, put it in Standby or use instance scale-in protection.
Why was my instance terminated? (checks)
aws autoscaling describe-scaling-activities– shows cause (health check, scale-in, AZ rebalance, Spot interruption).- Check termination policy (default: balance AZs, then oldest launch template, then closest to next billing hour).
- Check the target group health and the health check path/port/matcher.
Load balancer comparison
| Feature | ALB | NLB | GWLB |
|---|---|---|---|
| Layer | 7 (HTTP/HTTPS/gRPC) | 4 (TCP/UDP/TLS) | 3 |
| Routing | Host, path, header, query | Port | Transparent to appliances |
| Static IP | No (use Global Accelerator) | Yes (Elastic IP per AZ) | n/a |
| Security groups | Yes | Yes (supported) | No |
| Source IP preserved | Via X-Forwarded-For | Yes (instance targets) | Yes |
Troubleshooting target health
| Status reason | Fix |
|---|---|
Target.FailedHealthChecks | App not returning matcher code (e.g. 200) on the path; check SG allows ALB -> instance port |
Target.Timeout | Security group or NACL blocking; app slow |
Target.NotInUse | Target's AZ not enabled on load balancer |
| 502 Bad Gateway | Target closed connection / invalid response; keep-alive timeout lower than ALB idle timeout |
| 503 | No healthy targets |
| 504 | Target did not respond within idle timeout (default 60 s) |
Enable access logs to S3 and use cross-zone load balancing (on by default for ALB) for even distribution.
Lifecycle hooks
aws autoscaling put-lifecycle-hook --auto-scaling-group-name web-asg \
--lifecycle-hook-name drain --lifecycle-transition autoscaling:EC2_INSTANCE_TERMINATING \
--heartbeat-timeout 300 --default-result CONTINUE
Handle the event with EventBridge -> Lambda/SSM, then call complete-lifecycle-action.
Rolling updates
aws autoscaling start-instance-refresh --auto-scaling-group-name web-asg \
--preferences '{"MinHealthyPercentage":90,"InstanceWarmup":120}'
```### Scaling policy types, lifecycle hooks and warm pools
| Policy | How it works | Best for |
|--------|--------------|----------|
| **Target tracking** | Keeps a metric (CPU, ALBRequestCountPerTarget) near a target | Most workloads; simplest |
| **Step scaling** | Different adjustments per alarm breach size | Spiky load needing proportional response |
| **Scheduled** | Changes capacity at known times | Predictable events |
| **Predictive** | ML forecast of cyclical load, pre-provisions capacity | Daily/weekly patterns |
**Lifecycle hooks** pause an instance in `Pending:Wait` or `Terminating:Wait` so you can run bootstrap or drain tasks (default heartbeat 1 hour). **Warm pools** keep pre-initialized stopped or hibernated instances to cut scale-out time. **Instance refresh** replaces instances after a launch template change while keeping a minimum healthy percentage; **scale-in protection** and **termination policies** control which instance is removed.
```bash
aws autoscaling put-lifecycle-hook --auto-scaling-group-name web-asg --lifecycle-hook-name drain \
--lifecycle-transition autoscaling:EC2_INSTANCE_TERMINATING --heartbeat-timeout 300 --default-result CONTINUE
aws autoscaling complete-lifecycle-action --auto-scaling-group-name web-asg --lifecycle-hook-name drain \
--lifecycle-action-result CONTINUE --instance-id i-0abc123
Cooldowns and instance warm-up prevent flapping: set warm-up to the real application start time so new instances are not counted in metrics too early.
Real World Example
Scenario – a flash-sale site keeps dropping users. During sales, instances launch but ALB returns 502s and the ASG keeps replacing healthy servers. Investigation shows the health-check grace period was 60 seconds, yet the app takes 3 minutes to warm its cache. The ASG judged instances unhealthy and terminated them in a loop.
The fix: grace period of 300 s, target tracking on ALBRequestCountPerTarget, a scheduled action to raise minimum capacity 30 minutes before campaigns, and a warm pool. Instance refresh then rolls out new AMIs with 90% healthy capacity.
Architecture Diagram
- 1The ALB receives traffic and routes to healthy targets in both AZs.
- 2CloudWatch publishes request-count and CPU metrics.
- 3The target tracking policy adds instances when the metric is above target.
- 4ELB health failures cause the ASG to terminate and replace the bad instance.
Best Practices
- ✓Spread ASGs over at least two AZs and enable ELB health checks.
- ✓Set a realistic health check grace period and instance warm-up.
- ✓Prefer target tracking; add scheduled actions for known events.
- ✓Use launch templates (versioned) and instance refresh for rolling AMI updates.
- ✓Enable access logs and alarm on UnHealthyHostCount, HTTPCode_ELB_5XX and TargetResponseTime.
Common Interview Questions
Exam Tips
SOA-C03 focus
- Replace instances failing the load balancer check -> ASG health check type ELB.
- Scheduled predictable peaks -> scheduled scaling; automatic metric-based -> target tracking.
- 502/503/504 questions: 502 bad response, 503 no healthy targets, 504 timeout.
- Run custom actions on launch/terminate -> lifecycle hooks.
Finished this lesson?
0 of 46 lessons done · 0% of the course

