Expert · High availability, scaling and disaster recovery · topic 40 of 50 · 35 min
Load balancing and auto scaling
Explanation
Vertical versus horizontal scaling
Vertical scaling (scaling up) means moving to a bigger machine: more CPU and memory. It is simple and needs no code changes, but there is a largest size, resizing often needs a restart, and it is still one machine, so still a single point of failure. Horizontal scaling (scaling out) means adding more machines of the same size. It has almost no upper limit and improves availability, but needs a load balancer and stateless servers.
Elastic Load Balancing
Elastic Load Balancing (ELB) is AWS's managed load balancer service. It spreads incoming traffic across targets (EC2 instances, containers, IP addresses or Lambda functions) in several AZs, and it scales itself.
| Type | Layer | Use it for |
|---|---|---|
| Application Load Balancer (ALB) | Layer 7 (HTTP, HTTPS, gRPC) | Websites and APIs. Routes by path (/api, /images) or host name, handles HTTPS certificates, works with containers and Lambda. |
| Network Load Balancer (NLB) | Layer 4 (TCP, UDP, TLS) | Very high traffic, very low latency, non-HTTP protocols, or when clients need a static IP address per zone. |
| Gateway Load Balancer (GWLB) | Layer 3 (IP packets) | Putting third-party virtual appliances, such as firewalls and intrusion detection systems, in the traffic path. |
| Classic Load Balancer | Layer 4 and 7 (legacy) | Old setups only. Migrate to ALB or NLB. |
Three words to know. A listener checks for connections on a port and protocol, such as HTTPS on 443, and has rules that decide where requests go. A target group is a set of targets that receive traffic, plus its health check settings. The health check is the regular test (for example GET /health must return 200) that decides which targets are healthy.
aws elbv2 create-target-group --name results-web-tg \
--protocol HTTP --port 80 --vpc-id vpc-0abc1234 \
--health-check-path /health --health-check-interval-seconds 15 \
--healthy-threshold-count 2 --unhealthy-threshold-count 3Auto Scaling groups
An Auto Scaling group (ASG) keeps a fleet of EC2 instances at the right size. It starts instances from a launch template (which machine image, instance type, security groups and start-up script to use). You set three numbers: minimum (never fewer), desired (how many right now) and maximum (never more, which also caps cost). The ASG spreads instances across the subnets you give it in different AZs, and replaces any instance that fails its health check.
aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name results-web-asg \
--launch-template LaunchTemplateName=results-web,Version='$Latest' \
--min-size 2 --desired-capacity 2 --max-size 20 \
--vpc-zone-identifier "subnet-0aaa1111,subnet-0bbb2222" \
--target-group-arns arn:aws:elasticloadbalancing:ap-south-1:111122223333:targetgroup/results-web-tg/0123456789abcdef \
--health-check-type ELB --health-check-grace-period 120Scaling policies
| Policy | How it works | Good for |
|---|---|---|
| Target tracking | You pick a metric and a target, such as average CPU at 50%. AWS adds or removes instances to stay near it. | Most web apps. The simplest and the usual first choice. |
| Step scaling | CloudWatch alarms with steps: CPU above 60% add 2, above 80% add 5. | When you want bigger jumps for bigger spikes. |
| Scheduled | Change min, desired or max at a set time. | Known peaks: office hours, a sale, a booking window. |
| Predictive | AWS forecasts load from past daily and weekly patterns and scales ahead of time. | Regular, repeating patterns; often combined with target tracking. |
Target tracking works roughly like this: desired = ceil(current × metric ÷ target). With 4 instances at 80% CPU and a target of 50%, you need 4 × 80 ÷ 50 = 6.4, so 7 instances. The result is always kept between the minimum and maximum.
# cpu50.json
# {
# "PredefinedMetricSpecification": { "PredefinedMetricType": "ASGAverageCPUUtilization" },
# "TargetValue": 50.0
# }
aws autoscaling put-scaling-policy --auto-scaling-group-name results-web-asg \
--policy-name cpu50 --policy-type TargetTrackingScaling \
--target-tracking-configuration file://cpu50.json
# Scale up before a 10 am booking window, every day at 9:30 India time
aws autoscaling put-scheduled-update-group-action --auto-scaling-group-name tatkal-web-asg \
--scheduled-action-name before-tatkal --recurrence "30 9 * * *" --time-zone "Asia/Kolkata" \
--min-size 30 --desired-capacity 30 --max-size 120Warm-up and cooldown
A new instance needs time to boot, start the app and fill its caches. If its metrics are counted too early, the group may think it is still overloaded and add even more servers. Instance warm-up tells the ASG how long to wait before a new instance's metrics count. A cooldown (used with simple scaling policies) is a pause after one scaling action before the next. Scaling in (removing servers) is usually done more slowly than scaling out, so a brief dip does not remove capacity you need a minute later.
Scaling the database
App servers are easy to multiply; the database is usually the real limit. Common steps, from simple to complex: a bigger database instance (vertical); read replicas, copies that serve read-only queries such as "show my result"; a cache such as ElastiCache in front of the database for hot data; connection pooling (for example RDS Proxy), so thousands of app processes do not open thousands of connections; and finally sharding, which splits data across several databases by a key such as state or user ID. Sharding is powerful but complex, so treat it as a last step.
Planning for a known peak
Some peaks are on the calendar. On a ticket booking site, Tatkal booking for AC classes opens at 10 am, and huge traffic arrives in the first minutes. On a state board results day, millions of students open the site at the announced hour. Reactive scaling alone is too slow for a wall of traffic that arrives in seconds. Teams scale up on a schedule before the peak, load test beforehand, cache everything that can be cached (the landing page, static files on a CDN), use read replicas for result lookups, and put a queue or a virtual waiting room in front of the heaviest step.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Load balancing and auto scaling · 1/8
You can scale up with a bigger server, or scale out with more servers. Scaling out has no fixed limit and removes a single point of failure.
Prefer a video by a teacher? Find free videos on “aws application load balancer auto scaling group target tracking tutorial” on YouTube ↗
In real life: Exam results day on a state board website
A state board announces that Class 12 results go live at 11 am. The cloud team sets a scheduled action to raise the ASG to 40 instances at 10:15, behind an ALB in three AZs, with a target tracking policy (requests per target) on top in case traffic is even higher. The home page and static files are cached on a CDN, result lookups go to two read replicas, and the database primary only handles writes. At 11:02 traffic is 60 times normal; target tracking adds 25 more instances, and by evening a scheduled action brings the minimum back down to 2.
Practice (0/3 done)
Your web API needs path-based routing: /api to one group of servers and /images to another. Which load balancer fits?
Simulate target tracking. Write desired_capacity(current, metric, target, min_size, max_size) that returns ceil(current × metric ÷ target), kept between min_size and max_size. Example: 4 instances at 80% CPU with a 50% target gives 7. Use math.ceil.
An ed-tech app normally needs 4 app servers. Every Sunday at 10 am it runs an all-India mock test for 2 hours, with about 12 times normal traffic arriving in the first 5 minutes. Write a short scaling plan: ASG settings, which scaling policies you use and when, how the database copes, and what you test beforehand.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Backups and disaster recoveryHigh availability, scaling and disaster recovery · same module
- The Well-Architected FrameworkHigh availability, scaling and disaster recovery · same module
- Scaling: handling more usersBackend Development · Deployment and scaling
- Scaling and transforming numbersData Science, Machine Learning and AI · Clustering, dimensionality reduction and feature engineering
- Serverless with AWS LambdaServerless, monitoring and cost control
- Core Google Cloud servicesGoogle Cloud and comparing the clouds
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which is a drawback of vertical scaling?
Answer: There is a largest size, and it is still one machine
A bigger machine has a ceiling and remains a single point of failure; resizing often needs a restart.
A game server uses UDP and clients need a fixed IP address to connect to. Which load balancer fits?
Answer: Network Load Balancer
The NLB works at layer 4, supports UDP and can have a static IP address per zone.
An ASG has min 2, desired 4, max 10. One instance fails its health check. What does the ASG do?
Answer: Replaces the unhealthy instance to get back to 4
The ASG keeps the group at the desired number and replaces unhealthy instances.
Traffic always jumps at 10 am when a booking window opens. Which scaling policy prepares the capacity before the jump?
Answer: Scheduled scaling
A scheduled action raises capacity at a set time, before the peak arrives. Reactive policies always lag behind.
Most database load on a results site is students reading their own result. What helps most, simply?
Answer: Read replicas and a cache for the read queries
Read replicas and caching take read-only load off the primary. Sharding is a complex last step.
Which is horizontal scaling?Related
Answer: Adding more servers behind a load balancer
Horizontal means more machines sharing the work; vertical means a bigger single machine.
What does a load balancer do when a server fails its health checks several times in a row?Related
Answer: Stops sending traffic to that server
Unhealthy targets are removed from rotation until they pass checks again.
In the instance type r7g.xlarge, what does the g mean?Related
Answer: AWS Graviton (ARM) processor
The attribute g means a Graviton ARM processor. GPU instances are the g and p families, where the letter comes first.
In ECS, what keeps a desired number of tasks running and replaces failed ones?Related
Answer: A service
A service maintains the desired count and handles rolling deployments.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “High availability, scaling and disaster recovery” before its exam: Backups and disaster recovery, The Well-Architected Framework.
- Module 10 exam: High availability, scaling and disaster recovery · 13 questions · 25 min, without help. 4 topics of this module still to finish first.
- Then the next module, Cloud security and compliance. 50 topics left in the course before the final exam.