Elastic Load Balancing and Auto Scaling: ALB, NLB, Target Groups, Health Checks and Scaling Policies
Why Load Balancers and Auto Scaling?
One server is a single point of failure and has a fixed size. The usual pattern is: many identical instances in several AZs behind a load balancer, managed by an Auto Scaling group that adds or removes instances as needed.
text
Users ─► Route 53 ─► ALB (public subnets, 2+ AZs)
│ health checks, HTTPS (ACM)
┌──────────┴──────────┐
Target group: web instances in private subnets (AZ-a, AZ-b)
▲
Auto Scaling group: min 2, desired 2, max 10, scales on CPU or requests
Types of Load Balancers
| Type | Layer | Protocols | Best for |
| Application Load Balancer (ALB) | 7 (HTTP/HTTPS) | HTTP, HTTPS, gRPC, WebSocket | Web apps, microservices, path/host routing, Lambda targets, containers. Works with WAF, Cognito auth |
| Network Load Balancer (NLB) | 4 (TCP/UDP/TLS) | TCP, UDP, TLS | Extreme performance, millions of requests per second, static IP per AZ / Elastic IP, PrivateLink |
| Gateway Load Balancer (GWLB) | 3 | GENEVE (port 6081) | Insert third-party firewalls, IDS/IPS appliances |
| Classic Load Balancer (CLB) | 4 and 7 | Legacy | Old EC2-Classic style apps. Do not use for new designs |
Quick decision: HTTP routing or microservices → ALB. Static IPs, UDP or very high throughput → NLB. Network appliances → GWLB.
ALB Concepts
| Concept | Meaning |
| Listener | A port and protocol the ALB listens on (for example HTTPS 443) |
| Rule | If condition then action. Conditions: host header, path, HTTP header, query string, source IP. Actions: forward, redirect, fixed response, authenticate |
| Target group | A set of targets: instances, IP addresses, Lambda functions or other ALBs |
| Health check | Path, port, interval, thresholds. Unhealthy targets receive no traffic |
| Deregistration delay | Time to finish in-flight requests before removing a target (default 300 s) |
| Sticky sessions | Send a client to the same target using a cookie (duration-based or application-based) |
| Slow start | Gradually send traffic to a new target |
bash
# Create target group, ALB, and listener with CLI
TG=$(aws elbv2 create-target-group --name web-tg --protocol HTTP --port 80 --vpc-id vpc-0abc \
--health-check-path /health --health-check-interval-seconds 15 --healthy-threshold-count 2 \
--query 'TargetGroups[0].TargetGroupArn' --output text)
ALB=$(aws elbv2 create-load-balancer --name web-alb --subnets subnet-a subnet-b --security-groups sg-alb \
--query 'LoadBalancers[0].LoadBalancerArn' --output text)
aws elbv2 create-listener --load-balancer-arn $ALB --protocol HTTPS --port 443 \
--certificates CertificateArn=arn:aws:acm:ap-south-1:123456789012:certificate/abcd \
--ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06 \
--default-actions Type=forward,TargetGroupArn=$TG
# Redirect HTTP to HTTPS
aws elbv2 create-listener --load-balancer-arn $ALB --protocol HTTP --port 80 \
--default-actions 'Type=redirect,RedirectConfig={Protocol=HTTPS,Port=443,StatusCode=HTTP_301}'
bash
# Path based routing: /api/* goes to another target group
aws elbv2 create-rule --listener-arn $LISTENER --priority 10 \
--conditions Field=path-pattern,Values='/api/*' \
--actions Type=forward,TargetGroupArn=$API_TG
Load Balancer Details to Remember
- ALB has DNS name only (IPs change). NLB can have a static or Elastic IP per AZ
- Cross-zone load balancing: on by default for ALB (no charge for inter-AZ data), off by default for NLB (inter-AZ charges if enabled)
- The ALB sees the client IP in the **
X-Forwarded-For** header. NLB preserves the client IP
- Connection draining = deregistration delay
- Security group chain: internet → ALB SG (80/443 from anywhere) → instance SG (allow only from the ALB SG)
- Put the load balancer in public subnets (or internal in private subnets), and instances in private subnets
- Use access logs to S3 and CloudWatch metrics (
RequestCount, TargetResponseTime, HTTPCode_ELB_5XX_Count, UnHealthyHostCount)
Auto Scaling Groups (ASG)
An ASG keeps the right number of instances: it replaces unhealthy ones and scales in or out. It spreads instances across the subnets (AZs) you choose.
| Setting | Meaning |
| Minimum | Never fewer than this (for high availability use at least 2, in 2 AZs) |
| Desired | The number it tries to keep now |
| Maximum | Cost limit and safety limit |
| Launch template | What to launch: AMI, instance type, security groups, role, user data. Versioned. Replaces old launch configurations |
| Health check type | EC2 (instance status) or ELB (use load balancer health). Use ELB with a load balancer |
| Health check grace period | Time after launch before checks begin |
| Cooldown / warm-up | Avoid scaling again too fast |
bash
aws ec2 create-launch-template --launch-template-name web-lt --launch-template-data '{
"ImageId":"ami-0123","InstanceType":"t3.small","SecurityGroupIds":["sg-web"],
"IamInstanceProfile":{"Name":"AppS3Read"},"MetadataOptions":{"HttpTokens":"required"},
"UserData":"'$(base64 -w0 user-data.sh)'"}'
aws autoscaling create-auto-scaling-group --auto-scaling-group-name web-asg \
--launch-template LaunchTemplateName=web-lt,Version='$Latest' \
--min-size 2 --desired-capacity 2 --max-size 10 \
--vpc-zone-identifier "subnet-priv-a,subnet-priv-b" \
--target-group-arns $TG --health-check-type ELB --health-check-grace-period 120
Scaling Policies
| Policy | How it works | Example |
| Target tracking (recommended) | Keep a metric near a target, like a thermostat | Keep average CPU at 50 percent, or ALBRequestCountPerTarget at 1000 |
| Step scaling | Different actions for different alarm sizes | CPU over 60 add 1, over 80 add 3 |
| Simple scaling | One action per alarm with a cooldown | Older style |
| Scheduled scaling | Change capacity at set times | Scale out every weekday at 8:45 |
| Predictive scaling | Uses machine learning on past load to scale ahead | Regular daily patterns |
bash
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 "45 8 * * 1-5" --min-size 4 --desired-capacity 4
Scale on the right metric: CPU is simple. For web apps, requests per target is often better. For queue workers, scale on SQS queue depth per instance.
More ASG Features
- Mixed instances policy: On-Demand base plus Spot, many instance types
- Lifecycle hooks: pause an instance while launching or terminating to run setup or drain tasks
- Instance refresh: roll out a new AMI/launch template version gradually with a minimum healthy percentage
- Warm pools: pre-initialized instances for faster scale-out
- Termination policies: default picks the AZ with most instances, then the oldest launch template or closest to billing hour
- Instance scale-in protection for instances doing critical work
- Suspend processes (for example during maintenance)
bash
aws autoscaling start-instance-refresh --auto-scaling-group-name web-asg \
--preferences '{"MinHealthyPercentage":90,"InstanceWarmup":120}'
Design Checklist for a Scalable Web Tier
- Instances are stateless: sessions in ElastiCache or DynamoDB, files in S3 or EFS
- Instances in at least two AZs, ASG min of 2
- Health check path checks the app, not only the port
- AMI or user data builds identical servers with no manual steps
- Scale on a business-related metric and test with a load tool
- Alarms on
UnHealthyHostCount, 5xx errors and latency
Practice Tasks
- Create a launch template that installs a web server and shows the AZ name
- Create an ALB and ASG with min 2 across two AZs, and refresh the page to see both AZs answer
- Terminate one instance and watch the ASG replace it
- Add a target tracking policy at 50 percent CPU and generate load to see scale-out
- Add a path rule that sends
/api/* to a second target group
Conclusion
Use an ALB for HTTP routing, an NLB for static IP and extreme throughput, and a GWLB for appliances. Put instances in an Auto Scaling group across multiple AZs with ELB health checks, a launch template and target tracking policies, keep servers stateless, and roll out changes with instance refresh.
Quick Summary: ALB/NLB/GWLB choice; listeners, rules, target groups, health checks; CLI build; sticky + cross-zone; ASG min/desired/max + launch template; scaling policy types; refresh + lifecycle hooks; checklist.