Octet

How does a backend learn the real client IP behind cloud load balancers?

Show the answer

Say this first

It depends on whether the load balancer proxies or passes packets through. An ALB, Application Gateway or GCP proxy load balancer adds the client IP to X-Forwarded-For. An NLB preserves the source IP for instance targets by default, but not for IP targets with TCP or TLS, where you enable client IP preservation or proxy protocol v2. Azure Load Balancer and GCP passthrough load balancers do not rewrite the source at all.

Go deeper

By load balancer

Load balancerHow the client IP arrives
AWS ALBX-Forwarded-For, plus X-Forwarded-Proto and X-Forwarded-Port
AWS NLB, instance targetsSource IP preserved by default
AWS NLB, IP targets, TCP or TLSNot preserved by default; turn on preservation or proxy protocol v2
AWS NLB, UDPPreserved
Azure Load BalancerPassthrough, source preserved
Azure Application GatewayX-Forwarded-For
GCP passthrough Network LBSource preserved
GCP Application LB and proxy Network LBX-Forwarded-For, or PROXY protocol for TCP proxy

Side effects of preserving the client IP

  • The target's security group must allow the real client addresses, not just the load balancer.
  • Replies must go back through the load balancer path. With a passthrough design, a server whose default route points elsewhere breaks the flow.
  • Hairpin: with NLB client IP preservation, a target that connects to its own NLB and is balanced to itself sees a packet from its own IP to its own IP, and the connection fails.

Kubernetes

A LoadBalancer Service with externalTrafficPolicy: Cluster lets kube-proxy send traffic to a pod on another node, and it SNATs the packet, so the pod sees a node IP. externalTrafficPolicy: Local keeps traffic on nodes that run a pod and preserves the client IP, at the cost of possibly uneven spread.

Traps

  • Turning on proxy protocol on the NLB without enabling it on the backend, which then fails every request.
  • Assuming an NLB always preserves the client IP whatever the target type.
How did you do?