Auto Scaling and Load Balancing

Add and remove EC2 capacity automatically and spread traffic across it with Elastic Load Balancing.

What is it?

Elasticity means capacity follows demand. Amazon EC2 Auto Scaling changes how many instances run. Elastic Load Balancing (ELB) spreads requests across them.

An Auto Scaling group has three key numbers:

  • Minimum: the fewest instances ever running.
  • Desired: how many you want right now.
  • Maximum: the ceiling, which protects your budget.

Scaling approaches:

  • Dynamic scaling: react to metrics, for example 'keep average CPU near 50%' (target tracking) or step/simple policies tied to alarms.
  • Predictive scaling: use machine learning on past patterns to scale ahead of a recurring peak.
  • Scheduled scaling: scale at known times, like a Monday-morning rush.

Load balancer types:

  • Application Load Balancer (ALB): layer 7 (HTTP/HTTPS). Routes by path, host, headers; good for web apps and microservices.
  • Network Load Balancer (NLB): layer 4 (TCP/UDP/TLS). Very high throughput, low latency, static IPs.
  • Gateway Load Balancer (GWLB): sends traffic through third-party virtual appliances such as firewalls and inspection tools.
  • Classic Load Balancer is the legacy option.

Load balancers also run health checks and stop sending traffic to unhealthy targets.

Exam angle: Auto Scaling is about capacity and cost (run only what you need now). ELB is about availability (one entry point, traffic spread across healthy targets in several AZs). The service is Elastic Load Balancing; ALB, NLB, GWLB and CLB are its load balancer types.

Details the exam likes:

  • ALB supports content-based routing (host, path, headers, query strings) and can be protected by AWS WAF.
  • NLB handles millions of requests per second and sudden spikes with ultra-low latency, and gives a static IP per AZ. Good for gaming, IoT and other non-HTTP traffic.
  • GWLB deploys and scales fleets of third-party firewalls and intrusion detection/prevention appliances, using the GENEVE protocol.
  • CLB (legacy) registers instances directly, without target groups. AWS recommends moving to ALB or NLB.

A load balancer helps even in front of one instance. You get a stable DNS name, can add instances later, and can attach AWS WAF and free AWS Certificate Manager (ACM) TLS certificates.

Launch templates describe what to launch (AMI, instance type, key pair, security groups). They are versioned; the group uses a specific version or the latest. The older launch configurations are deprecated.

Explain like I'm 10

Think of an airport check-in hall. The load balancer is the person at the entrance who sends each traveler to the shortest open desk, and skips any desk whose agent stepped away. Auto Scaling is the manager who opens desks when the line grows and closes them when it empties: never fewer than two, never more than the hall can hold.

Examples

Auto Scaling group with target tracking (CLI)

aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name web-asg \
  --launch-template LaunchTemplateName=web-template,Version='$Latest' \
  --min-size 2 --desired-capacity 2 --max-size 6 \
  --vpc-zone-identifier "subnet-aaa111,subnet-bbb222" \
  --target-group-arns arn:aws:elasticloadbalancing:eu-west-1:111122223333:targetgroup/web/abc123 \
  --health-check-type ELB --health-check-grace-period 120

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
  }'

Two subnets in different AZs give you multi-AZ capacity; the ELB health check replaces instances that stop answering.

Which load balancer?

Need                                           Choose
---------------------------------------------  -----
Route /api to one service, /img to another     ALB
HTTP/2, WebSockets, host-based routing         ALB
Millions of TCP connections, fixed IPs         NLB
Insert a firewall appliance into the path      GWLB

How it works

Metrics (such as CPU or requests per target) flow to CloudWatch. A scaling policy compares the metric with its target and changes desired capacity, staying within min and max. The group launches instances from a launch template or terminates the least useful ones, balancing across AZs.

The load balancer registers new instances in a target group, health-checks them and spreads requests. Instances are interchangeable, so keep session data off the server (for example in a cache or database).

A listener (such as HTTP on port 80 or HTTPS on 443) receives traffic and forwards it to a target group by its rules. Targets can be EC2 instances, IP addresses, Lambda functions or another ALB. The health check calls a path and expects a healthy response (such as HTTP 200) a set number of times in a row.

By default an Auto Scaling group uses only EC2 status checks (is the instance running?). Switch to ELB health checks so instances whose app stopped answering are replaced too. Scale-in protection stops chosen instances from being terminated.

When an instance is removed, deregistration delay (connection draining) lets in-flight requests finish. Users reach the app through a Route 53 alias record to the load balancer's DNS name, never to instance IPs.

         users
           |
   [ Load Balancer ]  <- health checks
      /      |      \
  +-----+ +-----+ +-----+
  | EC2 | | EC2 | | EC2 |   Auto Scaling group
  +-----+ +-----+ +-----+   min 2 / desired 3 / max 6
   AZ-a    AZ-b    AZ-a
       ^ CloudWatch metric drives desired count

Why does it exist?

Fixed capacity wastes money when traffic is low and causes outages when it spikes. These services keep cost in line with demand and keep the app up when single servers fail.

When to use it

Use them for any stateless web or API tier with changing load, and whenever you want self-healing: failed instances are replaced automatically.

When not to use it

A single stateful server (like a lone database on EC2) gains nothing from extra copies. Small, steady workloads may not need scaling. Serverless options like Lambda scale without groups to manage.

Common mistakes

  • Setting min = max = 1 and believing that is 'highly available'.

  • Placing all instances in a single AZ.

  • Storing user sessions on local disk, so scaling in loses data.

  • Health-check grace period too short, so new instances are killed while booting.

  • Using an ALB when you need static IPs (NLB) or the reverse.

  • Terminating instances by hand to 'shut down' an app: the group simply launches replacements. Delete or scale the group itself.

  • Leaving the group on EC2 status checks only, so an instance with a crashed app keeps receiving traffic.

  • Pointing DNS at instance IPs instead of an alias to the load balancer.

  • Thinking ELB is mainly a cost-saving tool. Auto Scaling saves cost; ELB provides availability.

Practice exercises

  1. Easy:

    Explain min, desired, and max for a group set to 2/4/10 and what happens if an instance crashes.

  2. Medium:

    Choose dynamic, predictive, or scheduled scaling for: (a) a payroll app on the 1st and 15th, (b) a viral campaign, (c) a daily commuter app.

  3. Medium:

    Write ALB path rules to send /api/* to one target group and everything else to another.

  4. Hard:

    Design a stateless login flow so any instance can serve any user. Where does the session live?

  5. Easy:

    Match each to ALB, NLB or GWLB: a multiplayer game server over UDP, a fleet of third-party firewalls, a website routing /blog and /shop to different services.

  6. Medium:

    An instance in your group is running but its web server has crashed, and it is never replaced. Explain why and what setting fixes it.

Interview questions

Difference between EC2 Auto Scaling and ELB?

Auto Scaling changes how many instances exist; ELB distributes traffic across them and checks their health.

When use an NLB over an ALB?

When you need layer 4 handling, extreme performance, or static IP addresses; use an ALB for HTTP-aware routing.

What is predictive scaling?

Forecasting load from historical patterns and scaling capacity ahead of time.

Exam-style: Which service automatically adds EC2 instances when demand rises?

Amazon EC2 Auto Scaling.

Exam-style: Which load balancer routes traffic based on URL path?

Application Load Balancer.

Exam-style: Which load balancer provides a static IP address per Availability Zone and handles millions of requests per second?

Network Load Balancer.

Exam-style: Which load balancer is used to deploy and scale third-party virtual firewall appliances?

Gateway Load Balancer.

Exam-style: Which feature is mainly about cost, and which mainly about availability: Auto Scaling or ELB?

Auto Scaling matches capacity to demand (cost and capacity); ELB distributes traffic across healthy targets in multiple AZs (availability).

What happens if you terminate an instance that belongs to an Auto Scaling group?

The group sees it is below desired capacity and launches a replacement. To stop the instances, change the group's capacity or delete the group.