DEVOPS, SRE AND CLOUD · PART 2 · NETWORKING FOR DEVOPS · TRAFFIC · 39 OF 187

Load Balancers: Layer 4 vs Layer 7, Health Checks

Load balancing measured on two ShopRung instances behind nginx: round robin split 6 requests 3 and 3; after we killed one instance, the next request failed over within the same request and every later request went to the healthy one, all returning 200. Plus layer 4 vs layer 7, algorithms, active and passive health checks, sticky sessions, draining, 502 with no backend, and AWS ALB vs NLB.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
1 / 11

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Round robin 3/3
  • failover inside one request
  • passive vs active checks
  • 502 vs 504
  • L4 vs L7
  • draining

Notes

Our setup

Our setup: ShopRung instance A on port eight thousand and eighty, instance B on eight thousand and eighty two, and nginx on eight thousand and ninety in front. The upstream block lists both servers; max fails one with a ten second fail timeout means one failure marks a server as down for ten seconds. We added a response header showing which backend served each request, so we can see the balancing.

nginx upstream
upstream pool {
  server 127.0.0.1:8080
    max_fails=1
    fail_timeout=10s;
  server 127.0.0.1:8082 ...;
}
location / {
  proxy_pass http://pool;
  add_header X-Upstream
    $upstream_addr;
}

Round robin

Six requests, three to each backend: round robin, nginx's default, simply takes turns. Other algorithms: least connections sends each request to the backend with the fewest active requests, better when requests vary in cost. Hashing on the client IP or a header sends the same key to the same backend, useful for caches. Weights give bigger servers more traffic.

6 requests (ours)
3  X-Upstream: 127.0.0.1:8080
3  X-Upstream: 127.0.0.1:8082

round robin: take turns
least connections: pick the
  least busy
hash (IP, header): same key
  → same backend
weights for bigger servers

Kill one

Now we killed instance B. Request two was sent to B, the connection was refused, and nginx retried the same request on A: its header listed both, eight thousand and eighty two then eight thousand and eighty, and the user got two hundred. B was then marked down, so requests three to six went straight to A. nginx's error log recorded connection refused for B. No user saw an error. That retry is safe here because GET is idempotent.

After kill of B (ours)
req 1  8080           200
req 2  8082, 8080     200
  B refused, retried on A
req 3-6  8080         200

error.log: connect() failed
  (111: Connection refused)
  upstream 127.0.0.1:8082
no user saw an error

Health checks

That was a passive health check: nginx noticed failures in real traffic. Active checks probe each backend on a schedule, for example GET /health every five seconds, remove it after a few failures, and add it back after a few successes. Cloud load balancers and HAProxy do this. Make the health endpoint meaningful: it should show the app can actually serve, not just that the port is open, but avoid failing every instance because one shared dependency is slow.

Two kinds
  • passive: notice failures in real traffic (what nginx OSS did above)
  • active: probe /health every few seconds, remove after N failures, add after M successes
  • check what matters: app can serve, not just "port open"

No backend left

When no backend can answer, users get errors from the load balancer itself. We pointed a second nginx site at a port with nothing listening: the reply was five oh two, bad gateway, in a quarter of a millisecond, and the error log named the upstream and the reason. Five oh two means the balancer could not connect or got a bad reply; five oh four means the backend was too slow. Always read the balancer's log first.

Proxy to a dead port (ours)
$ curl :8091
code 502   0.000249 s

error.log: connect() failed
  (111: Connection refused)
  upstream 127.0.0.1:8099
502: could not connect or
  bad reply
504: upstream too slow

Layer 4 vs layer 7

A layer four balancer forwards TCP or UDP connections by address and port without reading the content. It is very fast, works for any protocol, including databases, and can preserve the client's IP. A layer seven balancer reads the HTTP request, so it can route /api to one service and everything else to another, terminate TLS, retry, rewrite headers and run a firewall. In AWS, the Network Load Balancer is layer four and the Application Load Balancer is layer seven.

Compare
  • L4 (TCP/UDP): forwards connections by IP:port, very fast, any protocol, can keep client IP
  • L7 (HTTP): reads host, path, headers; routes /api vs /; TLS termination, retries, rewrites, WAF
  • AWS: NLB = L4, ALB = L7

Deploys and state

Two operational ideas. Connection draining: before stopping an instance, the balancer stops sending it new requests and lets in-flight ones finish, which is what makes rolling deploys invisible to users. Sticky sessions pin a user to one backend with a cookie, but they unbalance load and lose sessions when an instance dies, so keep state in Redis or a database instead. And behind a proxy, the client's address arrives in X-Forwarded-For, or the PROXY protocol at layer four.

Operations
  • draining: stop new requests, let in-flight finish, then stop the instance
  • sticky sessions: same user → same backend (cookie) better: keep state in Redis or the database
  • client IP: X-Forwarded-For or PROXY protocol

Common mistakes

Mistakes. A health check that only tests whether the port is open. Deep checks that fail every instance at once when a shared dependency hiccups. Deploying without draining. Letting the balancer retry POST requests. Sticky sessions hiding state problems. Logging the balancer's address instead of the client's. And a single balancer in a single zone.

Avoid these
  • health check = "port open"
  • deep checks that fail every instance at once
  • no draining on deploy
  • retrying POSTs
  • sticky sessions as a crutch
  • logging the LB IP, not the client IP
  • a single LB, single AZ

Say it like this

In the interview: a layer four balancer forwards connections by IP and port, fast and protocol agnostic, like AWS NLB. A layer seven balancer parses HTTP, so it routes by host and path, terminates TLS, retries idempotent requests and adds headers, like ALB or nginx. Either way I rely on health checks that reflect real readiness, drain connections during deploys, and keep session state out of the instances.

In the interview
  • "L4 forwards connections by IP
  • and port: fast, any protocol. L7
  • parses HTTP, so it routes by host or path, terminates TLS and retries. Either way: health
  • checks that reflect real
  • readiness, draining on deploy, state outside the instances."

Interview questions

Q1What is the difference between an L4 and an L7 load balancer?

L4 balances TCP/UDP connections by IP and port without reading content; L7 understands HTTP and can route by host, path or header, terminate TLS and retry.

Q2What is the difference between active and passive health checks?

Active checks probe backends on a schedule (e.g. GET /health); passive checks mark backends down based on failures seen in real traffic.

Q3What is connection draining?

Stopping new requests to an instance while letting in-flight requests finish before it is removed, so deploys and scale-in do not drop requests.

Q4Why are sticky sessions discouraged?

They unbalance load and lose user sessions when an instance dies; storing session state in a shared store keeps instances stateless.

Q5How does a backend learn the real client IP behind a load balancer?

From the X-Forwarded-For header added by an L7 proxy, or the PROXY protocol header for L4 balancers.

Q6When would you choose AWS NLB over ALB?

For non-HTTP protocols, very high throughput or static IPs, or when you need to preserve the client IP at layer 4; ALB for HTTP routing and TLS features.

Q7Which load balancing algorithms do you know?

Round robin, weighted round robin, least connections, IP or header hash (consistent hashing), and random with two choices.