Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 25 min · revision 1

Where load balancers sit: L4, L7, reverse proxies and gateways

Compare layer 4 and layer 7 load balancers, reverse proxies and API gateways by what they can see, what they cost and how they fail, and decide which edge concerns a gateway should own.

Contentsand lesson path

What you will learn

  • Compare L4 and L7 load balancing, reverse proxies and API gateways by features, cost and failure behavior, and decide which concerns (routing, TLS and auth offloading, response aggregation) the gateway should own.

Prerequisites: Scalability Fundamentals

01. Why it matters

As soon as a service runs on more than one instance, something has to decide which instance receives each piece of work. That component is a load balancer: it accepts traffic on one stable address and spreads it over a pool of instances, often called backends or upstreams, while skipping instances that look unhealthy. Clients only know the stable address, so instances can be added, replaced or removed without telling anyone.

Because the balancer sits in the path of every request, the kind you choose decides what you can route on (an IP address, or a URL path and a cookie), what each request costs, and what users see when something fails. The wrong layer leads to problems that look mysterious later, such as one backend doing most of the work or a 504 that no application log explains.

The networking lesson on L4 and L7 used the two layers as a debugging map; this lesson uses them to design.

02. Layer 4: balancing connections

A layer 4 (L4) balancer works with transport information: source and destination IP addresses, ports and the protocol (TCP or UDP). It does not read HTTP. When a new connection or flow starts, it chooses a backend, and every later packet of that flow goes to the same backend. Large L4 tiers spread packets over many balancer machines; Google's Maglev, for example, combines connection tracking with consistent hashing of the flow's addresses and ports, so that a connection usually keeps reaching the same backend even when another balancer machine handles its packets; when the set of backends changes, a small share of connections can still be remapped.

L4 balancers run in two broad modes:

  • Passthrough: packets are forwarded, so the backend sees the real client address and TLS stays end to end between client and backend. Some designs even let replies skip the balancer (direct server return).
  • Proxy mode: the balancer accepts the TCP connection and opens a new one to the backend. The backend then sees the balancer's address unless both sides speak the PROXY protocol, a small header that carries the original client address across TCP proxies.

The strengths follow from not reading HTTP. An L4 balancer can carry any TCP-based protocol, such as PostgreSQL or MQTT, and many also handle UDP. It does little work per byte, so it usually costs less CPU than an L7 proxy for the same traffic (measure your case rather than trusting headline numbers), and in passthrough mode it never holds your TLS keys.

The weakness is the unit of balancing. Once a connection is placed, all of its requests follow it. That is fine for many short connections, but HTTP/2, gRPC, WebSockets and database pools keep a few connections open for a long time. The script below shows what happens when one batch client keeps a single busy connection open next to eight browsers.

Python 3.12 · conn_vs_request.py
"""Balance per connection (L4) or per request (L7): who carries the load?"""
from collections import Counter

BACKENDS = ["b1", "b2", "b3"]
# (client, requests it sends over ONE long-lived connection)
CONNECTIONS = [("batch-job", 900)] + [(f"browser-{i}", 30) for i in range(1, 9)]


def per_connection() -> Counter:
    """L4: pick a backend once per connection; every request follows it."""
    load = Counter()
    for i, (_client, requests) in enumerate(CONNECTIONS):
        load[BACKENDS[i % len(BACKENDS)]] += requests
    return load


def per_request() -> Counter:
    """L7: the proxy picks a backend again for every request it reads."""
    load, turn = Counter(), 0
    for _client, requests in CONNECTIONS:
        for _ in range(requests):
            load[BACKENDS[turn % len(BACKENDS)]] += 1
            turn += 1
    return load


total = sum(requests for _client, requests in CONNECTIONS)
for name, load in [("per connection", per_connection()),
                   ("per request", per_request())]:
    shares = "  ".join(f"{b} {100 * load[b] / total:4.1f}%" for b in BACKENDS)
    print(f"{name:<15} {shares}")
Expected output (deterministic)
per connection  b1 84.2%  b2  7.9%  b3  7.9%
per request     b1 33.3%  b2 33.3%  b3 33.3%

Both runs use round robin, yet the per-connection run puts 84.2% of all requests on b1, because the batch job's 900 requests travel on the one connection that landed there. Per-request balancing gives each backend exactly a third. Changing the algorithm cannot fix the first case; changing the unit can: balance at L7 or in the client, or close long connections now and then so that they are placed again.

03. Layer 7: balancing requests

A layer 7 (L7) balancer terminates the client's TCP connection, usually terminates TLS as well, parses each HTTP request and then sends it over its own connection to a backend. Because it reads every request, it can route by host name, path, header or cookie, choose a backend per request, retry a failed idempotent request (one that is safe to repeat, such as a GET) on another backend, add headers such as X-Forwarded-For, enforce body size limits and timeouts, compress responses and cache them.

That power has costs you should name in a design review:

  • CPU and memory. TLS handshakes and HTTP parsing cost more than forwarding packets, and buffering request bodies uses memory.
  • Another hop. Each proxy adds some latency and one more process to deploy, patch and monitor.
  • Plaintext in the middle. The proxy holds TLS keys and sees request contents, so it needs the same protection as your application. Re-encrypt to the backend if the network between them is not trusted.
  • Its own behaviour becomes your API's behaviour. Proxy timeouts, size limits and retry rules decide what clients see.

The last point surprises people during incidents: when an L7 proxy cannot get a good answer, it creates the error. RFC 9110 defines 502 (Bad Gateway) as a gateway receiving an invalid response from an inbound server and 504 (Gateway Timeout) as a gateway not receiving a timely response; 503 means the server cannot handle the request right now, and many proxies use it when no healthy backend is left. If the proxy's upstream timeout is 20 s and a backend needs 35 s, the user gets a 504 after 20 s, and the backend usually keeps working unless it notices that the connection has closed.

04. Reverse proxies, gateways and meshes: names for jobs

The names overlap because they describe jobs, not products: NGINX, HAProxy, Envoy and Caddy can each play most of the roles below, and Envoy is the usual sidecar in a service mesh.

  • A reverse proxy accepts connections on behalf of servers behind it. (A forward proxy does the opposite: it acts for clients.) An L7 load balancer is a reverse proxy with a pool and a balancing policy.
  • An API gateway is an L7 reverse proxy specialised for APIs. It is the single entry point for many services and owns concerns that are the same for all of them.
  • A service mesh or client-side balancing moves the decision into each caller, through a library or a sidecar proxy. Internal traffic can then be balanced per request without a central hop.

A real request path often combines several of these, but there is no fixed order. The sketch below is one common arrangement, not a rule: a CDN may terminate TLS before your proxy, a web application firewall may run inside the L7 proxy, internal calls may skip the gateway entirely, and a small system may have a single proxy doing everything.

One possible path (each box is optional, and the order can change)
client --TLS--> [CDN edge] ---> [L4 balancer] ---> [L7 gateway x3] --+--> orders x6
                (optional)      (TCP, no HTTP)     (TLS, auth, routing) +--> search x4
                                                                      +--> users x3

Inside:  orders --> [client-side balancer or sidecar] --> payments x5

The Azure Architecture Center describes three gateway patterns:

  1. Gateway routing: one endpoint routes to many services, or to several versions of one service during a rollout, using L7 rules.
  2. Gateway offloading: shared concerns move to the gateway, such as client-facing TLS, token validation, rate limits, request size limits and request logging. The same guidance says business logic should never be offloaded to it.
  3. Gateway aggregation: one client call fans out to several services and the gateway combines the answers. This helps chatty clients on slow mobile networks, but the combined response is only as fast as its slowest part, so each call needs a timeout and a plan for a partial answer. When aggregation needs domain logic, the guidance suggests a separate aggregation service behind the gateway.

05. What the gateway should own, and how it fails

A useful test: a concern belongs in the gateway when it is the same for every service, can be decided from the request alone, and does not change when one team ships a feature. Checking a token's signature and expiry passes the test. Deciding whether an order qualifies for free delivery fails it, because the rule belongs to one domain, changes with the business and needs that domain's data.

The gateway is also shared infrastructure, so its failure behaviour affects everything behind it:

  • It is a single point of failure unless you run several instances in different zones, usually behind an L4 balancer or several DNS addresses.
  • It is a bottleneck if sized for average traffic, so plan capacity for peaks.
  • A bad configuration push breaks every service at once, so roll out gateway changes in stages, like code.
  • Backends must not be reachable around it, and they should not trust identity headers that a client could forge directly.
A starting point for choosing a layer
Need                                          Reach for
Non-HTTP protocol (PostgreSQL, MQTT, UDP)     L4
Route by host, path, header or cookie         L7 proxy or gateway
TLS kept end to end to the backend            L4 passthrough (or L7 re-encrypt)
Many requests on a few long connections       L7, or client-side balancing
Token checks, rate limits per API key         API gateway
Real client IP at the backend                 L4 passthrough, PROXY protocol,
                                              or L7 with X-Forwarded-For

06. Check your understanding

Practice check · 3 questions

Layers, proxies and gateways

Three scenarios about client addresses, proxy timeouts and a shared gateway tier.

Q1. A fraud-scoring service sits behind an L4 balancer in proxy mode: it accepts each TCP connection and opens a new one to a backend. The service logs show the balancer's address instead of the customer's. Which change gives the service the real client address?
Q2. An L7 proxy has a 30 s upstream timeout. A new endpoint that imports a large CSV file works for 45 s before it sends its first byte. What do users see?
Q3. A company moves TLS termination for 30 services from their own instances onto two shared gateway instances. App CPU drops, but at the daily peak p99 latency now rises for every service at the same time. What is the most likely cause?
Practice only: not graded, not saved, not evidence.

07. Apply it

Draw the request path of a system you know, or of an imaginary shop with web, API and payment services. For each box, write down:

  • the layer it works at, and whether it balances per connection or per request;
  • who terminates TLS, and whether traffic is re-encrypted behind it;
  • its timeouts, and what status code a client sees when the next hop is slow or down;
  • what happens when that box itself fails, and what removes it from the path.

Then test each concern your gateway owns with the question "is it the same for every service?". The lab later in this skill puts Caddy, an L7 reverse proxy, in front of three instances: the first step of the practice task.

08. Review prompt

From memory, explain the difference between balancing per connection and per request, and give one protocol where each is the better choice. Then name two things an API gateway should own, one thing it should not, and two ways a shared gateway can turn a small mistake into an outage for every service behind it.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check