# Scaling and load balancing

Put two servers in two AZs behind an Application Load Balancer, let an Auto Scaling group keep them alive and scale on CPU, and watch it replace a server you kill.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 5. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/05-scaling-and-load-balancing

## What you will learn

- Describe a server once in a launch template
- Run an Auto Scaling group with min, max and desired capacity across two AZs
- Put an Application Load Balancer, a listener and a target group in front of it
- Lock the servers down so only the load balancer can reach them
- Watch the group replace an instance that dies, and scale on CPU with target tracking
- Choose between ALB and NLB, and know where TLS certificates from ACM fit

## From one server to a fleet

Before a site had a fleet, one server handled every request. If the server failed, the site went down; if a
promotion tripled traffic, the same server became overloaded. An operator could add another machine, but
configuring it by hand took time and left the two servers slightly different.

The standard fix is to put a load balancer in front of replaceable servers and let an Auto Scaling group keep
the desired capacity. The load balancer sends requests only to healthy targets. The group launches servers
from one template across multiple Availability Zones, and replaces instances that fail health checks. That
does not make every failure invisible, but it removes the single-machine dependency.

This lesson builds the pattern in the two-AZ VPC from lesson 4. The practice resources are deleted afterwards.
The request path is:

```text
internet → Application Load Balancer (public subnets, 2 AZs)
             → listener HTTP:80 → target group (health check GET /)
                → Auto Scaling group: 2–4 × t3.micro from a launch template, spread across AZs
```

Two security groups lock it down:

| Group            | Inbound                                |
| ---------------- | -------------------------------------- |
| `academy-alb-sg` | port 80 from `0.0.0.0/0`               |
| `academy-web-sg` | port 80 **only from `academy-alb-sg`** |

```sh
$ aws ec2 authorize-security-group-ingress --group-id $WEBSG --protocol tcp --port 80 --source-group $ALBSG
```

A security group can use another security group as its source, so nobody can skip the load balancer and hit a
server directly.

> **Figure.** Users reach the load balancer academy-alb on port 80. Through the target group academy-web-tg, which health-checks GET /, it sends requests only to healthy web servers. The Auto Scaling group academy-asg keeps min 2, desired 2, max 4 servers across ap-south-1a and ap-south-1b, launches each from the launch template academy-web-lt, adds up to two more when average CPU stays above 50 percent, and replaces a server that fails its health check.
>
> The load balancer is the one address users see. The Auto Scaling group keeps 2 to 4 healthy servers behind it.

## One server, described once

A **launch template** is a versioned recipe for launching EC2 instances. Without one, each replacement would
depend on someone repeating the console wizard and remembering the same AMI, type, network settings and
startup script. The Auto Scaling group reads the selected template version and uses it whenever it needs
capacity.

This template holds the AMI, instance type, security group, user data and IMDSv2 setting from lesson 3:

> **Figure.** Launch template academy-web-lt, version 1 (default), instance details: AMI ami-04394a3a96907e9ec, instance type t3.micro, security group sg-0dcb73ef50b44a171, no key pair.
>
> (1) The template's name. (2) Its instance type. No key pair: these servers are never logged into by hand.

The user data this time also asks the metadata service which AZ the server is in, so you can see the load
balancer spreading requests:

```sh
#!/bin/bash
dnf install -y nginx
TOKEN=$(curl -s -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 60")
AZ=$(curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/availability-zone)
echo "<h1>Hello from $(hostname) in $AZ</h1>" > /usr/share/nginx/html/index.html
systemctl enable --now nginx
```

Templates are versioned: change the AMI, create version 2, and roll it out (an **instance refresh** replaces the
servers a few at a time).

Keep production changes in a reviewed infrastructure definition, then publish a new template version instead
of editing running instances by hand. Pin the version when you need a controlled rollout; `Latest` is
convenient for a lab but can make a later scaling event use a different recipe than expected. A common
mistake is changing the template without refreshing existing instances: a new version affects future launches,
not machines already running.

## The Auto Scaling group

> **Figure.** Auto Scaling group academy-asg capacity overview: desired capacity 2, scaling limits 2 to 4, status At desired capacity. Details tab: launch template academy-web-lt, version Latest, t3.micro. Network: Availability Zones ap-south-1a and ap-south-1b with two subnets, Availability Zone distribution balanced best effort.
>
> (1) Desired capacity 2. (2) Scaling limits: never fewer than 2, never more than 4.

| Setting     | Meaning                                                             |
| ----------- | ------------------------------------------------------------------- |
| **Min**     | the floor: the group never goes below it, even if every server dies |
| **Desired** | how many it runs right now; scaling policies change this number     |
| **Max**     | the ceiling, which also caps your bill                              |

Give the group subnets in two or more AZs and it spreads instances evenly, so losing a whole AZ leaves half the
fleet running:

> **Figure.** Instance management tab: two instances, both InService, t3.micro, launched from academy-web-lt, one in aps1-az3 (ap-south-1b) and one in aps1-az1 (ap-south-1a), both Healthy.
>
> Two instances, two AZs, both InService and Healthy.

## The load balancer

An **Application Load Balancer** (ALB) takes requests on a **listener** (here HTTP:80), checks its **rules** and
forwards to a **target group**. The target group health-checks every server (`GET /` every 10 seconds) and only
sends traffic to the healthy ones:

> **Figure.** Load balancer academy-alb: type Application, internet-facing, Active, in two subnets in ap-south-1a and ap-south-1b, DNS name academy-alb-2056515812.ap-south-1.elb.amazonaws.com. Listeners and rules: HTTP:80.
>
> (1) The DNS name clients use; an ALB has no fixed IP. (2) The HTTP:80 listener.

> **Figure.** The load balancer's Resource map: Listeners (1) HTTP:80 with 1 rule; Rules: default priority, forward to target group; Target groups: academy-web-tg, instance HTTP, 2 targets, 2 healthy; Targets: i-00b8678ed097303f9 and i-02007cc1f591c06e4 on port 80, both Healthy.
>
> (1) Listener → rule → (2) target group → (3) targets: the whole request path, and the health of every hop.

> **Figure.** Target group academy-web-tg: HTTP port 80, load balancer academy-alb, 2 total targets, 2 Healthy, 0 Unhealthy. Registered targets: two academy-web instances on port 80 in ap-south-1a and ap-south-1b, both Healthy.
>
> Both targets healthy. The Auto Scaling group registers new instances here by itself.

Requests take turns between the AZs:

```sh
$ for i in 1 2 3 4; do curl -s http://academy-alb-2056515812.ap-south-1.elb.amazonaws.com; done
<h1>Hello from ip-10-0-23-40.ap-south-1.compute.internal in ap-south-1b</h1>
<h1>Hello from ip-10-0-23-40.ap-south-1.compute.internal in ap-south-1b</h1>
<h1>Hello from ip-10-0-10-240.ap-south-1.compute.internal in ap-south-1a</h1>
<h1>Hello from ip-10-0-10-240.ap-south-1.compute.internal in ap-south-1a</h1>
```

## Kill a server

An Auto Scaling group is designed to replace unhealthy capacity, not preserve a particular instance. This is
useful because instance hardware and processes can fail, but it means application data must not live only on
the instance disk. A load balancer's connection draining gives active requests time to finish before a target
is removed. Then the group launches a replacement from the launch template and registers it after startup.

In a real incident, investigate the failure as well as restoring capacity. Check target health, Auto Scaling
activity history and application logs; otherwise the replacement may fail for the same reason. The command
below deliberately terminates a practice instance to demonstrate the replacement path.

Terminate one instance by hand, as if its hardware failed:

```sh
$ aws ec2 terminate-instances --instance-ids i-0dca3be571b8075be
```

> **Figure.** Auto Scaling group Activity history: (1) Terminating EC2 instance i-0dca3be571b8075be, waiting for ELB connection draining, because an EC2 health check indicated it was terminated; (2) Launching a new EC2 instance i-02007cc1f591c06e4, in response to an unhealthy instance needing to be replaced, at the same second.
>
> (1) The dead instance is taken out of service and drained. (2) A replacement is launched the same second, with no one paged.

The load balancer stops sending traffic to the dying server (**connection draining** lets in-flight requests
finish), the group launches a replacement from the template, and once its health check passes, traffic returns
to two servers. The curl output above already includes the new server, `ip-10-0-10-240`.

## Scaling on load

> **Figure.** Automatic scaling tab: one dynamic scaling policy, cpu-50, type target tracking, enabled, as required to maintain average CPU utilization at 50, add or remove capacity units as required, instances need 300 seconds to warm up.
>
> A target tracking policy: keep average CPU near 50% by changing desired capacity between min and max.

| Policy              | How it works                                   | Use for                                        |
| ------------------- | ---------------------------------------------- | ---------------------------------------------- |
| **Target tracking** | keep a metric near a target, like a thermostat | most apps: CPU, requests per target            |
| **Step scaling**    | add or remove N instances at alarm thresholds  | when you need precise steps                    |
| **Scheduled**       | change capacity at set times                   | known patterns: office hours, a sale at 9 a.m. |

Scaling takes minutes (boot, user data, health checks), so it handles growth, not a sudden spike. Keep a little
headroom in min.

## ALB or NLB

Pick a load balancer based on the protocol and routing decisions the application needs. An Application Load
Balancer works at the HTTP request layer. It can route by host name, URL path or headers, so one listener can
serve multiple web applications. A Network Load Balancer works at the connection layer for TCP, UDP or TLS
traffic and can provide static addresses per Availability Zone.

|         | Application Load Balancer | Network Load Balancer                               |
| ------- | ------------------------- | --------------------------------------------------- |
| Layer   | 7: HTTP and HTTPS         | 4: TCP, UDP, TLS                                    |
| Routing | by path, host, header     | by port                                             |
| IP      | DNS name only             | static IPs per AZ                                   |
| Use for | web apps and APIs         | very high throughput, non-HTTP protocols, fixed IPs |

For HTTPS, request a free public certificate from **AWS Certificate Manager (ACM)** for your domain, add an
HTTPS:443 listener with it, and redirect HTTP:80 to HTTPS. ACM renews the certificate automatically.

Use an ALB for web applications and HTTP APIs when request-aware routing or HTTP health checks matter. Use an
NLB for protocols that are not HTTP, very high connection throughput, or a static-IP requirement. The common
mistake is selecting by name alone: confirm listener protocols, target type, address needs and TLS termination
before choosing. Both products have costs even when traffic is low.

## Clean up

## Listener rules choose the target

An ALB listener is the entry point for a protocol and port, such as HTTP on port 80. Its rules inspect request
attributes and choose an action. A path condition can route `/images/*` to one target group, while a host
condition can route `api.example.com` to another. The default action handles requests that match no rule.

ALB evaluates the lowest numbered matching priority first; each rule has a unique priority, and the default
rule is the final fallback. The example creates a path rule and then lists the configured priorities and
conditions. Always leave a sensible default action and check rule order after changes. A broad rule placed
above a more specific rule can capture traffic before the intended destination does.

```sh
$ aws elbv2 create-rule --listener-arn "$LISTENER" --priority 10 \
    --conditions Field=path-pattern,Values='/images/*' \
    --actions Type=forward,TargetGroupArn="$IMAGES_TG"
$ aws elbv2 describe-rules --listener-arn "$LISTENER" \
    --query 'Rules[].{Priority:Priority,Conditions:Conditions}' --output table
```

Use listener rules when several services share one ALB and need routing by host or path. Use separate ALBs
when the applications need independent network boundaries, certificates or scaling ownership. Rule changes
affect live traffic, so validate the condition and target group before applying them.

## Sticky sessions and safe refreshes

Stickiness keeps a browser on one target, which can help a legacy in-memory session but causes uneven load. Prefer
an external session store and stateless targets. Instance refresh replaces an Auto Scaling group gradually after a
launch-template change; lifecycle hooks pause launch or termination so work can drain, and warm pools keep
pre-initialised instances ready for bursts.

```sh
$ aws elbv2 modify-target-group-attributes --target-group-arn "$TG" \
    --attributes Key=stickiness.enabled,Value=true Key=stickiness.lb_cookie.duration_seconds,Value=300
$ aws autoscaling start-instance-refresh --auto-scaling-group-name "$ASG" \
    --preferences MinHealthyPercentage=90,InstanceWarmup=120
```

The load balancer is billed per hour even with no traffic, so delete everything, in order:

```sh
$ aws autoscaling delete-auto-scaling-group --auto-scaling-group-name academy-asg --force-delete
$ aws elbv2 delete-load-balancer --load-balancer-arn $ALB && aws elbv2 wait load-balancers-deleted --load-balancer-arns $ALB
$ aws elbv2 delete-target-group --target-group-arn $TG
$ aws ec2 delete-launch-template --launch-template-name academy-web-lt
$ aws ec2 delete-security-group --group-id $WEBSG && aws ec2 delete-security-group --group-id $ALBSG
```

`--force-delete` terminates the group's instances too. The web security group can only be deleted once those
instances are gone.

> **In production.** Servers go in private subnets with a NAT gateway or endpoints, only the ALB is public, HTTPS uses an ACM certificate, and the whole stack is in Terraform (lesson 16). Use instance refresh to roll out new AMIs, CloudWatch alarms on unhealthy targets and 5xx errors (lesson 13), and at least two AZs, or three for anything critical.

## Mission: A self-healing web tier

Behind an Application Load Balancer, run an Auto Scaling group of 2 t3.micro instances across two AZs, reachable only through the load balancer. Show requests answered from both AZs, kill one instance, watch it be replaced, then delete everything.

- You need: An AWS account, the AWS CLI, and a VPC with two public subnets (the lesson 4 VPC, or the default VPC)
- You'll have: curl answers from two AZs, an Activity entry replacing the instance you killed, and no load balancer or group left

```sh
$ V=vpc-…; SUBS="subnet-… subnet-…"                       # two public subnets in different AZs
$ ALBSG=$(aws ec2 create-security-group --vpc-id $V --group-name academy-alb-sg --description "HTTP to the ALB" --query GroupId --output text)
$ aws ec2 authorize-security-group-ingress --group-id $ALBSG --protocol tcp --port 80 --cidr 0.0.0.0/0
$ WEBSG=$(aws ec2 create-security-group --vpc-id $V --group-name academy-web-sg --description "HTTP from the ALB only" --query GroupId --output text)
$ aws ec2 authorize-security-group-ingress --group-id $WEBSG --protocol tcp --port 80 --source-group $ALBSG
$ AMI=$(aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text)
$ aws ec2 create-launch-template --launch-template-name academy-web-lt --launch-template-data \
    "{\"ImageId\":\"$AMI\",\"InstanceType\":\"t3.micro\",\"SecurityGroupIds\":[\"$WEBSG\"],\"UserData\":\"$(base64 -w0 user-data.sh)\",\"MetadataOptions\":{\"HttpTokens\":\"required\"}}"
$ TG=$(aws elbv2 create-target-group --name academy-web-tg --protocol HTTP --port 80 --vpc-id $V --health-check-path / --query 'TargetGroups[0].TargetGroupArn' --output text)
$ ALB=$(aws elbv2 create-load-balancer --name academy-alb --type application --subnets $SUBS --security-groups $ALBSG --query 'LoadBalancers[0].LoadBalancerArn' --output text)
$ aws elbv2 create-listener --load-balancer-arn $ALB --protocol HTTP --port 80 --default-actions Type=forward,TargetGroupArn=$TG
$ aws autoscaling create-auto-scaling-group --auto-scaling-group-name academy-asg --launch-template LaunchTemplateName=academy-web-lt,Version='$Latest' \
    --min-size 2 --max-size 4 --desired-capacity 2 --vpc-zone-identifier "$(echo $SUBS | tr ' ' ,)" \
    --target-group-arns $TG --health-check-type ELB --health-check-grace-period 60
$ DNS=$(aws elbv2 describe-load-balancers --load-balancer-arns $ALB --query 'LoadBalancers[0].DNSName' --output text)
$ for i in 1 2 3 4; do curl -s http://$DNS; done            # after a few minutes: both AZs answer
$ aws ec2 terminate-instances --instance-ids <one of the group's instances>
$ aws autoscaling describe-scaling-activities --auto-scaling-group-name academy-asg --max-items 2 --query 'Activities[].Description'
```

`user-data.sh` is the script from this lesson; the subnets must give instances public IPs so they can download nginx
(if not, turn it on: `aws ec2 modify-subnet-attribute --subnet-id … --map-public-ip-on-launch`). Clean up
with the commands above. An ALB plus two t3.micro for half an hour costs a few cents.

## Try it

- Create a launch template with the nginx user data from lesson 3.
- Create an Auto Scaling group of 2 instances across two public subnets, with ELB health checks.
- Put an Application Load Balancer in front and curl its DNS name a few times. Which hosts answer?
- Terminate one instance by hand and watch the Activity tab.
- Add a target tracking policy at 50% CPU and read what it will do.
- Delete the group, load balancer, target group, launch template and security groups.

## Quiz

1. What does an Auto Scaling group do when one of its instances fails its health check?
   - Emails you
   - **Terminates it and launches a replacement to get back to the desired capacity** (answer)
   - Nothing until you act
   Why: The Activity tab showed it, launching i-02007cc1f591c06e4 in response to an unhealthy instance needing to be replaced.

2. Why does the servers' security group allow port 80 only from the load balancer's security group?
   - It is required by AWS
   - **So nobody can bypass the load balancer and hit a server directly** (answer)
   - It makes the load balancer faster
   Why: A security group can name another security group as its source. Only traffic coming from the ALB gets in.

3. Min 2, max 4, desired 2, and a target tracking policy at 50% CPU. Traffic doubles and CPU hits 80%. What happens?
   - Nothing, desired is fixed
   - **The group adds instances, up to 4, until average CPU is back near 50%** (answer)
   - It replaces the instance type with a bigger one
   Why: Target tracking raises desired capacity within min and max, then lowers it again when the load drops.

4. Your app needs path-based routing (/api to one service, / to another) over HTTPS. Which load balancer?
   - **Application Load Balancer** (answer)
   - Network Load Balancer
   - Classic Load Balancer
   Why: The ALB works at layer 7 (HTTP), with rules on paths and hosts and TLS certificates from ACM. The NLB works at layer 4 (TCP/UDP), for raw speed and static IPs.

5. Why use ELB health checks for the Auto Scaling group instead of only EC2 status checks?
   - They are cheaper
   - **EC2 checks only see whether the machine runs; ELB checks see whether the app answers, so a crashed app also gets replaced** (answer)
   - EC2 checks don't exist for groups
   Why: A server can be up while nginx is dead. The target group's HTTP check catches that.

## Resources

- [Amazon EC2 Auto Scaling user guide](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html) (AWS Docs)
- [Target tracking scaling policies](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-target-tracking.html) (AWS Docs)
- [Application Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) (AWS Docs)
- [Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html) (AWS Docs)
- [AWS Certificate Manager](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) (AWS Docs)
