TExcelTAD
Home › AWS Cloud › Elastic Load Balancing

Elastic Load Balancing

A load balancer is a single entry point that spreads incoming traffic over several servers (its targets). If one target fails its health check, the load balancer stops sending it traffic. Elastic Load Balancing (ELB) is AWS's managed load balancer: it scales itself, spans several Availability Zones and integrates with Auto Scaling.

Types of load balancers

Type Layer Understands Use it for
Application Load Balancer (ALB) 7 (HTTP/HTTPS) paths, host names, headers, query strings Web apps, microservices, containers, Lambda targets
Network Load Balancer (NLB) 4 (TCP/UDP/TLS) IPs and ports Very high throughput, static IPs, non-HTTP protocols
Gateway Load Balancer (GWLB) 3 (IP packets) packets Inserting third-party firewalls/appliances
Classic Load Balancer 4/7 basic Legacy only

The pieces of an ALB

  • Listener: a port and protocol the load balancer accepts (HTTPS:443), with a TLS certificate from ACM.
  • Rules: conditions (path is /api/*, host is shop.example.com) and actions (forward, redirect, fixed response).
  • Target group: a set of targets (instances, IPs, Lambda functions) plus a health check (GET /health must return 200).
bash
aws elbv2 create-target-group --name web-tg --protocol HTTP --port 80 \
    --vpc-id vpc-0abc1234def567890 --health-check-path /health
aws elbv2 register-targets --target-group-arn arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/web-tg/6d0ecf831eec9f09 \
    --targets Id=i-0aaa1111bbbb22223 Id=i-0ccc3333dddd44445
aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/web-tg/6d0ecf831eec9f09 \
    --query "TargetHealthDescriptions[].[Target.Id,TargetHealth.State]" --output text

Sample output:

text
i-0aaa1111bbbb22223	healthy
i-0ccc3333dddd44445	unhealthy

Model: round robin vs least outstanding requests

ALBs use round robin by default and can be switched to least outstanding requests. The difference shows when requests take different amounts of time. In this model each request has a duration; we track how long each target stays busy.

python · try it yourself
requests = [9, 1, 1, 9, 1, 1, 9, 1, 1, 9, 1, 1]   # seconds of work, arriving one per second
targets = ["web-a", "web-b", "web-c"]

def simulate(pick):
    busy_until = {t: 0 for t in targets}
    waits = []
    rr = 0
    for arrival, work in enumerate(requests):
        if pick == "round-robin":
            target = targets[rr % len(targets)]
            rr += 1
        else:   # least outstanding: the target that frees up first
            target = min(targets, key=lambda t: (max(busy_until[t] - arrival, 0), t))
        start = max(arrival, busy_until[target])
        waits.append(start - arrival)
        busy_until[target] = start + work
    return waits

for algo in ("round-robin", "least-outstanding"):
    w = simulate(algo)
    print(f"{algo:<18} total wait {sum(w):>3} s, worst wait {max(w):>2} s  {w}")
round-robin        total wait  36 s, worst wait 18 s  [0, 0, 0, 6, 0, 0, 12, 0, 0, 18, 0, 0]
least-outstanding  total wait  10 s, worst wait  2 s  [0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 2]

With round robin, every slow request lands on web-a (the pattern repeats every three requests, just like the target order), so each slow request waits longer and longer for the previous one, while web-b and web-c sit mostly idle. Least outstanding requests sends each request to the target that will be free soonest, which cuts the total wait from 36 s to 10 s for exactly the same traffic.

Model: health checks

A target becomes unhealthy after a number of consecutive failed checks (the unhealthy threshold) and healthy again after a number of consecutive successes (the healthy threshold):

python · try it yourself
def health(results, healthy_threshold=3, unhealthy_threshold=2):
    state, streak, last = "healthy", 0, None
    timeline = []
    for ok in results:
        streak = streak + 1 if ok == last else 1
        last = ok
        if state == "healthy" and not ok and streak >= unhealthy_threshold:
            state = "unhealthy"
        elif state == "unhealthy" and ok and streak >= healthy_threshold:
            state = "healthy"
        timeline.append(state[0].upper())
    return "".join(timeline)

checks = [True, True, False, True, False, False, False, True, True, True, True]
print("checks:", "".join("+" if c else "x" for c in checks))
print("state :", health(checks))
checks: ++x+xxx++++
state : HHHHHUUUUHH

One failed check (a blip) doesn't remove the target; two in a row do. Coming back takes three good checks in a row, so a flapping server doesn't keep getting traffic.

Path-based routing

python · try it yourself
from fnmatch import fnmatchcase

rules = [   # (priority, host pattern, path pattern, target group)
    (10, "api.example.com", "*", "api-tg"),
    (20, "*", "/images/*", "static-tg"),
    (30, "*", "/admin*", "admin-tg"),
]
default = "web-tg"

def route(host, path):
    for _prio, host_pat, path_pat, tg in sorted(rules):
        if fnmatchcase(host, host_pat) and fnmatchcase(path, path_pat):
            return tg
    return default

for host, path in [("api.example.com", "/v1/orders"), ("www.example.com", "/images/logo.png"),
                   ("www.example.com", "/admin/users"), ("www.example.com", "/cart")]:
    print(f"{host}{path:<18} -> {route(host, path)}")
api.example.com/v1/orders         -> api-tg
www.example.com/images/logo.png   -> static-tg
www.example.com/admin/users       -> admin-tg
www.example.com/cart              -> web-tg

Rules are evaluated in priority order (lowest number first) and the first match wins; requests that match nothing go to the listener's default action.

Test yourself

Which load balancer can route /api/* and /images/* to different target groups?

  1. Network Load Balancer
  2. Application Load Balancer
  3. Gateway Load Balancer
  4. None of them

You need a static IP address and millions of TCP connections per second. Which type fits?

  1. ALB
  2. NLB
  3. GWLB
  4. Classic

What does the load balancer do with a target that fails its health checks?

  1. Terminates it
  2. Stops routing traffic to it until it passes again
  3. Restarts it
  4. Sends it more traffic