Back to Articles

Load Balancing Architecture: L4, L7, and Choosing a Platform

Contents

L4 vs. L7: What Each Actually Balances

The first decision shapes every one after it, because it determines what the load balancer can even see:

Layer 4 (Transport)Layer 7 (Application)
What it seesIP addresses, ports, TCP/UDP state — no visibility into the payloadThe full HTTP request: method, path, host header, cookies, body
Routing decisionsWhich backend gets this connection, based on IP/port and the algorithmWhich backend gets this request, based on path, host, header, or content
PerformanceVery low overhead — it moves packets, not requestsHigher overhead — it terminates and parses the protocol
Typical useTCP/UDP services in general, or as the fast outer tier in front of an L7 layerHTTP(S) web and API traffic where routing depends on the request itself

The practical pattern in most modern stacks is both, layered: an L4 load balancer (often the cloud provider's own, or a hardware/virtual appliance) absorbs connection-level scale and DDoS pressure, handing traffic to an L7 tier that does the content-aware routing — host-based virtual hosting, path-based API routing, header-based canary splits. Reach for L4 alone when the backends are a uniform TCP service with nothing to route on; reach for L7 the moment "which backend" depends on anything inside the request.

Load Balancing Algorithms

The algorithm decides which of the healthy backends gets the next connection or request. Five cover nearly every real deployment:

  • Round robin. Backends take turns, in order. Simple, and fine when every backend and every request is roughly equal cost — a bad fit when they aren't.
  • Least connections. Send the next request to whichever backend currently holds the fewest open connections. This is the default that actually adapts to uneven request cost, and it's the right first choice for most HTTP workloads.
  • Weighted (round robin or least connections). Assign each backend a capacity weight — useful when the fleet is mixed hardware, or during a canary rollout where the new version should get a deliberately small slice of traffic.
  • IP hash / source hash. Route by a hash of the client IP (or another key), so the same client consistently lands on the same backend. This is a crude form of session persistence, and its weakness is the same as its strength: it doesn't rebalance when a backend goes away, and NAT can pile many real clients behind one hashed IP.
  • Consistent hashing. A hash-ring approach that minimizes redistribution when a backend is added or removed — the algorithm behind cache and CDN routing at scale, and worth knowing exists even if you don't reach for it directly in a typical web-tier config.

Least connections is a useful starting point for requests with variable duration; round robin fits uniform, short-lived work. Use weights when backends have different capacity or when a rollout deliberately limits traffic to a subset.

Health Checks: The Part That Actually Prevents Outages

The algorithm only matters among backends the load balancer believes are healthy — and "believes" is the operative word, because a weak health check is the single most common cause of a load balancer sending traffic into a backend that's already failing.

  • TCP check. Can the load balancer open a connection? This proves the process is listening, and nothing else — a backend deadlocked but still holding its socket open passes a TCP check while serving every request as a timeout.
  • HTTP check. A GET to a specific path, expecting a specific status code (and optionally a body match). This is the practical minimum for a web tier — it proves the application layer is answering, not just the socket.
  • Application-level (deep) check. The health endpoint itself verifies dependencies — the database connection, a downstream service — before returning healthy. This catches the "the web server is up but the database it needs is not" failure that an HTTP check on a static path misses, but it also means a downstream blip can cascade into pulling every backend out of rotation at once. Use it deliberately, and make sure the check has its own timeout shorter than the load balancer's.

Two settings decide how fast a real failure is detected and how tolerant the system is of a blip: the interval (how often to check) and the threshold (how many consecutive failures before marking a backend down, and how many consecutive successes before marking it back up). A threshold of one flaps a backend in and out of rotation on a single dropped packet; a threshold that's too high leaves a dead backend serving errors for minutes. Two to three consecutive checks each way is a reasonable starting point — tune it against your actual failure modes, not a default you never revisited.

Session Persistence (Sticky Sessions)

Some applications store session state in the process that handled the first request — an in-memory shopping cart, a login session never externalized to shared storage — and need every subsequent request from that client to land on the same backend. Two mechanisms do it:

  • Cookie-based (L7 only). The load balancer inserts or reads a cookie identifying which backend owns this client's session. This is the more reliable mechanism because it doesn't depend on the client's network path staying constant.
  • Source-IP based (L4 or L7). Hash the client IP to a backend, as above. It breaks down behind NAT (many clients, one visible IP) and when a client's IP changes mid-session (mobile networks do this constantly).

The architectural fix is usually better than either mechanism: externalize session state to shared storage (Redis, a database) so any backend can serve any request, and persistence becomes unnecessary. Stateless backends also make rolling deploys, autoscaling, and failover simpler across the board — persistence is a workaround for state that shouldn't live in the process, not a feature to reach for by default.

The Platforms: HAProxy, nginx, F5, and Cloud LBs

PlatformTypeStrengthBest fit
HAProxy[1]Software, L4/L7Extremely high performance per core, mature health checks, a real stats/admin interface, and an ACL model — despite the name, these are named match conditions on the request (this host header, that URL path) that routing rules then test against, not access control listsThe default self-hosted choice for TCP and HTTP load balancing; the reference implementation most others get compared against
nginx / nginx Plus[2]Software, primarily L7 (reverse proxy first)Doubles as a web server, reverse proxy, and cache; the open-source core is nearly everywhere alreadySites that want one tool for TLS termination, static content, and basic load balancing without a separate LB tier
F5 BIG-IP (LTM)[3]Hardware appliance or virtual edition, L4/L7Deep enterprise feature set — iRules for custom traffic logic, integration with a web application firewall that inspects requests for attack patterns before they reach a backend, extensive protocol supportLarge enterprise estates that need the feature depth and are willing to pay for the license and the appliance
Cloud load balancers (AWS ALB/NLB[4], Azure Load Balancer/App Gateway/Front Door[5], GCP LB)Managed service, L4 and L7 variantsNo infrastructure to run or patch, native integration with autoscaling and health checks, HA built inCloud-native workloads where you don't want to operate the LB tier yourself; the default for anything already living in one cloud

The decision usually reduces to two questions: are you on-prem or cloud-native, and do you need protocol-level customization a managed service won't give you. Cloud-native workloads should default to the cloud provider's LB — it removes an entire operational surface. On-prem or hybrid estates land on HAProxy or nginx for cost and control, or F5 when the enterprise feature set (and its price tag) is already justified elsewhere in the stack.

TLS: Termination, Passthrough, and Re-Encryption

Where TLS is decrypted determines what the load balancer can route on and what stays encrypted end to end:

  • Termination. The load balancer holds the certificate, decrypts the connection, and forwards plaintext (or a new TLS connection) to the backend. This is what makes L7 routing possible — the load balancer needs the decrypted request to read the host and path — and it centralizes certificate management in one place instead of on every backend.
  • Passthrough. The load balancer forwards the encrypted TCP stream untouched, routing only on what it can see without decrypting — typically the SNI (Server Name Indication) hostname in the TLS handshake. This keeps the traffic encrypted all the way to the backend, at the cost of losing any routing decision that needs the HTTP layer.
  • Re-encryption (TLS bridging). The load balancer terminates the client connection, then opens a new, separately encrypted connection to the backend. This gets you L7 routing and encryption on both hops — the standard pattern for anything handling regulated data, at the cost of a second certificate to manage and a second TLS handshake's worth of CPU.

TLS termination can fit a controlled backend network. Use re-encryption when the threat model, compliance requirements, tenant boundaries, or network path require confidentiality and peer authentication beyond the load balancer.

A Worked Example: An HAProxy Config for a Web Tier

The shape of an HAProxy config for a TLS-terminating, host-routed web tier with least-connections balancing and an HTTP health check. The syntax is HAProxy 2.x; confirm directive names against your installed version before you deploy.

# /etc/haproxy/haproxy.cfg — frontend + two backends, routed by Host header
global
    maxconn 50000
    log stdout format raw local0

defaults
    mode http
    timeout connect 5s
    timeout client 30s
    timeout server 30s
    option httplog

frontend web_front
    bind *:443 ssl crt /etc/haproxy/certs/site.pem
    acl is_api hdr(host) -i api.example.com
    use_backend api_servers if is_api
    default_backend web_servers

backend web_servers
    balance leastconn
    option httpchk GET /healthz
    http-check expect status 200
    server web01 10.0.1.11:8080 check inter 2s fall 3 rise 2
    server web02 10.0.1.12:8080 check inter 2s fall 3 rise 2

backend api_servers
    balance leastconn
    option httpchk GET /healthz
    http-check expect status 200
    server api01 10.0.1.21:8080 check inter 2s fall 3 rise 2
    server api02 10.0.1.22:8080 check inter 2s fall 3 rise 2

Two checks confirm it's actually working, not just running:

# Reload after a config change (validate first — a bad config
# should never take the running config down)
haproxy -c -f /etc/haproxy/haproxy.cfg && systemctl reload haproxy

# Watch backend state live via the stats socket
echo "show stat" | socat stdio /run/haproxy/admin.sock

Validate before you reload, every time. HAProxy's -c check flag catches a syntax error before it reaches the running process — skipping it is how a typo takes down a load balancer that was otherwise fine. Confirm the current directive names and defaults against your installed HAProxy version's documentation; the config surface has grown across major versions and a directive from an old blog post may not match what you're running.

High Availability for the Load Balancer Itself

A load balancer that removes the backend tier's single point of failure while being one itself has only moved the problem. Two patterns fix that:

  • Active-passive with a floating IP. Two load balancer instances, a shared virtual IP managed by Keepalived (VRRP) or a similar protocol, and automatic failover if the active instance stops responding. This is the standard self-hosted pattern and the one covered in more depth in the companion article on high-availability infrastructure.
  • Active-active behind DNS or anycast. Multiple load balancer instances all live and serving, with traffic spread across them by DNS round robin, by a global server load balancing (GSLB) layer that hands each client the address of a healthy site based on location and availability, or by anycast — advertising the same IP address from several locations and letting the network itself deliver each client to the nearest one. This scales further than active-passive but adds its own coordination problem — session state and rate limits now span multiple LB instances unless they share state.

Cloud load balancers make this moot in the usual case — the provider operates the HA pair (or the anycast fleet) for you, which is one more reason "use the cloud provider's LB" is the right default when the workload is already cloud-native.

When a Load Balancer Is the Wrong Fix

Not every service needs a dedicated load balancing tier:

  1. A single-instance service. There's nothing to balance across. Adding an LB in front of one backend adds a hop and an HA problem without adding availability.
  2. DNS round robin is genuinely enough. For low-stakes services where a client retrying against a different IP on failure is an acceptable failure mode, DNS round robin across a few backends is simpler than standing up an LB tier — with the caveat that it can't do health-aware failover or fine-grained routing.
  3. A reverse proxy alone covers it. A single nginx instance in front of one or two backends, doing TLS termination and basic routing, is not "load balancing architecture" — it's a reverse proxy, and treating it as more than that is over-engineering a problem that doesn't exist yet.

Rule of Thumb: Stand up a dedicated load balancing tier the moment you have more than one backend that needs to look like one service, or the moment "which backend" needs to depend on anything the client didn't explicitly choose. Below that, a reverse proxy or DNS is enough, and the extra HA pair, the extra config surface, and the extra thing to patch are cost without benefit.


References

  1. HAProxy Technologies — "HAProxy Configuration Manual": frontends, backends, balancing algorithms, health checks, and ACLs. HAProxy Documentation, current.
  2. F5, Inc. — "NGINX Documentation": reverse proxy, load balancing, and TLS termination configuration. NGINX Documentation, current.
  3. F5, Inc. — "BIG-IP Local Traffic Manager (LTM) documentation": iRules, health monitors, and traffic management profiles. F5 Technical Documentation, current.
  4. Amazon Web Services — "Elastic Load Balancing documentation": Application Load Balancer and Network Load Balancer feature comparison. AWS Documentation, current.
  5. Microsoft — "Azure load balancing options": Load Balancer, Application Gateway, and Front Door decision guidance. Microsoft Learn, current.
← Back to Articles ← Previous: Container Security Next: DNS and Network Redundancy →