Skip to Content
Cloud Engineering Academy
2. AWS Networking & Infrastructure

Elastic Load Balancing: ALB, NLB and Gateway Load Balancer

Choose between Application, Network and Gateway Load Balancers, configure listeners, rules, target groups, health checks and TLS termination, make ASP.NET Core behave correctly behind a load balancer, and audit load balancers with C#.

intermediateโฑ 1 h 35 min๐ŸŸก Low costSAA-C03SOA-C03SCS-C03

Assumes: AWS CLI v2 ยท AWS SDK for .NET v4 (AWSSDK.ElasticLoadBalancingV2 4.1.0.2) ยท .NET 10 LTS / ASP.NET Core 10 ยท CDK v2 (Amazon.CDK.Lib 2.277.0) ยท Terraform AWS provider v6 ยท Region us-east-1. Verified against official sources on 2026-11-18.

Learning objectives

By the end of this lesson you can:

  • Choose between an Application Load Balancer (ALB), Network Load Balancer (NLB) and Gateway Load Balancer (GWLB) for a requirement, and say why.
  • Explain listeners, rules, target groups, target types and health checks, and how they fit together.
  • Terminate TLS on a load balancer with an ACM certificate and a modern security policy, and describe mutual TLS options.
  • Configure ASP.NET Core for life behind a load balancer: forwarded headers, health endpoints and graceful shutdown that matches the deregistration delay.
  • Deploy a cheap internet-facing ALB with a fixed response, inspect it, delete it within the hour โ€” and audit any load balancer with a C# tool.

Prerequisites

Why this matters in banking

The load balancer is usually the only component of a banking workload that faces the internet. Everything behind it โ€” containers, databases, queues โ€” sits in private or isolated subnets. That makes it the front door for availability (customers can't log in if it's misconfigured), for security (TLS policy, WAF, header handling, what's exposed) and for evidence (access logs show every request when an investigator asks "who called this endpoint at 03:14?").

Common incidents trace back to load balancer details: health checks that hit a page requiring authentication, so every target is marked unhealthy; deployments that drop in-flight payment requests because the app shuts down before the load balancer stops sending it traffic; audit logs showing the load balancer's IP instead of the customer's because forwarded headers weren't configured; a TLS policy that still allows TLS 1.0 flagged in a penetration test. Each is easy to avoid once you know how the pieces work.

The idea in plain language

A load balancer receives connections from clients and spreads them across a group of healthy servers (targets). If a target fails its health check, it stops receiving traffic. Elastic Load Balancing (ELB) is AWS's managed load-balancing service; it scales itself and runs across several AZs.

Analogy: the load balancer is the bank's reception desk. Listeners are the entrances it watches (the HTTPS door on port 443). Rules are the receptionist's instructions: "mortgage questions to the second floor, card disputes to the third". Target groups are the teams on each floor, and health checks are the receptionist phoning each desk every 30 seconds โ€” no answer twice in a row and that desk gets no more customers until it answers five times in a row.

The three load balancers

Application Load BalancerNetwork Load BalancerGateway Load Balancer
OSI layer7 (HTTP/HTTPS, gRPC, WebSockets)4 (TCP, UDP, TLS, TCP_UDP)3 (IP packets, GENEVE port 6081)
Routes onHost, path, headers, method, query string, source IPPort and protocolAll traffic to appliances
TargetsInstances, IPs, Lambda functions (and ALB-type targets for NLB only)Instances, IPs, an ALBInstances, IPs of virtual appliances
Static IPsNo (DNS name only)Yes โ€” one per AZ; Elastic IPs for internet-facingNo (reached through GWLB endpoints)
Client source IP at targetIn X-Forwarded-For headerPreserved (for instance/most IP targets)Preserved (transparent)
TLSTerminates HTTPS; mTLS verify/passthroughTerminates TLS or passes TCP throughDoesn't terminate
Security groupsYesYes (must be chosen at creation)No
AWS WAFYesNoNo
Cross-zone load balancingOn by defaultOff by defaultOff by default
PrivateLink endpoint service frontNoYesYes (GWLB endpoints)
Price in us-east-1USD 0.0225/h + USD 0.008 per LCU-hourUSD 0.0225/h + USD 0.006 per NLCU-hourUSD 0.0125/h + USD 0.004 per GLCU-hour
Use it forWeb apps and REST APIsNon-HTTP protocols, static IPs, extreme throughput, PrivateLinkFirewalls, IDS/IPS, deep packet inspection

The original Classic Load Balancer is legacy; don't use it for new work.

How a request flows through an ALB

  1. The client resolves the ALB's DNS name (or your alias record) and connects to a load balancer node in one of the enabled AZs.
  2. The listener (protocol + port, e.g. HTTPS:443) accepts it and, for HTTPS, terminates TLS with a certificate from AWS Certificate Manager (ACM).
  3. Rules are evaluated in priority order; the first match picks an action: forward to target group(s) (optionally weighted), redirect, fixed response, or authenticate (OIDC/Cognito) then forward.
  4. The node opens (or reuses) a connection to a healthy target in the chosen target group, adding X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Port headers.

Target groups and health checks

A target group has a protocol, a port, a target type (instance, ip, lambda, or alb for NLB) and a health check. ALB health check defaults (verified 2026-11-18):

SettingDefault (instance/ip targets)
Protocol / pathHTTP, /
Interval30 seconds
Timeout5 seconds
Healthy threshold5 consecutive successes
Unhealthy threshold2 consecutive failures
Success codes200

Two behaviours to remember: if every target in a group is unhealthy, the ALB fails open and sends traffic to all of them anyway; and when a target is deregistered, the deregistration delay (default 300 seconds) lets in-flight requests finish before the connection is closed.

TLS termination and security policies

The listener holds an ACM certificate (free for use with ELB, renewed automatically) and a security policy that decides which TLS versions and ciphers are allowed. Prefer a TLS 1.3 + 1.2 policy such as ELBSecurityPolicy-TLS13-1-2-2021-06; newer policies with post-quantum hybrid key exchange are also available โš  VERIFY current policy names in the ELB documentation. Traffic from the load balancer to targets can be HTTP (inside the VPC) or HTTPS for end-to-end encryption โ€” many bank standards require the latter.

Mutual TLS (mTLS) on an ALB has two modes: verify (the ALB checks client certificates against a trust store you upload, then passes certificate details in headers) and passthrough (the ALB forwards the client certificate chain in a header for your app to verify). Open Banking APIs commonly use mTLS for partner authentication โ€” see certificates, TLS and mTLS.

Pricing: what is an LCU?

ALBs bill per hour plus per Load Balancer Capacity Unit, measured on four dimensions and charged on whichever is highest each hour. One LCU = 25 new connections per second, or 3,000 active connections per minute (1,500 with mTLS), or 1 GB per hour processed for EC2/container/IP targets (0.4 GB for Lambda), or 1,000 rule evaluations per second (first 10 rules free). An idle ALB costs about USD 16.43 a month (0.0225 ร— 730) plus at least some LCU charges โ€” the "idle load balancer" is a classic forgotten cost, along with the public IPv4 addresses of internet-facing load balancers (USD 0.005 per address per hour, one per AZ node โš  VERIFY how many addresses an ALB holds at low load).

What problem ELB solves

  • Availability: spreads traffic over targets in several AZs and routes around unhealthy ones.
  • Scalability: scales its own capacity with demand; with Auto Scaling or ECS service autoscaling behind it, the whole tier grows and shrinks.
  • Security at the edge: TLS termination with managed certificates, modern TLS policies, AWS WAF (ALB), security groups, access logs.
  • Deployment safety: weighted target groups and deregistration delay enable blue/green and canary releases without dropped requests.

Sharp edges:

  • An ALB needs subnets in at least two AZs. Internet-facing ALBs go in public subnets; internal ALBs in private ones.
  • ALB IP addresses change. Never allow-list them; use the DNS name, an alias record, or put an NLB (static IPs) in front of the ALB when a partner insists on fixed IPs.
  • Sudden traffic spikes (a marketing push, salary day) can outpace automatic scaling; ALB LCU capacity reservation lets you pre-provision capacity for known events โš  VERIFY current feature name and pricing.
  • Idle timeout (ALB default 60 seconds) closes idle connections. Keep the app's keep-alive timeout longer than the ALB's (Kestrel's default is longer) so the ALB never sends a request on a connection the app just closed.

Microsoft / Azure comparison

You know (Microsoft/Azure)AWS equivalentWhat's different
Application Gateway (v2)Application Load BalancerSimilar L7 routing; ALB integrates AWS WAF and has Lambda targets
Application Gateway WAFAWS WAF web ACL on the ALBWAF is a separate service attached to the ALB
Azure Load Balancer (Standard)Network Load BalancerNLB can terminate TLS and front PrivateLink services
Gateway Load Balancer (Azure)Gateway Load Balancer (AWS)Same idea; AWS uses GENEVE and GWLB endpoints in route tables
Backend poolTarget groupTarget type is fixed per group (instance, ip, lambda, alb)
Health probeTarget group health checkUnhealthy/healthy thresholds are counts of consecutive checks
Listener + routing rulesListener + rules (priority ordered)ALB rules support weighted forwarding to several target groups
Key Vault certificates on App GatewayACM certificates on the listenerACM public certificates are free and auto-renew when DNS-validated
Front DoorAmazon CloudFront (+ ALB origin) / AWS Global AcceleratorGlobal entry points are separate services in AWS
UseForwardedHeaders behind App GatewaySame middleware behind ALBClear KnownNetworks/KnownProxies or add the VPC CIDR

Architecture

Security-boundary view: the ALB is the trust boundary between the internet and the application. TLS ends here (or is re-encrypted to targets), WAF inspects requests here, and the ALB's security group is the only one with an internet source. Targets accept traffic only from the ALB's security group, so nothing can bypass the ALB. Access logs (to an S3 bucket with retention and restricted access) and CloudWatch metrics give the evidence trail. The NLB in front exists only for the partner who requires fixed IPs.

Step-by-step implementation

Prerequisites in place

Public subnets in two AZs routed to the IGW (lessons 4โ€“5), and hl-m02-alb-sg allowing TCP 80 from 0.0.0.0/0 (lesson 7). If you deleted them, recreate them or use the lab's Terraform.

Create an internet-facing ALB (billing starts)

hl-m02-alb in both public subnets with hl-m02-alb-sg. Note the time โ€” you will delete it within the hour.

Add a listener with a fixed response

HTTP:80 with a default action fixed-response 200 "Harbourline learning ALB". No targets are needed, so there is nothing else to pay for.

Turn on safe attributes

routing.http.drop_invalid_header_fields.enabled = true (drop malformed headers rather than pass them to your app) and look at the other attributes: idle timeout, deletion protection, access logs.

Test, audit, delete

curl the DNS name, run the C# auditor (expect findings for plain HTTP and access logs off), then delete the listener and load balancer.

AWS Console instructions

  • EC2 โ†’ Load Balancers โ†’ Create load balancer โ†’ Application Load Balancer โ†’ Create. Name hl-m02-alb; Scheme: Internet-facing; IP address type: IPv4; VPC: hl-m02-vpc; Mappings: tick us-east-1a and us-east-1b and pick the public subnet in each; Security groups: remove default, choose hl-m02-alb-sg.
  • Listeners and routing: HTTP : 80 โ†’ Default action: you must pick a target group in the wizard; create an empty target group hl-m02-tg (target type IP, HTTP 8080, health check path /health/ready) โ€” or create the ALB with the CLI, which allows a fixed-response default action.
  • After creation: Listeners tab โ†’ select the listener โ†’ Manage rules / Edit listener to change the default action to Return fixed response (200, text/plain, body text).
  • Attributes tab โ†’ Edit: Drop invalid header fields on; Deletion protection (off for the lab, on in production); Access logs โ†’ S3 bucket.
  • Integrations tab shows AWS WAF association; Monitoring tab shows request count, target response time, 5XX counts and LCU usage.
  • Delete: select the ALB โ†’ Actions โ†’ Delete load balancer; then Target groups โ†’ delete hl-m02-tg.

AWS CLI

$p = "--profile", "learn-sandbox", "--region", "us-east-1"
$tags = "Key=Project,Value=cea-lab Key=Lab,Value=m02-secure-vpc Key=Environment,Value=learn Key=Owner,Value=alex"
$vpcId = aws ec2 describe-vpcs --filters Name=tag:Name,Values=hl-m02-vpc @p --query "Vpcs[0].VpcId" --output text
$publicSubnets = (aws ec2 describe-subnets @p --filters Name=vpc-id,Values=$vpcId Name=tag:Tier,Values=public --query "Subnets[].SubnetId" --output text) -split "\s+"
$albSg = aws ec2 describe-security-groups @p --filters Name=vpc-id,Values=$vpcId Name=group-name,Values=hl-m02-alb-sg --query "SecurityGroups[0].GroupId" --output text

# 1. Internet-facing ALB in both public subnets (about USD 0.0225/hour + LCUs + public IPv4)
$albArn = aws elbv2 create-load-balancer --name hl-m02-alb --type application --scheme internet-facing `
  --subnets $publicSubnets --security-groups $albSg --tags ($tags -split " ") @p `
  --query "LoadBalancers[0].LoadBalancerArn" --output text
aws elbv2 wait load-balancer-available --load-balancer-arns $albArn @p

# 2. Listener with a fixed response: no targets, nothing else to pay for
$listenerArn = aws elbv2 create-listener --load-balancer-arn $albArn --protocol HTTP --port 80 @p `
  --default-actions '[{"Type":"fixed-response","FixedResponseConfig":{"StatusCode":"200","ContentType":"text/plain","MessageBody":"Harbourline learning ALB"}}]' `
  --query "Listeners[0].ListenerArn" --output text

# 3. Safer attributes
aws elbv2 modify-load-balancer-attributes --load-balancer-arn $albArn @p `
  --attributes Key=routing.http.drop_invalid_header_fields.enabled,Value=true

# 4. Test it (may take a minute for DNS)
$dns = aws elbv2 describe-load-balancers --load-balancer-arns $albArn @p --query "LoadBalancers[0].DNSName" --output text
curl.exe -s -i "http://$dns/"

# 5. A target group as you'd use for ECS tasks (IP targets on 8080, ASP.NET Core readiness endpoint)
$tgArn = aws elbv2 create-target-group --name hl-m02-tg --protocol HTTP --port 8080 --target-type ip --vpc-id $vpcId `
  --health-check-path /health/ready --health-check-interval-seconds 15 --healthy-threshold-count 3 --unhealthy-threshold-count 2 `
  --matcher HttpCode=200 --tags ($tags -split " ") @p --query "TargetGroups[0].TargetGroupArn" --output text
aws elbv2 modify-target-group-attributes --target-group-arn $tgArn @p --attributes Key=deregistration_delay.timeout_seconds,Value=30

# 6. Production listener shape (needs an ACM certificate for your domain โ€” not run in the lab)
# aws elbv2 create-listener --load-balancer-arn $albArn --protocol HTTPS --port 443 `
#   --certificates CertificateArn=arn:aws:acm:us-east-1:111122223333:certificate/โ€ฆ `
#   --ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06 `
#   --default-actions Type=forward,TargetGroupArn=$tgArn @p
# ...and change the HTTP:80 listener to redirect:
#   --default-actions '[{"Type":"redirect","RedirectConfig":{"Protocol":"HTTPS","Port":"443","StatusCode":"HTTP_301"}}]'

# Inspect
aws elbv2 describe-listeners --load-balancer-arn $albArn @p --query "Listeners[].[Protocol,Port,DefaultActions[0].Type]" --output table
aws elbv2 describe-load-balancer-attributes --load-balancer-arn $albArn @p --output table

In PowerShell, single-quoted JSON is passed to the CLI as-is; this avoids the escaping problems double quotes cause on Windows.

Infrastructure as Code

AlbStack.cs
using Amazon.CDK;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
using Constructs;

namespace Harbourline.Networking.Examples;

public sealed class AlbStack : Stack
{
    public AlbStack(Construct scope, string id, IVpc vpc, ISecurityGroup albSg, IStackProps? props = null)
        : base(scope, id, props)
    {
        var alb = new ApplicationLoadBalancer(this, "Alb", new ApplicationLoadBalancerProps
        {
            Vpc = vpc,
            LoadBalancerName = "hl-m02-alb",
            InternetFacing = true,
            VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PUBLIC },
            SecurityGroup = albSg,
            DropInvalidHeaderFields = true,
            DeletionProtection = false, // LEARNING: true in production
        });

        // LEARNING SHORTCUT: HTTP with a fixed response. Production: HTTPS listener + redirect (below).
        var http = alb.AddListener("Http", new BaseApplicationListenerProps
        {
            Port = 80,
            Open = false, // the security group is managed explicitly
            DefaultAction = ListenerAction.FixedResponse(200, new FixedResponseOptions
            {
                ContentType = "text/plain",
                MessageBody = "Harbourline learning ALB",
            }),
        });

        var targets = new ApplicationTargetGroup(this, "AccountsApi", new ApplicationTargetGroupProps
        {
            Vpc = vpc,
            TargetGroupName = "hl-m02-tg",
            TargetType = TargetType.IP,
            Protocol = ApplicationProtocol.HTTP,
            Port = 8080,
            DeregistrationDelay = Duration.Seconds(30),
            HealthCheck = new Amazon.CDK.AWS.ElasticLoadBalancingV2.HealthCheck
            {
                Path = "/health/ready",
                Interval = Duration.Seconds(15),
                HealthyThresholdCount = 3,
                UnhealthyThresholdCount = 2,
                HealthyHttpCodes = "200",
            },
        });

        http.AddTargetGroups("AccountsRule", new AddApplicationTargetGroupsProps
        {
            Priority = 10,
            Conditions = [ListenerCondition.PathPatterns(["/accounts/*"])],
            TargetGroups = [targets],
        });

        // Production shape (requires an ACM certificate):
        // alb.AddListener("Https", new BaseApplicationListenerProps {
        //     Port = 443, Certificates = [ListenerCertificate.FromArn(certArn)],
        //     SslPolicy = SslPolicy.TLS13_RES, DefaultTargetGroups = [targets] });
        // alb.AddRedirect();  // HTTP 80 -> HTTPS 443

        _ = new CfnOutput(this, "AlbDns", new CfnOutputProps { Value = alb.LoadBalancerDnsName });
    }
}

HealthCheck is fully qualified because Amazon.CDK.AWS.EC2 also defines a HealthCheck type. The CDK SslPolicy enum names differ from the AWS policy names โš  VERIFY which enum value maps to the policy your standard requires.

Complete code

1. ASP.NET Core behind an ALB

Three things every .NET service behind a load balancer needs: correct client IP and scheme from forwarded headers, liveness and readiness endpoints for health checks, and a shutdown that lets in-flight requests finish.

Program.cs (Harbourline.Accounts.Api)
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Diagnostics.HealthChecks;

var builder = WebApplication.CreateBuilder(args);

// 1. Trust X-Forwarded-For / X-Forwarded-Proto from the load balancer only.
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
    options.KnownIPNetworks.Clear();
    options.KnownProxies.Clear();
    // The ALB's nodes have private IPs inside the VPC's public subnets.
    options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(builder.Configuration["Network:ProxyCidr"] ?? "10.20.0.0/18"));
    options.ForwardLimit = 1;
});

// 2. Health checks: "live" = process is up; "ready" = dependencies reachable.
builder.Services.AddHealthChecks()
    .AddCheck("self", () => HealthCheckResult.Healthy(), tags: ["live"])
    .AddCheck("database", () => HealthCheckResult.Healthy("replace with a real DB check"), tags: ["ready"]);

// 3. Allow in-flight requests to finish after SIGTERM (keep below the target group's deregistration delay).
builder.Services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(25));

var app = builder.Build();

app.UseForwardedHeaders();

app.MapHealthChecks("/health/live", new() { Predicate = c => c.Tags.Contains("live") });
app.MapHealthChecks("/health/ready", new() { Predicate = c => c.Tags.Contains("ready") });

app.MapGet("/accounts/whoami", (HttpContext ctx) => Results.Ok(new
{
    clientIp = ctx.Connection.RemoteIpAddress?.ToString(),
    scheme = ctx.Request.Scheme,
    correlationId = ctx.Request.Headers["X-Amzn-Trace-Id"].ToString(),
}));

app.Run();

2. Load balancer auditor

Checks every ALB and NLB in the Region for plain-HTTP listeners that don't redirect, outdated TLS policies, missing access logs, deletion protection off, invalid-header dropping off (ALB), and unhealthy targets.

ElbAudit.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="AWSSDK.ElasticLoadBalancingV2" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSO" Version="4.1.0.2" />
    <PackageReference Include="AWSSDK.SSOOIDC" Version="4.1.0.2" />
  </ItemGroup>
</Project>
Program.cs
using Amazon;
using Amazon.ElasticLoadBalancingV2;
using Amazon.ElasticLoadBalancingV2.Model;

// Usage:  $env:AWS_PROFILE = "learn-sandbox"; dotnet run
using var elb = new AmazonElasticLoadBalancingV2Client(RegionEndpoint.USEast1);
var findings = 0;

await foreach (var lb in elb.Paginators.DescribeLoadBalancers(new DescribeLoadBalancersRequest()).LoadBalancers)
{
    if (lb.Type == LoadBalancerTypeEnum.Gateway)
    {
        continue; // GWLBs have no TLS listeners or HTTP attributes to check
    }

    Console.WriteLine($"{lb.LoadBalancerName} ({lb.Type}, {lb.Scheme}) {lb.DNSName}");
    var problems = new List<string>();
    var isAlb = lb.Type == LoadBalancerTypeEnum.Application;
    var internetFacing = lb.Scheme == LoadBalancerSchemeEnum.InternetFacing;

    // Listeners: plain HTTP must redirect; TLS listeners need a TLS 1.2+ policy.
    var listeners = await elb.DescribeListenersAsync(new DescribeListenersRequest { LoadBalancerArn = lb.LoadBalancerArn });
    foreach (var listener in listeners.Listeners ?? [])
    {
        var actions = listener.DefaultActions ?? [];
        if (listener.Protocol == ProtocolEnum.HTTP && internetFacing &&
            !actions.Any(a => a.Type == ActionTypeEnum.Redirect && a.RedirectConfig?.Protocol == "HTTPS"))
        {
            problems.Add($"listener HTTP:{listener.Port} serves plain HTTP to the internet (no redirect to HTTPS)");
        }

        if ((listener.Protocol == ProtocolEnum.HTTPS || listener.Protocol == ProtocolEnum.TLS) &&
            listener.SslPolicy is { } policy && !policy.Contains("TLS13", StringComparison.Ordinal) && !policy.Contains("TLS-1-2", StringComparison.Ordinal))
        {
            problems.Add($"listener {listener.Protocol}:{listener.Port} uses policy {policy} โ€” prefer a TLS 1.3/1.2 policy");
        }
    }

    // Attributes: logs, deletion protection, header hygiene.
    var attributes = (await elb.DescribeLoadBalancerAttributesAsync(new DescribeLoadBalancerAttributesRequest
    {
        LoadBalancerArn = lb.LoadBalancerArn,
    })).Attributes?.ToDictionary(a => a.Key, a => a.Value) ?? [];

    if (attributes.GetValueOrDefault("access_logs.s3.enabled") != "true") problems.Add("access logs are off");
    if (attributes.GetValueOrDefault("deletion_protection.enabled") != "true") problems.Add("deletion protection is off");
    if (isAlb && attributes.GetValueOrDefault("routing.http.drop_invalid_header_fields.enabled") != "true")
    {
        problems.Add("invalid header fields are passed to targets (drop_invalid_header_fields is off)");
    }

    // Target health per target group.
    var groups = await elb.DescribeTargetGroupsAsync(new DescribeTargetGroupsRequest { LoadBalancerArn = lb.LoadBalancerArn });
    foreach (var tg in groups.TargetGroups ?? [])
    {
        var health = await elb.DescribeTargetHealthAsync(new DescribeTargetHealthRequest { TargetGroupArn = tg.TargetGroupArn });
        var descriptions = health.TargetHealthDescriptions ?? [];
        var healthy = descriptions.Count(d => d.TargetHealth?.State == TargetHealthStateEnum.Healthy);
        Console.WriteLine($"    target group {tg.TargetGroupName}: {healthy}/{descriptions.Count} healthy, health check {tg.HealthCheckProtocol} {tg.HealthCheckPath}");

        foreach (var d in descriptions.Where(d => d.TargetHealth?.State != TargetHealthStateEnum.Healthy))
        {
            Console.WriteLine($"      {d.Target?.Id}:{d.Target?.Port} {d.TargetHealth?.State} {d.TargetHealth?.Reason} {d.TargetHealth?.Description}");
        }

        if (descriptions.Count > 0 && healthy == 0) problems.Add($"target group {tg.TargetGroupName} has NO healthy targets (ALB fails open)");
    }

    foreach (var p in problems)
    {
        Console.WriteLine($"    FINDING: {p}");
    }

    findings += problems.Count;
}

Console.WriteLine(findings == 0 ? "No findings." : $"{findings} finding(s).");
return findings == 0 ? 0 : 1;

Expected output for the lab ALB:

hl-m02-alb (application, internet-facing) hl-m02-alb-123456789.us-east-1.elb.amazonaws.com
    target group hl-m02-tg: 0/0 healthy, health check HTTP /health/ready
    FINDING: listener HTTP:80 serves plain HTTP to the internet (no redirect to HTTPS)
    FINDING: access logs are off
    FINDING: deletion protection is off
3 finding(s).

Code explained line by line

ASP.NET Core:

  1. ForwardedHeaders.XForwardedFor | XForwardedProto โ€” the ALB connects to your app from its own IP over HTTP; the real client IP and original scheme arrive in these headers. Without the middleware, logs and rate limits see the ALB's address, and Request.Scheme is http, which breaks redirect URLs and cookie Secure flags.
  2. KnownIPNetworks.Clear() then Add(...) โ€” by default ASP.NET Core only trusts loopback proxies and ignores the headers. Trust only the subnets where load balancer nodes live (the public tier's /18), never "any", or clients could spoof their IP. (KnownIPNetworks uses System.Net.IPNetwork; older code uses KnownNetworks.)
  3. ForwardLimit = 1 โ€” process exactly one hop (the ALB).
  4. Tagged health checks โ€” /health/live says the process runs; /health/ready says it can serve (database reachable). Point the target group at ready. Keep it cheap and unauthenticated, and don't make it depend on non-critical services, or one slow dependency marks every target unhealthy.
  5. HostOptions.ShutdownTimeout = 25 s โ€” on deployment ECS sends SIGTERM after deregistering the task; the ALB stops sending new requests and waits up to the deregistration delay (30 s here) for in-flight ones. Shutdown must be shorter than that delay.
  6. X-Amzn-Trace-Id โ€” the ALB adds this header to every request; logging it lets you join app logs with ALB access logs.

Auditor:

  1. elb.Paginators.DescribeLoadBalancers(...) โ€” ALBs, NLBs and GWLBs all live in the ELBv2 API (AWSSDK.ElasticLoadBalancingV2).
  2. LoadBalancerTypeEnum, LoadBalancerSchemeEnum, ProtocolEnum, ActionTypeEnum, TargetHealthStateEnum โ€” SDK v4 constant classes, compared with ==.
  3. HTTP listener check โ€” compliant only if the default action is a redirect to HTTPS. Fixed responses and forwards on plain HTTP to the internet are findings.
  4. SslPolicy check โ€” a simple name heuristic (TLS13 or TLS-1-2 in the policy name). It's a prompt for review, not a cryptographic assessment.
  5. DescribeLoadBalancerAttributes โ†’ dictionary โ€” attributes are key/value strings such as access_logs.s3.enabled = "true".
  6. DescribeTargetHealth โ€” Reason and Description explain unhealthy targets (Target.ResponseCodeMismatch, Target.Timeout, โ€ฆ), which is the first thing to read during an incident.

Security considerations

  • HTTPS only for internet-facing listeners, with HTTP redirecting to HTTPS, a TLS 1.3/1.2 security policy and ACM certificates. Consider HTTPS to targets as well if your standard requires encryption in transit inside the VPC.
  • AWS WAF on every internet-facing ALB (managed rule groups, rate-based rules) โ€” see AWS WAF and Shield.
  • Targets accept traffic only from the load balancer's security group. Nothing should be reachable around the load balancer.
  • Access logs to an S3 bucket with lifecycle retention, restricted read access and Object Lock if your record-keeping policy requires it. They contain client IPs โ€” personal data under GDPR โ€” so define retention with your data-protection team.
  • Drop invalid header fields, and consider desync mitigation mode (default "defensive") to protect against HTTP request smuggling.
  • Deletion protection on production load balancers, so a stray terraform destroy or console click can't take down the customer front door.
  • Don't expose internal ALBs by accident: internal scheme for service-to-service traffic, placed in private subnets.

โš  Learning shortcut โ€” not for production

The lab ALB serves plain HTTP on port 80 with a fixed response, no WAF, no access logs and deletion protection off โ€” so it can be created and deleted in minutes for a few cents. In production at Harbourline the customer-facing ALB has an HTTPS listener with an ACM certificate and a TLS 1.3/1.2 policy, HTTP โ†’ HTTPS redirect, AWS WAF with managed rules and rate limits, access logs to a central log-archive account, deletion protection, and (for partner APIs) mTLS in verify mode with a trust store of partner CAs.

Banking use case

Mobile-banking API (ALB). An internet-facing ALB in three AZs fronts the Accounts API and Payments API on ECS Fargate. Path rules send /accounts/* and /payments/* to separate target groups; the payments rule forwards to payments-blue and payments-green with weights for canary releases. WAF blocks common attacks and rate-limits login endpoints. Route 53 failover alias records point at this ALB and its twin in eu-west-1.

Card-network link (NLB). The card scheme requires a fixed set of IP addresses and raw TLS. An NLB with Elastic IPs in each AZ terminates TLS with the scheme's required policy and forwards TCP to the authorisation service, preserving client IPs so security groups can restrict sources to the scheme's ranges.

Partner Open Banking API (NLB + PrivateLink). For partners with private connectivity, an internal NLB fronts the API as a VPC endpoint service (VPC endpoints and PrivateLink); the NLB's target is the internal ALB, so the same WAF-protected routing rules apply.

Inspection (GWLB). In the central inspection VPC, a Gateway Load Balancer spreads traffic across a fleet of third-party firewall appliances; workload route tables send traffic to GWLB endpoints. Many banks now use AWS Network Firewall for this instead (covered later in this module).

Common mistakes

  • Health check path requires authentication or hits a slow dependency โ†’ all targets unhealthy โ†’ a cheap, unauthenticated /health/ready.
  • App shuts down before deregistration completes โ†’ 502s during every deployment โ†’ shutdown timeout shorter than deregistration delay; handle SIGTERM.
  • Forwarded headers not configured โ†’ client IP is the ALB's; redirects go to http:// โ†’ UseForwardedHeaders with trusted networks.
  • Allow-listing ALB IPs โ†’ they change โ†’ DNS name, alias records, or NLB with Elastic IPs in front.
  • Internet-facing ALB in private subnets โ†’ unreachable โ†’ internet-facing goes in public subnets.
  • Idle ALBs left running in dev โ†’ about USD 16+ per month each plus public IPv4 โ†’ delete after use; tag and report.
  • App keep-alive shorter than ALB idle timeout โ†’ intermittent 502s โ†’ app keep-alive longer than the ALB's idle timeout.

Troubleshooting

SymptomLikely causeFix
502 Bad GatewayTarget closed the connection, returned a malformed response, or crashedCheck app logs; keep-alive timeout longer than ALB idle timeout; ALB access logs show target_status_code
503 Service UnavailableNo registered targets in the target groupRegister targets; check ECS service events
504 Gateway TimeoutTarget didn't respond within the idle timeout, or SG/NACL blocks ALB โ†’ targetCheck target SG allows the ALB SG on the target port; slow requests
Targets unhealthy with Target.TimeoutHealth check can't reach the target (SG, NACL, wrong port)Allow health-check port from the ALB SG
Targets unhealthy with Target.ResponseCodeMismatchHealth endpoint returns 301/401/500Fix the path, or the matcher; don't redirect health checks to HTTPS
ALB DNS name doesn't respondInternet-facing ALB in subnets without an IGW route, or SG missing inbound rulePublic subnets + IGW route + SG inbound 80/443
Client IPs in app logs are 10.20.x.xForwarded headers not processedUseForwardedHeaders with the right KnownIPNetworks
ValidationError: At least two subnets in two different Availability ZonesOnly one subnet chosenOne public subnet per AZ, at least two

Cost and cleanup

Cost label: credits. An ALB for 30 minutes: 0.5 ร— USD 0.0225 โ‰ˆ USD 0.011, plus minimal LCUs, plus public IPv4 addresses for its nodes (USD 0.005 per address per hour) โ€” about USD 0.02 in total. Left running for a month: roughly USD 16.43 plus LCUs and IPv4 โ‰ˆ USD 25+. Free alternative: synthesise the CDK stack or run terraform plan without applying, and run the ASP.NET Core app locally with UseForwardedHeaders and a fake X-Forwarded-For header from curl.

$p = "--profile", "learn-sandbox", "--region", "us-east-1"

# Listener, then load balancer, then target group (a target group in use can't be deleted)
aws elbv2 delete-listener --listener-arn $listenerArn @p
aws elbv2 delete-load-balancer --load-balancer-arn $albArn @p
aws elbv2 wait load-balancers-deleted --load-balancer-arns $albArn @p
aws elbv2 delete-target-group --target-group-arn $tgArn @p

# Nothing left?
aws elbv2 describe-load-balancers @p --query "LoadBalancers[].LoadBalancerName"
aws elbv2 describe-target-groups @p --query "TargetGroups[].TargetGroupName"
aws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=cea-lab @p --query "ResourceTagMappingList[].ResourceARN"

Exercises

  • ๐ŸŸข Guided: Create the fixed-response ALB with the CLI, curl it, set drop_invalid_header_fields, run the auditor (three findings), and delete everything within 30 minutes.
  • ๐ŸŸก Challenge: Add a second listener rule that returns a fixed 403 for any request whose path starts with /admin unless the source IP is in a CIDR you choose (use a source-ip condition with a higher priority allow rule). Show both responses with curl, then explain why this is not a substitute for authentication.
  • ๐Ÿ”ด Live problem: "Every deployment of the Payments API produces 20โ€“40 502 errors for about 15 seconds, and a few customers see 'payment status unknown'. Deployments are rolling ECS updates behind an ALB. Deregistration delay is 300 s. The app is ASP.NET Core 10." Find the likely causes and propose fixes.

Assignment

Write an ALB standard for Harbourline (one page): required listeners and TLS policy, WAF, attributes, logging and retention, health-check conventions for .NET services, deregistration delay and shutdown timeout rules, and the auditor checks that enforce it. Add the auditor to your repository as tools/elb-audit/.

Solutions

Knowledge check

Interview questions

  • "ALB or NLB?" โ€” ALB for HTTP APIs: L7 routing, WAF, OIDC, Lambda targets. NLB for non-HTTP, static IPs, preserved client IPs, very high throughput, or PrivateLink. Both if you need static IPs and L7 features.
  • "How do you do zero-downtime deployments behind an ALB?" โ€” Readiness health checks, deregistration delay sized to request duration, graceful shutdown shorter than it, rolling or blue/green with weighted target groups, idempotent writes.
  • "How do you secure an internet-facing ALB?" โ€” HTTPS only with a modern policy, redirect HTTP, WAF, SG from the internet only on 443, targets only from the ALB SG, access logs, drop invalid headers, deletion protection.
  • "What's an LCU?" โ€” The ALB's usage unit: the highest of new connections, active connections, processed bytes and rule evaluations each hour.

Certification practice

Completion checklist

  • I can choose ALB, NLB or GWLB for a scenario and justify it
  • I can explain listeners, rules, target groups and health-check thresholds
  • I created a fixed-response ALB, inspected it and deleted it (or synthesised the IaC)
  • I configured forwarded headers, health endpoints and graceful shutdown in ASP.NET Core
  • I ran the ELB auditor and confirmed no load balancers or target groups remain

Key takeaways

  • ALB = HTTP routing, WAF, OIDC, Lambda targets; NLB = L4, static IPs, source IP preservation, PrivateLink; GWLB = transparent appliance insertion.
  • Listeners โ†’ rules โ†’ target groups โ†’ health checks; an all-unhealthy ALB target group fails open.
  • Terminate TLS with ACM certificates and a TLS 1.3/1.2 policy; redirect HTTP; add WAF; log access.
  • In .NET: UseForwardedHeaders with trusted networks, readiness health checks, and shutdown shorter than the deregistration delay.
  • Load balancers bill hourly plus capacity units and public IPv4 โ€” delete idle ones.

Further reading

Next: the remaining lessons in this module โ€” private networking patterns, VPC peering and Transit Gateway, hybrid connectivity and more โ€” are listed in the module overview.

Independent learning resource โ€” not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.

On this page