TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท aws ยท cloud ยท networking ยท load balancing ยท alb ยท nlb

Elastic Load Balancing: ALB and NLB

AWS's managed load balancers. Listeners accept connections, rules pick a target group, and health checks keep traffic on healthy targets; the Application Load Balancer routes HTTP by path, host and header, while the Network Load Balancer forwards TCP, UDP and TLS with static IPs and the client's own address.

16 min7 animations

๐Ÿ“š Builds on๐ŸŽก Load balancing๐Ÿ˜๏ธ Amazon VPC: subnets, route tables and security groups

๐Ÿ–จ๏ธ Cheat sheet

The arrivals hall

Picture a big airport where passengers land and then need to reach their next gate. They don't wander about looking for it. They come into the arrivals hall through a numbered door, and someone there sends them on.

Behind the hall are the gates. Each gate is for one kind of journey, and each has several desks with staff, so one desk never gets swamped. A gate with its desks is called a target group: the staff at it all do the same job, and any of them can help.

At the door stands a guide with a card of instructions. The guide looks at each passenger's ticket, finds the first line on the card that fits, and walks the passenger to a desk at that gate. If no line fits, the card's last line says where everyone else goes. The answer from the desk comes back through the guide to the passenger.

The airport runs the hall for you. You only say which doors are open, what the card says and which desks belong to which gate. If more passengers turn up, the airport makes the hall bigger by itself.

Listeners, rules and target groups

Elastic Load Balancing (ELB) is AWS's managed load balancing service. You don't run the load balancer's machines; AWS scales them with your traffic and spreads them across the Availability Zones you choose in your VPC. Every load balancer is built from the same parts:

PartWhat it is
ListenerA protocol and port the load balancer accepts connections on, such as HTTPS:443
RuleOn an ALB listener: conditions plus an action, checked in priority order, lowest number first
Default ruleThe action taken when no other rule matches; it has no conditions
Target groupA set of targets that receive traffic, with one protocol, port and health check
TargetAn EC2 instance, an IP address, a Lambda function (ALB) or an ALB (NLB)

A client resolves the load balancer's DNS name, connects to a listener, and the matching rule's action (for an ALB: forward, redirect or fixed-response) decides where it goes. The response travels back through the load balancer. There are three current types: the Application Load Balancer (ALB, layer 7), the Network Load Balancer (NLB, layer 4) and the Gateway Load Balancer (GWLB, layer 3). The older Classic Load Balancer still exists but isn't used for new designs.

Listener, rules and target groups4 steps
๐Ÿ›ฌ Arrivals hall๐Ÿ›ซ Gate A๐Ÿ›ซ Gate B๐ŸงณPassenger๐ŸšชDoor 443๐Ÿง‘โ€โœˆ๏ธGuide๐Ÿง‘โ€๐Ÿ’ผDesk A1๐Ÿง‘โ€๐Ÿ’ผDesk A2๐Ÿ‘ฉโ€๐Ÿ’ผDesk B1๐Ÿ‘ฉโ€๐Ÿ’ผDesk B2
Press play and watch it happen!

The guide who reads tickets

The guide is clever. They read the whole ticket, so the card can say all sorts of things: "tickets for the shop go to gate A", "tickets from the airline's staff go to the staff gate", "tickets stamped 'trial' go to the new gate we're trying out".

Tickets arrive sealed in an envelope, so nobody on the way can peek. The guide wears an official badge from the airport's badge office that proves they really work here, so passengers trust them to open the envelope. After that, the guide can read everything, and the desks behind don't have to open envelopes themselves.

This guide is called the Application Load Balancer. Some passengers hand over a whole family's tickets at once, and some stay at their desk for a long chat. The guide handles both. There's even a gate with no desk at all, just a bell: the guide rings it, a helper appears to deal with that one passenger, and leaves again.

The guide doesn't have a fixed spot. As the hall grows, they move about, so you always ask for them by name.

Application Load Balancer

The ALB works at layer 7 with HTTP and HTTPS listeners. Because it parses each request, its rules can match on:

  • path-pattern (/api/*), host-header (admin.example.com), http-header (X-Beta: on), http-request-method, query-string and source-ip;
  • and act by forwarding to one or more weighted target groups, redirecting (HTTP โ†’ HTTPS) or returning a fixed response. HTTPS listeners can also authenticate users through OIDC or Amazon Cognito first.

TLS termination. An HTTPS listener needs at least one server certificate, usually from AWS Certificate Manager (ACM), which renews the certificates it issues. The ALB decrypts the request, applies the rules, and talks to targets over HTTP or over a new HTTPS connection. With SNI, one listener can serve several certificates, one per hostname. A security policy fixes the TLS versions and ciphers offered to clients.

It also supports HTTP/2 from clients (with HTTPS listeners), gRPC, and WebSockets on both listener types. Targets see the ALB's address as the source, so the client's IP arrives in the X-Forwarded-For header, along with X-Forwarded-Proto and X-Forwarded-Port. Target types are instance, ip and lambda: for a Lambda target the ALB turns the request into an event, invokes the function and turns its result into the response. An ALB needs subnets in at least two Availability Zones. Its node IPs change as it scales, so clients must use its DNS name, never an IP; Route 53 alias records point a domain at it.

ALB rules and TLS termination5 steps
๐ŸงณPassenger๐Ÿชช Official badge๐Ÿง‘โ€โœˆ๏ธGuide๐Ÿ›๏ธShop gate๐Ÿง‘โ€๐Ÿ”งStaff gate๐ŸงชTrial gate๐Ÿ›Ž๏ธBell for a helper
Press play and watch it happen!

The fast turnstile

Some passengers don't need a guide at all. Think of a crew that flies in every few minutes: they all go to the same place, and there are thousands of them. For them the airport has a turnstile. It doesn't read tickets. It only knows which door you came through, and it sends you straight on to a desk for that door, very fast.

This is the Network Load Balancer. Because it opens nothing, it can handle huge crowds and many kinds of passenger, not only ticket holders. The desk can see the passenger's own face, not the guide's, so it knows exactly who it's talking to.

The airport has several wings, each with its own power, so one breaking doesn't close the whole airport. Each wing has its own turnstile, and each turnstile has a fixed spot on the airport map that never moves. Partner airlines can write those spots down once and rely on them. If one wing loses power, passengers use the turnstile in another wing.

Network Load Balancer

The NLB works at layer 4. Its listeners are TCP, UDP, TCP_UDP, TLS, and (passthrough) QUIC and TCP_QUIC. It routes each connection (or UDP flow) to a target without reading the payload, so it has no path or header rules: a listener forwards to one target group, or splits connections by weight across several. AWS designs it for very high throughput, millions of requests per second, at low latency.

  • Static IPs. The NLB has one node per enabled AZ, each with a fixed address: an Elastic IP you can assign per subnet, or one AWS assigns (internet-facing), or a private IP from the subnet (internal). Clients and partner firewalls can allow-list them. The DNS name resolves to the nodes in healthy AZs.
  • Client IP preservation. For instance targets the target sees the client's real source IP. For ip targets it's on by default for UDP and off by default for TCP and TLS (attribute preserve_client_ip.enabled); when it's off, the target sees the NLB's private IP. Proxy protocol v2 is the other way to pass the client address.
  • TLS listeners can terminate TLS with an ACM certificate, like an ALB, without parsing HTTP.
  • Targets are instance, ip or alb: an ALB behind an NLB gives you static IPs and layer-7 rules.

The Gateway Load Balancer is different again: it's a layer-3 "bump in the wire" that sends all IP packets, wrapped in GENEVE on port 6081, through a fleet of third-party appliances such as firewalls or intrusion detection, then back on their way. You'd use it to insert inspection, not to serve an app.

An NLB passes connections through4 steps
๐Ÿข Wing A๐Ÿข Wing B๐ŸงณPassenger๐ŸšงTurnstile, wing A๐ŸšงTurnstile, wing B๐Ÿง‘โ€๐Ÿ’ผDesk A๐Ÿง‘โ€๐Ÿ’ผDesk B
Press play and watch it happen!

The supervisor's round

A desk might close at any moment: the clerk falls ill, or the computer freezes. So a supervisor walks past every desk again and again and asks "are you open?". A desk that answers is fine.

If a desk doesn't answer twice in a row, the supervisor puts a "closed" sign on it, and the guide stops sending passengers there. These checks are called health checks. The supervisor keeps asking the closed desk too. Only after it has answered five times in a row does the sign come down, so a desk that wobbles doesn't flip open and shut all day.

Health checks

Each target group has its own health check. The load balancer probes every registered target and routes only to targets in the healthy state. For an ALB target group the defaults are an HTTP check on /, every 30 seconds, a 5 second timeout, healthy after 5 consecutive successes and unhealthy after 2 consecutive failures (the threshold is configurable with target group health settings), with 200 as the success code (Matcher can widen that). So with the defaults a dead target takes about a minute to be marked unhealthy, and a recovered one about two and a half minutes to come back. NLB checks can be TCP, HTTP or HTTPS.

Point the check at a cheap endpoint that says whether this instance can serve, such as Spring Boot's /actuator/health/readiness. Don't make it depend on a shared database: if the database blips, every target fails together. If every target in a group is unhealthy, the ALB fails open and sends traffic to all of them, on the theory that some may still work. An Auto Scaling group can use the ELB health check to replace targets the load balancer marks unhealthy.

Health checks4 steps
๐Ÿ›ซ Gate๐ŸงณPassengers๐Ÿง‘โ€โœˆ๏ธGuide and supervisor๐Ÿง‘โ€๐Ÿ’ผDesk 1๐Ÿง‘โ€๐Ÿ’ผDesk 2๐Ÿง‘โ€๐Ÿ’ผDesk 3
Press play and watch it happen!

Sending people across wings

Each wing has its own guide or turnstile, and arriving passengers are split evenly between them. But wings don't always have the same number of desks. Say wing A has one desk and wing B has three.

If each wing only uses its own desks, the single desk in wing A gets half of all the passengers, while wing B's three desks share the other half. So the hall can let each guide send people to desks in any wing. This is called cross-zone load balancing, and it spreads passengers evenly over every desk. The guide does it unless you tell a gate not to. The turnstiles don't, unless you ask them to.

Cross-zone load balancing

Clients are spread across the load balancer's nodes, roughly one per AZ, by DNS. Cross-zone load balancing decides whether each node may also send traffic to targets in other AZs.

Load balancer levelTarget group level
ALBAlways on, can't be turned offDefaults to the load balancer's setting; can be turned off per target group
NLBOff by default; can be turned onDefaults to the load balancer's setting; can be overridden

With it off, traffic is even per AZ, not per target, so uneven target counts give uneven load: with one target in AZ a and three in AZ b, the AZ a target takes half the traffic. With it on, traffic is even across all healthy targets. Keeping it off on an NLB avoids cross-AZ hops and the inter-AZ data charges that come with them, but then you must keep enough capacity in every AZ. On an ALB, turning it off for a target group rules out stickiness and Lambda targets in that group.

Cross-zone load balancing3 steps
๐Ÿข Wing A๐Ÿข Wing B๐ŸงณPassengers๐ŸšงTurnstile, wing A๐Ÿง‘โ€๐Ÿ’ผDesk A1๐ŸšงTurnstile, wing B๐Ÿ‘ฉโ€๐Ÿ’ผDesk B1๐Ÿ‘ฉโ€๐Ÿ’ผDesk B2๐Ÿ‘ฉโ€๐Ÿ’ผDesk B3
Press play and watch it happen!

Closing a desk politely

When a desk is swapped for a new one, you don't just switch off its lights while a passenger is halfway through. First the new desk opens, and the supervisor checks it answers. Then the old desk gets a sign: "no new passengers". The guide sends everyone new to other desks, while the old desk finishes the people already standing at it.

That waiting time is called the deregistration delay. It has a limit, five minutes unless you change it, so a passenger who never leaves can't keep a desk open forever. When the last one is done, or time runs out, the desk closes for good.

Deregistration delay and rolling deploys

When a target is deregistered (by a deploy, a scale-in or by hand), the load balancer stops sending it new requests but lets in-flight ones finish. This is connection draining, set per target group by deregistration_delay.timeout_seconds: 300 seconds by default, 0 to 3600. On an ALB, remaining connections are closed when it expires. It doesn't apply to Lambda targets. Lower it (30 seconds is common) when requests are short, or deploys wait five minutes per batch for nothing.

Make the app's shutdown match. Spring Boot can stop taking new work and finish in-flight requests, and it should see the client's real scheme and address from the ALB's forwarded headers:

1# the default since Spring Boot 3.42server.shutdown=graceful3spring.lifecycle.timeout-per-shutdown-phase=30s4server.forward-headers-strategy=native5# on automatically only on Kubernetes6management.endpoint.health.probes.enabled=true
Deregistration delay in a deploy4 steps
๐Ÿ›ซ Gate๐ŸงณPassengers๐Ÿง‘โ€โœˆ๏ธGuide๐Ÿง‘โ€๐Ÿ’ผOld desk
Press play and watch it happen!

A turnstile in front of the guide

Sometimes you want both. A partner airline insists on a fixed spot on the map, but your passengers still need someone to read their tickets. So you put a turnstile at the fixed spot, and it sends everyone straight on to the guide, who reads each ticket and picks the gate as usual.

Some airports also add a security checkpoint. Every passenger is walked through a screening lane and then carries on their way, whichever door or gate they're going to. That checkpoint has its own kind of helper, the Gateway Load Balancer, but it's there to inspect, not to send people to desks.

Choosing and wiring them up

NeedUse
HTTP routing by path, host or header, TLS termination, WebSockets, gRPC, Lambda targetsALB
Non-HTTP protocols, UDP, extreme throughput, static IPs, client IP at the targetNLB
Static IPs and layer-7 rulesNLB with an alb target group
Firewalls or inspection appliances in the traffic pathGWLB

Targets are often containers rather than instances: ECS and EKS register task or pod IPs in ip target groups as they start and deregister them as they stop.

With the AWS CDK in Java, a listener, a rule and target groups look like this:

1ApplicationLoadBalancer alb = ApplicationLoadBalancer.Builder.create(this, "Alb")2        .vpc(vpc).internetFacing(true).build();3 4ApplicationListener https = alb.addListener("Https", BaseApplicationListenerProps.builder()5        .port(443)6        .certificates(List.of(ListenerCertificate.fromArn(certArn)))   // from ACM7        .build());8 9https.addTargets("Api", AddApplicationTargetsProps.builder()10        .priority(10)11        .conditions(List.of(ListenerCondition.pathPatterns(List.of("/api/*"))))12        .port(8080).targets(List.of(apiAsg))13        .healthCheck(HealthCheck.builder().path("/actuator/health/readiness").build())14        .deregistrationDelay(Duration.seconds(30))   // software.amazon.awscdk.Duration15        .build());16 17https.addTargets("Web", AddApplicationTargetsProps.builder()      // no priority: the default action18        .port(8080).targets(List.of(webAsg)).build());

A target group without priority and conditions becomes the listener's default action.

๐Ÿ”ง Going deeper

Status codes from the ALB itself tell you where to look: 502 means the target closed the connection or sent a malformed response, 503 means the target group has no registered targets, and 504 means the target didn't answer in time. Check the ALB's access logs and the target's logs together.

Idle timeout. An ALB closes connections that send no data for 60 seconds by default. Long-lived WebSockets or slow downloads need heartbeats or a higher idle_timeout.timeout_seconds. Keep the app's own keep-alive timeout longer than the ALB's, or the app may close a connection the ALB is about to reuse, which shows up as occasional 502s.

An NLB in front of an ALB4 steps
๐ŸงณPartner airline passenger๐ŸšงTurnstile๐Ÿง‘โ€โœˆ๏ธGuide๐Ÿ›๏ธShop gate๐Ÿ›ซMain gate
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Elastic Load Balancing: ALB and NLB, told the same way as the story.
  1. You want shop tickets to go to one gate and staff tickets to another, sorted by what's written on each ticket. Who can do that?
  2. A partner airline will only let passengers through from spots on the map it has written down once and for all. What do you give it?
  3. A desk's computer freezes and it stops answering the supervisor. What happens to passengers?
  4. Wing A has one desk and wing B has three, and the turnstiles only use desks in their own wing. Which desk is busiest?
  5. You swap an old desk for a new one. How do you avoid sending away passengers who are halfway through?
Answer every question to check.Passing marks Elastic Load Balancing: ALB and NLB as done.
Got the hang of Elastic Load Balancing: ALB and NLB? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ›ฐ๏ธ AWS in productionStep 1 of 7

Next on the path โ†’๐Ÿชง Amazon Route 53

๐Ÿ‘‰ Read next

  • ๐Ÿš›Amazon ECS, Fargate and EKSA port with working berths for containers: bring your own lorries or rent one by the trip.
  • ๐ŸชงAmazon Route 53The city information kiosk that tells visitors which branch of your shop to go to, following your rules.