Elastic Load Balancing & Auto Scaling
Design a self-healing, auto-scaled tier behind the right load balancer type.
By Invicly Tech, , in AWS Solutions Architect – Associate. About 12 minutes to read.
In short
Elastic Load Balancing spreads traffic across healthy targets in multiple AZs. Auto Scaling groups keep the right number of instances running, replacing unhealthy ones and adding or removing capacity based on policies. Together they make a self-healing, elastic tier.
Explained simply
A load balancer is a traffic officer standing in front of your servers. Users talk to one address, and the load balancer passes each request to a healthy server behind it. If a server breaks, the load balancer stops sending it traffic, and users never notice.
Elastic Load Balancing has three main types. The Application Load Balancer (ALB) understands web requests and can route by URL path or host name. The Network Load Balancer (NLB) works with raw TCP and UDP connections and is extremely fast. The Gateway Load Balancer (GWLB) sends traffic through security appliances such as firewalls.
An Auto Scaling group (ASG) is a manager that keeps the right number of servers running. You say "at least 2, at most 10", and it launches or removes instances to follow demand. If an instance fails a health check, the group replaces it with a fresh one.
Together they make a self-healing, elastic tier. Traffic grows, the ASG adds instances and registers them with the load balancer. Traffic falls, it removes them and you stop paying. An instance dies at 3 am, and a replacement is serving users before anyone wakes up.
Press Play on a diagram to walk through it one step at a time.
- 1Monitor metric
CloudWatch tracks CPU, requests per target or queue depth.
- 2Compare to target
Policy checks the metric against the target value.
- 3Adjust desired capacity
Scale out or in within min and max.
- 4Launch or terminate
Uses the launch template and balances across AZs.
- 5Health checks
Unhealthy instances are replaced automatically.
- Back to step 1
- Layer 7 HTTP and HTTPS
- Path and host routing
- Targets: EC2, IP, Lambda
- WAF integration
- Layer 4 TCP, UDP, TLS
- Millions of requests per second
- Static IP per AZ
- Ultra-low latency
- Layer 3 GENEVE
- Inserts firewall appliances
- Transparent inspection
- Scales third-party appliances
- 1DNS lookup
ALB name returns IPs of nodes in each AZ.
- 2ALB node
Terminates TLS with the ACM certificate.
- 3Listener rule
Host or path picks a target group.
- 4Target group
Only healthy targets are candidates.
- 5Instance
Request served; reply goes back via the ALB.
In depth
ALB listeners and routing rules
A listener waits on a port and protocol, usually HTTPS on 443 with an ACM certificate, plus HTTP on 80 that redirects to HTTPS. Each listener has rules checked in priority order. Conditions can match the host header, URL path, HTTP headers, method, query string or source IP. Actions can forward to one target group or split traffic across several by weight (handy for blue/green releases), redirect, return a fixed response, or authenticate users through Cognito or any OIDC provider before forwarding.
Targets can be instances, IP addresses (for containers or on-premises servers) or Lambda functions. The ALB adds an X-Forwarded-For header so your app can see the real client IP. Sticky sessions keep a user on the same target using a cookie, but they work against even load spreading, so prefer storing session data in ElastiCache or DynamoDB.
- Host api.example.com
- Forward to api-tg
- Path /images/*
- Forward to image-tg
- Header x-beta: on
- Weighted: 90% v1-tg, 10% v2-tg
- Path /old/*
- Redirect 301 to /new/
- Default rule
- Forward to web-tg
NLB and GWLB specifics
The NLB works at layer 4, forwarding TCP, UDP and TLS connections without reading HTTP. It handles millions of requests per second with very low latency and suits long-lived connections, gaming, IoT and non-HTTP protocols. It gives one static IP per AZ, or you can attach your own Elastic IPs, which helps when clients must allow-list addresses. With instance targets, the client's source IP is preserved. NLBs can now have security groups too.
Cross-zone load balancing is always on for ALBs but off by default for NLBs, and turning it on for an NLB adds cross-AZ data charges. An NLB is also required to publish a service through PrivateLink.
The GWLB uses the GENEVE protocol on port 6081 to pass traffic transparently through a fleet of third-party firewalls or inspection appliances. Gateway Load Balancer endpoints in route tables steer traffic to it.
- NLB: TCP, UDP, TLS; static IP per AZ
- NLB: preserves client IP; required for PrivateLink
- Cross-zone: always on for ALB, off by default for NLB
- GWLB: GENEVE 6081, firewall fleets
Health checks, draining and slow start
Each target group runs its own health checks. ALB defaults are a check every 30 seconds with a 5-second timeout, 5 consecutive successes to become healthy, 2 failures to become unhealthy, and HTTP 200 as success. Point the check at a lightweight /health page that tests the app's real dependencies, not just that the web server responds.
When a target is removed, the load balancer stops sending new requests but lets in-flight ones finish during the deregistration delay, 300 seconds by default. Lower it for short requests so deployments go faster. Slow start ramps traffic gradually to new targets that need to warm caches.
By default an ASG only uses EC2 status checks, which catch hardware and OS failures but not a crashed app. Set the ASG health check type to ELB so failed load balancer checks also trigger replacement, with a grace period long enough for the app to boot.
- Load balancer to Instance A: GET /health times out, twice1GET /health times out, twice
- Load balancer to Auto Scaling group: Target A is unhealthy2Target A is unhealthy
- Auto Scaling group to Instance A: Terminate after draining3Terminate after draining
- Auto Scaling group to Load balancer: Register new instance B4Register new instance B
- 5B passes 5 checks, gets trafficLoad balancer to Load balancer: B passes 5 checks, gets traffic
Inside an Auto Scaling group
A launch template holds the instance settings: AMI, instance type, security groups, IAM instance profile, user data and metadata options. It is versioned, so the ASG can point at a specific version or at the default. Launch configurations are the legacy alternative; use templates.
The ASG keeps desired capacity between min and max, spreads instances evenly across the subnets and AZs you list, and rebalances if one AZ gets too many. A mixed instances policy combines several instance types and On-Demand with Spot, for example a base of two On-Demand instances and the rest 70 percent Spot.
Instance refresh replaces instances in rolling batches after you change the launch template, while keeping a minimum healthy percentage. Lifecycle hooks pause an instance in Pending:Wait or Terminating:Wait, one hour by default, so you can install software or copy logs. Warm pools keep pre-initialized stopped instances ready for apps that boot slowly.
Choosing a scaling policy
Target tracking is the default choice. You pick a metric and a target, such as average CPU at 50 percent or 1,000 requests per target, and the ASG creates the CloudWatch alarms and adjusts capacity for you. It scales out quickly and in slowly to avoid flapping. Step scaling adds or removes different amounts depending on how far an alarm is breached, when you want more control. Simple scaling is legacy.
Scheduled actions change min, max or desired at set times, with cron expressions and a time zone, for known peaks like 9 am Monday to Friday. Predictive scaling studies past daily and weekly patterns and launches capacity ahead of forecast demand.
For queue workers, CPU is a poor signal. Publish a custom metric of backlog per instance (messages waiting divided by running instances) and target-track that. Set a default instance warmup so new instances are not counted before they are ready.
- Hold a metric at a target
- Alarms created for you
- CPU, requests per target, custom
- Best default
- You define alarms
- Bigger breach, bigger step
- More control
- More to tune
- Act before demand arrives
- Cron with time zone
- Forecast from history
- Combine with target tracking
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Compare ALB, NLB and GWLB~1h
- 2Configure target groups and health checks~1h
- 3Create an Auto Scaling group with a launch template~1h
- 4Set target tracking and scheduled scaling policies~1h
Key points
- Use ELB health checks in the ASG so app failures trigger replacement.
- Target tracking is the simplest policy: keep average CPU at 50 percent, for example.
- Scheduled scaling handles known peaks; predictive scaling learns daily patterns.
- Use launch templates; launch configurations are legacy.
- Pick NLB when clients need a static IP or extreme performance.
Key terms
Tap a card to flip it. 0/5 known
Examples
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}'Keep average CPU around 50 percent.
A self-healing web tier from the CLI
Step 1: create a launch template with the AMI, instance type, app security group, instance role and IMDSv2 required. Step 2: create the ASG across two private subnets in different AZs, attached to the ALB's target group, with min 2 and max 6. Step 3: set the health check type to ELB with a 120-second grace period, so a hung app is replaced. Step 4: add the target tracking policy (shown in the explainer). Step 5: test by stopping the app on one instance and watching the ASG replace it.
aws ec2 create-launch-template --launch-template-name web-lt \
--launch-template-data '{"ImageId":"ami-0abcdef1234567890",
"InstanceType":"t4g.small","SecurityGroupIds":["sg-0app"],
"IamInstanceProfile":{"Name":"web-role"},
"MetadataOptions":{"HttpTokens":"required"}}'
aws autoscaling create-auto-scaling-group --auto-scaling-group-name web-asg \
--launch-template 'LaunchTemplateName=web-lt,Version=$Default' \
--min-size 2 --max-size 6 --desired-capacity 2 \
--vpc-zone-identifier "subnet-0privA,subnet-0privB" \
--target-group-arns $TG_ARN \
--health-check-type ELB --health-check-grace-period 120Getting ahead of the 9 am rush
An internal app jumps from 2 to 8 instances every weekday at 9 am London time, and target tracking reacts a few minutes late. Step 1: add a scheduled action at 08:30 Monday to Friday that raises min and desired to 8. Step 2: add another at 18:00 that lowers min back to 2, so target tracking can scale in overnight. Step 3: keep the target tracking policy for unexpected spikes during the day. Predictive scaling could learn this pattern by itself, but a schedule is simpler when the pattern is fixed.
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name web-asg --scheduled-action-name morning \
--recurrence "30 8 * * 1-5" --time-zone "Europe/London" \
--min-size 8 --desired-capacity 8
aws autoscaling put-scheduled-update-group-action \
--auto-scaling-group-name web-asg --scheduled-action-name evening \
--recurrence "0 18 * * 1-5" --time-zone "Europe/London" \
--min-size 2Quick reference
- ALB: layer 7, host and path rules, Lambda targets, WAF, OIDC authentication
- NLB: layer 4 TCP and UDP, static IP per AZ, preserves client IP, needed for PrivateLink
- GWLB: GENEVE on port 6081 for transparent firewall fleets
- ALB health check defaults: 30 s interval, 5 healthy, 2 unhealthy, 5 s timeout
- Deregistration delay defaults to 300 seconds; lower it for faster deploys
- Set ASG health check type to ELB so app failures trigger replacement
- Instance refresh rolls out a new launch template version in batches
- Queue workers: scale on backlog per instance, not CPU
Common mistakes
- Leaving the ASG on EC2 status checks only, so a hung app is never replaced.
- Running the ASG in a single AZ, which defeats high availability.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a target group for an HTTP app on port 8080 with a health check on /health, and list its targets' health.
- Exercise 2medium
Add an ALB listener rule that sends /api/* to an api-tg target group, ahead of the default rule.
- Exercise 3hard
Change web-asg to a mixed instances policy: 2 On-Demand instances as a base, then 30% On-Demand and 70% Spot, across three Graviton instance types.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- ALB or NLB for a normal website?
- An ALB. It understands HTTP, supports path and host routing, WAF and authentication. Choose an NLB for non-HTTP protocols, static IPs or extreme performance.
- What is the difference between desired, minimum and maximum capacity?
- Minimum and maximum are the limits. Desired is how many instances the group runs right now, and scaling policies move it between those limits.
- Is the Classic Load Balancer still used?
- It is a previous-generation load balancer kept for older setups. New designs should use ALB, NLB or GWLB.
- Can an ALB route to Lambda functions?
- Yes. A target group can have a Lambda function as its target, and the ALB invokes it with the request as an event.