Skip to content

Lesson 12 of 30Modern AWS

API Gateway and Load Balancing

Choose between API Gateway, ALB and NLB, set up target groups and health checks, and terminate TLS with ACM.

15 min read0/4 questions

Every request to your backend enters through a front door, and on AWS there are three main ones: API Gateway, the Application Load Balancer and the Network Load Balancer. Picking the wrong one costs money (API Gateway at high volume), features (an NLB cannot route by path) or latency. This lesson shows what each one does and how traffic flows through it.

What a front door does

Whatever sits in front of your app has a few jobs:

  • Terminate TLS: hold the HTTPS certificate so your app can speak plain HTTP inside the VPC.
  • Route: decide which backend gets the request (by path, host, header).
  • Spread load across healthy copies of your app, and stop sending to unhealthy ones.
  • Sometimes authenticate, throttle and transform requests.

Application Load Balancer

An Application Load Balancer (ALB) works at layer 7 (HTTP). It understands paths, hosts, headers and cookies.

  • A listener waits on a port and protocol, like HTTPS on 443.
  • Rules on the listener match requests: Host: api.example.com, Path: /admin/*.
  • Each rule forwards to a target group: a set of targets (EC2 instances, IPs such as ECS Fargate tasks, or a Lambda function) plus a health check.
ALB routing to two target groups
Public subnetsPrivate subnetsBrowserBrowserALB: HTTPS :443ALBHTTPS :443ACM cert: *.example.comACM cert*.example.comapi task: TG api /api/*api taskTG api /api/*api task: unhealthyapi taskunhealthyweb task: TG web /*web taskTG web /*web task: TG web /*web taskTG web /*TLS/api/*/*

The browser opens HTTPS to the ALB. The certificate comes from ACM, and TLS ends here.

1/4

Health checks

A health check is a request the load balancer sends to each target on a schedule, for example GET /health every 15 seconds, expecting 200. After a few failures in a row (the unhealthy threshold) the target is taken out; after a few successes it comes back.

Make /health cheap and honest. If it checks the database, a database blip marks every target unhealthy at once, and the ALB has nothing to route to. Many teams keep the ALB check shallow (the process is up) and alarm on dependencies separately.

Pythonround_robin.py
from itertools import cycle targets = {"10.0.2.11": 0, "10.0.3.12": 0, "10.0.2.13": 0} # ip -> consecutive failuresUNHEALTHY_THRESHOLD = 3 def health_check(ip, ok): targets[ip] = 0 if ok else targets[ip] + 1 def healthy(): return [ip for ip, fails in targets.items() if fails < UNHEALTHY_THRESHOLD] for _ in range(3): health_check("10.0.3.12", ok=False) rr = cycle(healthy())print("healthy:", healthy())print("routing:", [next(rr) for _ in range(4)])
Output
Press Run (⌘ Enter) to see what happens.

Network Load Balancer

A Network Load Balancer (NLB) works at layer 4 (TCP, UDP, TLS). It does not look at HTTP at all, so it cannot route by path, but it gives you:

  • very high throughput with very low added latency,
  • static IP addresses per AZ (or Elastic IPs you own), which partners can allowlist in their firewalls,
  • non-HTTP protocols: game servers, MQTT, raw TCP to a database proxy,
  • the way to expose a service privately to other accounts with PrivateLink.

API Gateway

Amazon API Gateway is a managed API front door, billed per request, with no servers or hourly charge. It is the natural partner for Lambda. It comes in flavors:

HTTP APIREST API
Price (example)about $1.00 per million requestsabout $3.50 per million requests
LatencyLowerHigher
AuthJWT authorizers (Cognito, Auth0...), IAM, Lambda authorizersIAM, Cognito, Lambda authorizers, API keys and usage plans
ExtrasCORS, simple routingRequest validation, transformations, caching, WAF, per-client throttling
Pick itDefault for new APIsWhen you need the extra features

(There is also a WebSocket API type for real-time apps.) Check current pricing; the ratios matter more than the exact numbers.

Throttling protects your backend. API Gateway uses a token bucket: a bucket holds up to burst tokens, refills at rate tokens per second, and each request takes one. Empty bucket means 429 Too Many Requests.

Pythontoken_bucket.py
class TokenBucket: def __init__(self, rate, burst): self.rate, self.burst = rate, burst self.tokens, self.last = burst, 0.0 def allow(self, now): self.tokens = min(self.burst, self.tokens + (now - self.last) * self.rate) self.last = now if self.tokens >= 1: self.tokens -= 1 return 200 return 429 bucket = TokenBucket(rate=2, burst=3)times = [0.0, 0.1, 0.2, 0.3, 0.4, 1.0, 1.1]print([bucket.allow(t) for t in times])
Output
Press Run (⌘ Enter) to see what happens.

The first three requests use the burst, the next two are rejected, and by t = 1.0 the bucket has refilled enough for two more.

Predict the outputPython

A token bucket starts full with burst 2 and refills slowly. Four requests arrive at the same instant. How many get a 200?

allowed = 0
tokens = 2
for _ in range(4):
  if tokens >= 1:
      tokens -= 1
      allowed += 1
print(allowed)
Need a nudge? Hints walk you through it.

Choosing the front door

API Gateway (HTTP API)ALBNLB
Layer7 (HTTP)7 (HTTP)4 (TCP/UDP/TLS)
PricingPer requestPer hour + capacity units (LCU)Per hour + capacity units (NLCU)
BackendsLambda, HTTP URLs, private ALB/NLB via VPC linkEC2, IPs (ECS), LambdaEC2, IPs, ALB
RoutingRoutes by method + pathPath, host, header, query rulesPort only
Built-in authJWT, IAM, Lambda authorizersOIDC/Cognito login on listener rulesNone
Best forLambda APIs, low or spiky trafficContainers and EC2 web apps, steady trafficStatic IPs, extreme throughput, non-HTTP

A rough cost intuition: an ALB is around $16 to $25 a month just to exist (example price; it bills hourly), then cheap per request. API Gateway costs nothing idle, but at hundreds of millions of requests a month the per-request fee overtakes the ALB.

Match the pairs0/4 matched

Pick the front door.

Choose an item, then its match on the other side.

TLS certificates with ACM

AWS Certificate Manager (ACM) issues public TLS certificates for free for use with ALB, NLB, API Gateway and CloudFront, and renews them automatically. You prove you own the domain with a DNS validation record (a CNAME that ACM gives you; if your DNS is in Route 53, one click adds it).

aws acm request-certificate \  --domain-name api.example.com \  --subject-alternative-names "*.example.com" \  --validation-method DNS

Two gotchas. Certificates are Regional: an ALB in eu-west-1 needs a cert in eu-west-1, but CloudFront needs its cert in us-east-1. And you cannot export ACM's public certificates' private keys to install on your own EC2 web server; ACM certificates live on AWS's managed front doors.

A typical ALB setup has two listeners: HTTPS on 443 with the ACM cert forwarding to target groups, and HTTP on 80 with a single redirect to HTTPS rule.

Quick check
After a deploy, the ALB shows all targets as unhealthy and users get 503. The app logs show it is serving requests on port 8000 just fine. What is the most likely cause?
Need a nudge? A hint rules out a wrong answer.
Quick check
You want only signed-in users (with a Cognito-issued JWT) to reach your Lambda API, without writing token-checking code. Simplest option?
Need a nudge? A hint rules out a wrong answer.
Key terms
target group
A set of backends (instances, IPs, a Lambda) plus the health check an ALB or NLB uses for them.
health check
A periodic probe like GET /health. Failing targets stop receiving traffic.
listener rule
ALB condition (path, host, header) mapped to an action like forward or redirect.
Network Load Balancer
Layer 4 load balancer with static IPs, very high throughput, any TCP/UDP protocol.
token bucket
Throttling model: tokens refill at a rate up to a burst size; each request spends one.
ACM
AWS Certificate Manager: free, auto-renewing TLS certificates for AWS front doors.