A load balancer distributes traffic across backends, but it works at one of two layers. A layer 4 balancer balances TCP or UDP connections without inspecting the payload; a layer 7 balancer terminates the request and can route on HTTP details such as path, host and headers.
Before you start
You should understand TCP and basic HTTP. This article compares the two layers and their trade-offs.
Step-by-step walkthrough
Step 1: Know what layer 4 can see
An L4 balancer sees packets and connections, not HTTP requests, so it can balance by connection and preserve the client’s TCP flow. It is fast and protocol-agnostic, handling any TCP or UDP traffic, but it cannot route by URL path or inspect a header.
Step 2: Know what layer 7 adds
An L7 balancer terminates TLS and parses HTTP, so it can route /api to one pool and /images to another, rewrite headers, and apply per-route policies. The trade is more processing and the need to handle TLS certificates at the balancer.
Step 3: Align health checks and sessions
Both layers use health checks to remove unhealthy backends, but an L7 check can request a specific path, while an L4 check is usually a TCP connect. Sticky sessions are simpler at L4 because a connection maps to one backend; at L7, stickiness must be implemented in the application or via cookies.
Worked scenario
The L7 balancer routes by path to different pools.
client -> L7 balancer (TLS terminated here)
/api/* -> api-pool
/static/* -> static-pool
default -> web-poolWalk through the example
Because the balancer parses the request, it can send /api requests to the API pool and /static to a static pool, which an L4 balancer could not do without separate addresses. TLS is terminated at the balancer, so backends receive plain HTTP or re-encrypted traffic, and certificate management moves to one place.
Common mistake
Expecting an L4 balancer to route by path, which it cannot, or terminating TLS at an L7 balancer without planning where certificates and security policies live. Another is relying on client IP for stickiness when the balancer rewrites or hides it.
Verify the behavior
Send requests to different paths and confirm each reaches the intended pool. Check that health checks remove a failing backend. Confirm the client IP is preserved or forwarded as expected in a header such as X-Forwarded-For.
Interview exercise
When would you choose L4 over L7?
Answer and reasoning
When the traffic is not HTTP, such as a database or a custom TCP protocol, or when you need the highest throughput and lowest latency and do not need payload-based routing. L4 is also simpler when the protocol is unknown to the balancer. Choose L7 when you need routing by path, host or header, or TLS termination with per-route policy.
Continue learning
Compare routing in Proxies and forwarding and balancing in Load balancing. Read the Cloudflare load balancing documentation and try the Networking interview questions.