Compute and load balancing on AWS

Intermediate · 32 min

Wire an ALB, target group, listener, launch template and Auto Scaling group with security groups that reference each other, and what the ALB costs per month.

Before thisA VPC on AWSIAM roles and policies in Terraform

kodEdge · 32 min

Compute and load balancing on AWS

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by kodEdgeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The app security group should allow traffic from the ALB's security group, not a CIDR, so the rule survives instances coming and going.
  • The ASG registers instances in the target group; health_check_type = ELB makes it replace instances the load balancer marks unhealthy.
  • Use launch templates (aws_launch_configuration is discouraged), IMDSv2 via metadata_options, and instance_refresh so template changes roll through the fleet.
  • An ALB costs $0.0252 per hour in eu-west-1 on the price list I read, about $18.40 per month before capacity units, so share ALBs across services.

A service that survives its own server

One EC2 instance behind a public IP works until the instance dies, the zone has a bad hour or you need to deploy. Then someone logs in and restarts something by hand. The standard shape that removes that person is three pieces: an Application Load Balancer that terminates traffic and checks health, an Auto Scaling group that keeps N copies of a launch template running across zones, and security groups that say who may talk to whom. This lesson writes that in Terraform on top of the VPC from the last lesson and the role from the one before.

The idea behind each piece is covered in the devops lessons on reverse proxies and load balancers and autoscaling. Here the question is how the Terraform resources fit together, which is where the bugs live.

How the pieces connect

internet -> ALB (public subnets, sg: 80/443 from anywhere)
              -> listener -> target group
                              <- ASG instances (private subnets, sg: 8080 only from ALB's sg)

Four connections to get right:

  1. The security groups reference each other: the app’s group allows port 8080 from the ALB’s security group, not from a CIDR. When instances come and go, the rule stays valid.
  2. The listener forwards to a target group, and the target group defines the health check.
  3. The ASG registers its instances into the target group, and with health_check_type = "ELB" it replaces instances that the load balancer marks unhealthy, not just ones EC2 says have stopped.
  4. The ASG launches from a launch template, which holds the AMI, instance type, security group, instance profile and user data.

The Terraform

Written from the AWS provider documentation, not run by me, because Terraform and an AWS account are not available here. It assumes the aws_vpc.main and subnets from the previous lesson, plus an aws_iam_instance_profile.app and an AMI data source:

resource "aws_security_group" "alb" {
  vpc_id = aws_vpc.main.id
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "app" {
  vpc_id = aws_vpc.main.id
  ingress {
    from_port       = 8080
    to_port         = 8080
    protocol        = "tcp"
    security_groups = [aws_security_group.alb.id]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_lb" "web" {
  load_balancer_type = "application"
  subnets            = [for s in aws_subnet.public : s.id]
  security_groups    = [aws_security_group.alb.id]
}

resource "aws_lb_target_group" "web" {
  port     = 8080
  protocol = "HTTP"
  vpc_id   = aws_vpc.main.id
  health_check {
    path    = "/healthz"
    matcher = "200"
  }
}

resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.web.arn
  port              = 80
  protocol          = "HTTP"
  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.web.arn
  }
}

resource "aws_launch_template" "web" {
  name_prefix            = "web-"
  image_id               = data.aws_ami.app.id
  instance_type          = "t4g.small"
  vpc_security_group_ids = [aws_security_group.app.id]
  iam_instance_profile { name = aws_iam_instance_profile.app.name }
  metadata_options { http_tokens = "required" }
  user_data = filebase64("${path.module}/boot.sh")
}

resource "aws_autoscaling_group" "web" {
  min_size            = 2
  max_size            = 6
  vpc_zone_identifier = [for s in aws_subnet.private : s.id]
  target_group_arns   = [aws_lb_target_group.web.arn]
  health_check_type   = "ELB"

  launch_template {
    id      = aws_launch_template.web.id
    version = aws_launch_template.web.latest_version
  }

  instance_refresh {
    strategy = "Rolling"
    preferences { min_healthy_percentage = 90 }
  }
}

Things in it that matter. http_tokens = "required" turns on IMDSv2, the token-based version of the instance metadata service; it appears in the launch template docs, and I left it on because instances that can be tricked into fetching the old unauthenticated version leak their role credentials. Pointing the ASG at latest_version plus instance_refresh means a changed template rolls the fleet gradually, instead of only affecting instances launched later. Do not use aws_launch_configuration: the provider’s own docs carry a warning that launch configurations are discouraged in favour of launch templates.

The listener here is HTTP on port 80 to keep the example short. In production you add an aws_lb_listener on 443 with a certificate, and either redirect port 80 to it or leave it closed. The TLS lesson in devops covers certificates.

Where this breaks in practice

  • Health check path. The target group probes /healthz and expects 200. If your app returns a redirect or needs auth, every instance is marked unhealthy, the ASG replaces them endlessly and you see a refresh loop. The ASG docs mention that waiting for capacity can time out and mark the group tainted when new instances do not pass the load balancer’s health checks.
  • Ordering. The ALB must exist before the ASG registers with its target group, and a destroy must reverse it. Terraform’s implicit dependencies through attribute references handle most of this, as the dependency lesson shows. NAT gateways and the internet gateway are the usual places where an explicit depends_on is needed.
  • Replace without downtime. Anything that forces a new target group while a listener points at it needs create_before_destroy, from the lifecycle lesson, and a unique name or name_prefix.
  • Desired capacity. If you let the autoscaler change the size and Terraform also sets desired_capacity, every apply fights the scaler. Leave it out, or use ignore_changes on it.

What the load balancer costs

I pulled the public AWS Price List for load balancing in eu-west-1, published 25 November 2026. An Application Load Balancer is $0.0252 per hour, plus $0.008 per used load balancer capacity unit per hour. Over a 730-hour month the fixed part is about $18.40 per load balancer, before any traffic. One ALB per service, per environment, adds up, so teams share one ALB across services with host or path rules on listeners. That price is the first thing an Infracost run would show you.

Alternatives, briefly

This lesson uses EC2 behind an ALB. The same ALB resources front containers on ECS or pods on Kubernetes, with the target type changed (ip instead of instance). The ASG part gets replaced by a service definition. The network and role parts stay the same.

About the video

The embed is kodEdge’s “5. Setup AWS Application Load Balancer with Auto Scaling Group using Terraform”, 31 minutes 39 seconds, May 2024. Its chapter list covers the architecture, the VPC recap, creating the security groups, the ALB and the Auto Scaling group, and applying the code, and its description says the ALB is in a public subnet with the Auto Scaling group in a private one, which matches the diagram above. It is the fifth lecture of a series, so it depends on earlier ones. It is a small channel. I did not check whether it uses a launch template or a launch configuration, and the lesson text above is from the provider docs. English was judged from the title, description, channel and its English auto-caption track.

Where this fits

Instances are one way to run an app. The next lesson covers the other big one, a managed Kubernetes cluster, and the two providers that put workloads on it: Kubernetes clusters and the kubernetes and helm providers.

Check yourself

  1. 01Why reference the ALB security group in the app group's ingress rule?

    Instances change, but the ALB's group stays the same, so the rule stays correct without maintaining IP ranges.

  2. 02What does health_check_type = ELB change for the Auto Scaling group?

    It replaces instances that the load balancer reports unhealthy, not only instances that EC2 reports as stopped.

  3. 03Why leave desired_capacity out when an autoscaler changes the size?

    Otherwise each apply resets the size and fights the scaler. Leave it out or ignore changes to it.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark