Load Balancing Algorithms and Layer 4 versus Layer 7

Scaling DNS and Load Balancing · 40 min

System Design · Module 5 · Lesson 3 of 4 · 40 min

Load Balancing Algorithms and Layer 4 versus Layer 7

Choose a balancing policy from request cost and connection behavior, then state which routing decisions require HTTP visibility.

Equal request counts are not necessarily equal work; choose a policy using the signals the balancer can actually observe.

01 The idea

The problem this lesson solves

Round robin over A,B,C sends six equal-cost requests A,B,C,A,B,C.

Prerequisite: earlier lessons introduce the vocabulary and shared examples used here. Follow the module order.

Round robinCycling through eligible backends in a defined order.
Least connectionsChoosing using a count of currently active connections.
L7 routingRouting with application-level information such as HTTP host or path.

02 Worked example

Follow one worked example

Load Balancing Algorithms and Layer 4 versus Layer 7 worked diagram01Incoming workConnections or requests02PolicyRound robin / weights03Eligible poolA, B, C04MeasureLatency + saturationLoad Balancing Algorithms and Layer 4 versus Layer 7 compact diagram01Incoming workConnections or requests02PolicyRound robin / weights03Eligible poolA, B, C04MeasureLatency + saturation
Incoming work: Connections or requests • Policy: Round robin / weights • Eligible pool: A, B, C • Measure: Latency + saturation.

Trace the example in order. Follow the same identities, units and state transitions through the diagram and the events below.

1
All eligibleRound robin over A,B,C sends six equal-cost requests A,B,C,A,B,C.
2
Change capacityGive C twice the relative weight when its tested budget is twice as large.
3
Change durationLong-running connections make equal request counts a weak load signal.
4
Change visibilityHost/path routing requires an application-aware policy at the relevant TLS boundary.

Equal request counts are not necessarily equal work; choose a policy using the signals the balancer can actually observe.

03 The method

Mechanisms decisions and a guided tutorial

Work through the explanation in order, then apply it in the tutorial. Each comparison names a cost as well as a benefit.

Choice or conceptPurposeBoundary or cost
Round robinSimilar-cost requestsEqual counts need not mean equal load
Least connectionsVarying connection lifetimesConnections are not equal units of work
L4 / L7Connection routing / application routingChoose based on needed protocol visibility
Weighted round robinDifferent relative capacitiesAssumes weights reflect tested budgets
Hash affinityRelated requests share an ownerSkew and hot keys remain possible

Understand the balancer's visibility

Layer 4 balancing uses transport information such as addresses and ports and commonly selects a backend for a connection. Layer 7 balancing understands application information such as HTTP hostnames and paths when it terminates or can otherwise inspect that traffic. An HTTPS L7 proxy normally terminates TLS and can open a separately protected upstream connection. L7 can route /api and /images differently, but has a broader protocol responsibility.

Choose an algorithm for the workload

Round robin cycles through eligible backends and is a useful baseline when requests have similar costs. Weighted round robin gives a larger share to stronger backends. Least connections can help when connection durations vary, but connection count is an imperfect proxy for work, especially with multiplexing. Hash-based routing preserves affinity, but an unlucky distribution or hot key can overload one backend. No algorithm removes the need to measure backend latency and saturation.

Choose the unit being balanced

A layer-4 balancer commonly selects a backend for a transport connection. A layer-7 proxy can route HTTP requests based on parsed fields. Long-lived or multiplexed connections can carry very different amounts of work, so a count of connections is only a proxy for load.

For equal-cost short requests, round robin provides a simple baseline. For heterogeneous machines, weights can allocate different shares. If connection durations vary, least connections can be helpful, but a connection carrying many concurrent streams complicates the signal. Measure backend saturation and latency rather than infer fairness from one counter.

Work a weighted allocation

With weights 1,1,2, the ideal long-run shares are one quarter, one quarter and one half. Out of 800 equal-cost requests that corresponds to 200,200,400. A finite scheduling sequence can differ and request cost can dominate the result.

Hash affinity can keep related requests on one owner, which helps some caches or sessions, but it can also concentrate hot clients. Adding a server may change placement and cache warmth. Treat affinity, balanced work and fast failover as separate properties that need their own guarantees.

TLS visibility determines routing options

A transport proxy forwarding encrypted bytes cannot simply inspect an HTTP path inside that encrypted stream. An L7 HTTPS proxy normally terminates TLS to parse HTTP, then can protect its upstream connection separately. Path-based routing therefore changes both visibility and responsibility.

Document trusted forwarding headers and source identity. If all requests appear to come from the proxy address, a naive per-IP quota may combine every user. Accept forwarded identity only from trusted intermediaries under the deployment’s policy, not arbitrary client-supplied headers.

Guided tutorial

1. Trace round robin

Assign six numbered requests to three healthy backends.

2. Calculate weights

Allocate 800 requests under 1:1:2 ideal shares.

3. Introduce unequal costs

Make one request ten times more expensive and explain the limitation of request counts.

4. Draw TLS boundaries

Show where HTTP becomes visible and which upstream hop is separately protected.

# Equal-cost baseline: A B C A B C
# Weighted 1:1:2 ideal shares: 25%, 25%, 50%
# L4: addresses / ports / connection policy
# L7: parsed application fields such as host and path
# Inspect saturation and latency, not just selected-request totals.

04 Cheat sheet

Review the decisions

Use this table to explain the mechanism and its limit without memorizing a product name.

Choice or conceptRememberCheck
Round robinSimilar-cost requestsEqual counts need not mean equal load
Least connectionsVarying connection lifetimesConnections are not equal units of work
L4 / L7Connection routing / application routingChoose based on needed protocol visibility
Weighted round robinDifferent relative capacitiesAssumes weights reflect tested budgets
Hash affinityRelated requests share an ownerSkew and hot keys remain possible
Round robinCycling through eligible backends in a defined order.
Least connectionsChoosing using a count of currently active connections.
L7 routingRouting with application-level information such as HTTP host or path.

05 Where & why

Check the primary references

Use official references for protocol and implementation details. The questions here are teaching prompts.

Primary reference
NGINX HTTP load balancing

Read NGINX HTTP load balancing

Primary reference
DNS concepts

Read DNS concepts

Primary reference
Google SRE cascading failures

Read Google SRE cascading failures

State the implementation version and the workload assumptions when defending your own design.

06 Interview questions

Explain the reasoning out loud

Answer before opening the explanation. The questions progress from vocabulary to decisions and failure behavior.

What does Round robin mean?
Cycling through eligible backends in a defined order.
What does Least connections mean?
Choosing using a count of currently active connections.
What does L7 routing mean?
Routing with application-level information such as HTTP host or path.
Why can round robin overload one backend?
Requests can have unequal costs, and backends can have unequal capacities or dependency delays. Equal counts do not imply equal resource use.
Can a plain L4 proxy choose by URL path?
It lacks the required parsed HTTP visibility. Path routing needs application-aware handling at the relevant encryption boundary.
Does least connections measure CPU demand?
No. It observes connection counts, which may correlate imperfectly with work. Multiplexing and request cost can weaken the correlation.
Why are weights assumptions rather than proof?
They should reflect tested relative capacities for the actual workload. Hardware size alone does not establish a reliable weight.
Why must forwarded identity be trusted selectively?
A client can supply its own headers. The application must know which proxy boundary is authorized to assert the original identity.

07 Practice problems

Practice a new case

Solve the new cases before revealing hints. Complete worked solutions follow the set.

Name the proxy

Easy
Classify a corporate browsing proxy and an ingress proxy in front of an API.
Follow-up
The proxy's position alone is less useful than whose behalf it acts on.
Show the hint
Ask whether it represents clients or servers.

Round robin

Easy
Assign requests 1–8 to A,B,C cyclically and count selections.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
Write the sequence first.

Weighted traffic

Medium
Allocate 800 equal-cost requests to backends with weights 1,1,2 under ideal weighted distribution.
Follow-up
The weights are relative shares.
Show the hint
Divide by the sum of weights.

Unequal work

Medium
Two backends receive five requests each, but A’s requests each take ten units of CPU and B’s one unit; compare work.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
Multiply count by cost.

Encrypted routing

Medium
An ingress must route /images and /api on HTTPS; state the required visibility.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
The path is inside HTTP.

Policy choice

Hard
Choose a starting balancing policy for similar short reads and one for mixed long streams; state what to measure.
Follow-up
State the assumption or edge case that makes the answer correct.
Show the hint
No single counter perfectly measures work.

Worked solutions

1. Name the proxy

The corporate browsing proxy is a forward proxy for clients. The ingress proxy is a reverse proxy for the API servers.

2. Round robin

A,B,C,A,B,C,A,B gives A=3, B=3, C=2.

3. Weighted traffic

The total weight is 4. Expected shares are 200,200,400 requests. Short finite scheduling sequences can differ, and equal cost is an assumption.

4. Unequal work

A receives fifty modeled work units and B five. Equal request counts hide a ten-times work difference.

5. Encrypted routing

Use an application-aware proxy that can inspect HTTP at the chosen TLS termination boundary, with a separately defined upstream protection policy.

6. Policy choice

Round robin is a reasonable baseline for similar reads. Connection-aware routing may help streams, but measure active work, backend latency and saturation, including multiplexing and failure behavior before claiming balance.