System Design Part 2 From one machine to many

Load Balancing in Depth: L4 and L7, Algorithms, Health Checks, and Connection Draining

Bill.Lin 19 min read

System Design series Part 2-2 | Previous: Vertical Scaling, Horizontal Scaling, and Stateless Services | Next: Caching in Depth | Series map

Read first: Part 1-1 The Journey of an HTTP Request.

Scenario and problem

Your service is now stateless, with a Load Balancer in front and ten instances behind it. One day, three things happen:

  1. One instance’s processing time goes from 10 ms to 100 ms because a neighbor is stealing its CPU. It has not crashed, its health check still returns 200, and the Load Balancer keeps sending it one tenth of the traffic: that tenth of your users keeps timing out
  2. Every deploy, a short burst of 502s shows up in monitoring, without fail
  3. The database stalls for 3 seconds. Because the health check includes the database, all ten instances are marked unhealthy at the same time, and the whole site is down for far longer than the 3-second database stall
The Load Balancer in front of ten instances1 / 4
The Load Balancer in front of ten instancesUsersLoad BalancerThe slow oneDatabaseThe other 9UsersLoad BalancerThe slow oneThe other 9All traffic1/109/10Load BalancerThe slow oneUsersStill gets 1/1010x slower, health still 2001 in 10 keep timing outThe other 9Load BalancerUsersDeploying, shut downStill sending502DatabaseThe slow oneThe other 9Load BalancerStalls for 3 sCheck DBCheck DBAll ten unhealthy
  1. When things are normalThe service is already stateless, and the Load Balancer spreads traffic evenly across ten instances.
  2. Slow, but not downOne instance loses its CPU to a neighbor, and its processing time goes from 10 ms to 100 ms. It has not crashed, its health check still returns 200, and the Load Balancer keeps sending it one tenth of the traffic, so that tenth of your users keeps timing out.
  3. A burst of 502s on every deployDuring a deploy the instance is simply shut down before the Load Balancer has taken it out of the list. New requests sent to it and requests it has not finished both turn into 502s.
  4. DB stalls 3 s, whole site stopsThe health check includes a database check. The database stalls for 3 seconds, all ten instances are marked unhealthy at the same time and removed from the list, and the site has no instance left. After the database recovers, each instance must still pass several checks in a row before it is added back, so the outage lasts far longer than 3 seconds.

These three incidents map to the three core questions of a Load Balancer: how to distribute traffic, how to judge health, and how to bring instances in and out.

The simplest approach and its limits: DNS Round Robin

The simplest form of load balancing is to put several A records in DNS and let the client pick an IP itself. Its problems:

  • No health checks: when a server dies, DNS keeps handing out its IP
  • Removal is not immediate: clients, resolvers, and the JVM all cache DNS results, so a DNS change takes effect only after the TTL expires
  • The granularity is too coarse: once a client has an IP, all its later requests go to the same server

DNS is good for coarse-grained distribution such as “send users to the nearest data center” (GeoDNS); distribution inside a data center still belongs to a real Load Balancer.

Core mechanism

L4 and L7

flowchart LR
    C1[Client] -- "TCP connection" --> L4["L4 Load Balancer<br/>Sees: IP, port"]
    L4 -- "Forwards the whole connection" --> B1[Backend]
    C2[Client] -- "HTTPS" --> L7["L7 Load Balancer<br/>Terminates TLS<br/>Sees: method, path, header, cookie"]
    L7 -- "Assigns each request" --> B2[Backend]
L4 (transport layer) L7 (application layer)
What it sees IP, port, TCP/UDP HTTP method, path, header, cookie
Unit of distribution Connection Request
TLS Can pass it through (passthrough) for the backend to terminate Must terminate TLS to see the HTTP content
What it can do Very high throughput, low latency, any TCP protocol Path-based routing, retries, header rewriting, gradual rollouts, WAF
Typical products AWS NLB, LVS, HAProxy in TCP mode AWS ALB, Nginx, Envoy, HAProxy in HTTP mode

The “unit of distribution” row matters most. HTTP/2 and gRPC multiplex a large number of requests over one long-lived connection. L4 can only decide which server that connection goes to; once the connection is up, every request on it goes to the same server. The result: one client with heavy traffic saturates one backend while the others sit idle, and newly added instances get none of the traffic on existing connections. These protocols need L7 or client-side load balancing.

Algorithms: how they differ with a slow node

Compare them with a simulation: 10 backends, one of which takes 100 ms to handle a request while the other 9 take only 10 ms; 500 requests per second arrive at random following a Poisson distribution, and each server handles one request at a time while the rest wait in a queue.

Full simulation (JDK 21, run it directly with java LoadBalancerSimulation.java)
java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Random;

public class LoadBalancerSimulation {

    static final int SERVERS = 10;
    static final int REQUESTS = 200_000;
    static final double ARRIVALS_PER_MS = 0.5;               // 500 requests per second
    static final double[] SERVICE_MS = new double[SERVERS];   // how long each server takes per request

    static {
        Arrays.fill(SERVICE_MS, 10);   // 9 normal servers: 10 ms
        SERVICE_MS[0] = 100;           // 1 slow server (GC, a neighbor stealing CPU): 100 ms
    }

    interface Picker {
        int pick(int requestNo, int[] inFlight, Random random);
    }

    public static void main(String[] args) {
        run("Round Robin", (n, inFlight, r) -> n % SERVERS);
        run("Random", (n, inFlight, r) -> r.nextInt(SERVERS));
        run("P2C", (n, inFlight, r) -> {                 // pick two at random, choose the one with fewer in flight
            int a = r.nextInt(SERVERS);
            int b = r.nextInt(SERVERS);
            return inFlight[a] <= inFlight[b] ? a : b;
        });
        run("Least Outstanding", (n, inFlight, r) -> {   // compare all, choose the one with the fewest in flight
            int best = 0;
            for (int s = 1; s < SERVERS; s++) {
                if (inFlight[s] < inFlight[best]) {
                    best = s;
                }
            }
            return best;
        });
    }

    @SuppressWarnings("unchecked")
    static void run(String name, Picker picker) {
        Random random = new Random(42);
        ArrayDeque<Double>[] completions = new ArrayDeque[SERVERS];
        double[] lastFinish = new double[SERVERS];
        for (int i = 0; i < SERVERS; i++) {
            completions[i] = new ArrayDeque<>();
        }
        int[] inFlight = new int[SERVERS];
        double[] latency = new double[REQUESTS];
        int toSlowServer = 0;
        double now = 0;

        for (int n = 0; n < REQUESTS; n++) {
            now += -Math.log(1 - random.nextDouble()) / ARRIVALS_PER_MS; // Poisson arrivals
            for (int s = 0; s < SERVERS; s++) {                          // remove completed requests
                while (!completions[s].isEmpty() && completions[s].peekFirst() <= now) {
                    completions[s].pollFirst();
                }
                inFlight[s] = completions[s].size();
            }
            int s = picker.pick(n, inFlight, random);
            double start = Math.max(now, lastFinish[s]);                 // single worker, FIFO queue
            double finish = start + SERVICE_MS[s];
            lastFinish[s] = finish;
            completions[s].addLast(finish);
            latency[n] = finish - now;
            if (s == 0) {
                toSlowServer++;
            }
        }

        Arrays.sort(latency);
        System.out.printf("%-18s slow=%5.2f%%  p50=%6.0f ms  p99=%9.0f ms%n",
                name, 100.0 * toSlowServer / REQUESTS,
                latency[REQUESTS / 2], latency[(int) (REQUESTS * 0.99)]);
    }
}

Output (slow is the share of traffic sent to the slow server):

text
Round Robin        slow=10.00%  p50=    10 ms  p99=  1439295 ms
Random             slow=10.00%  p50=    12 ms  p99=  1439619 ms
P2C                slow= 2.00%  p50=    10 ms  p99=      249 ms
Least Outstanding  slow= 1.99%  p50=    10 ms  p99=      136 ms
  • Round Robin and Random see nothing of the backends’ state: the slow server can handle only 10 requests a second but still gets 10% (50 a second), so its queue grows by 40 every second, without limit. In the simulation the p99 reaches 24 minutes; a real system would time out first, and the result is a constant 10% error rate
  • P2C (Power of Two Choices): pick two servers at random each time and choose the one with fewer requests in flight. Because the slow server has a longer queue, it is naturally chosen less often; its traffic drops to 2%, close to what it can actually handle
  • Least Outstanding: compares all backends every time and performs best, but needs the live state of every node

If comparing all of them is best, why do large systems often use P2C? Because the Load Balancer itself usually runs on many machines, and the state each one sees is delayed. If they all pick “the least busy one right now”, every LB dumps traffic on the same server at the same instant, overloads it, and then moves on together to the next one. P2C’s randomness avoids this herd behavior while keeping most of the benefit. In theory, with n machines and purely random assignment, the busiest machine’s load is about ln n ÷ ln ln n; picking two at random and taking the less busy one brings it down to about ln ln n ÷ ln 2, an exponential improvement.

Note also that the slow server’s health check was healthy the whole time. Active health checks cannot catch a gray failure, where a node is slow but not dead; only algorithms that look at live load, or passive outlier detection, can.

Health checks: what to check and what not to

Check Question it answers Action on failure What not to put in it
Liveness Is the process still alive? Is it deadlocked? Restart the instance Any external dependency
Readiness Can this instance take traffic right now? (warm-up done, not shutting down) Temporarily remove it from the LB’s list Dependencies shared by all instances (database, Redis)
Passive check Error rate and timeout ratio of real traffic Remove it for a while —

The site-wide outage in scenario 3 came from putting the shared database into readiness: the database stalled, and all ten instances went unhealthy at once. On Kubernetes, the Service is then left with no endpoints and every request fails immediately; even after the database recovers, each instance must pass several checks in a row before it is added back to the list. To avoid this, AWS ALB is designed to fail open when every target in a target group is unhealthy, and keeps sending traffic to all targets. That amounts to admitting that “all unhealthy” usually means the check itself is wrong, not that every server is broken. A better approach is to let requests keep coming in and have the application handle database errors itself (timeouts, circuit breaking, graceful degradation), so it can at least return cached data or a friendly error message.

Liveness checking external dependencies is even worse: when the database goes down, all instances are restarted over and over, and the cold starts during those restarts reduce how much they can handle once the database recovers.

Another thing people often overlook is detection time: detection time = check interval × consecutive failure threshold. With the AWS ALB defaults (30-second interval, 2 consecutive failures to remove, 5 consecutive successes to add back), a dead instance takes about 60 seconds to be removed, and about 150 seconds to be added back after it recovers.

Bringing instances in and out: connection draining and slow start

  • Connection draining (deregistration delay): after an instance is removed from the list, the LB stops sending it new requests but waits for in-flight requests to finish. Too short a wait cuts off long requests; too long a wait slows down deploys (AWS ALB defaults to 300 seconds). Set it to a little more than your longest request time
  • Slow start: right after a new instance starts, the JIT has not compiled the hot code yet, the local cache is empty, and the connection pool has not been built. If it gets its full share of traffic immediately, latency in the first few tens of seconds looks ugly. You can configure slow start on the LB so traffic ramps up gradually, or warm the instance up before it declares itself ready

Keep-alive: whose timeout should be longer

Part 1 noted that the client’s idle timeout should be shorter than the server’s. The same applies between the LB and the backend, except that here the LB is the client and the backend is the server:

text
LB idle timeout (e.g. ALB 60 s) < backend keep-alive timeout (e.g. 75 s)

If it is the other way round, the backend closes an idle connection first; if the LB uses that connection to send a request at the same instant, it gets a connection reset and returns a 502 to the user. This error is intermittent: rare and hard to reproduce, so it often gets dismissed as “the network hiccuped”. The general rule: the side that reuses the connection should have the shorter idle timeout.

Comparing options

Algorithms

Algorithm How it works Good for Weakness
Round Robin Takes turns Identical backends, requests of similar cost Cannot see backend state; slow nodes still get their share
Weighted Round Robin Takes turns by weight Backends of different sizes Weights are static and cannot reflect live conditions
Random Random Multiple LBs that share no state Same as Round Robin
Least Connections / Outstanding Picks the one with the fewest in flight Requests with very different costs, possible slow nodes Needs global live state; multiple LBs herd together
P2C Picks two at random, chooses the less busy one Large scale, many LBs Must track in-flight requests per server
Hash / consistent hashing The key decides which server Cache affinity: the same key always goes to the same server Hot keys cause uneven load (see the Consistent Hashing post)

Service meshes and RPC frameworks such as Linkerd and Finagle often use P2C combined with EWMA (exponentially weighted moving average) latency, which accounts for both in-flight requests and recent response times.

Server-side vs client-side load balancing

Server-side (central LB) Client-side (the caller picks)
How Every request goes through the LB first The caller gets the list from a service registry and picks one itself
Network hops One more hop One fewer hop
Long-lived connections (gRPC) Uneven with L4, needs L7 The caller can distribute per request
Implementation cost Concentrated in the LB, language-agnostic Every language and every client must implement it
Examples ALB, Nginx, Envoy Spring Cloud LoadBalancer, gRPC client, service mesh sidecar

Client-side load balancing needs service registration and discovery, which waits until Service Discovery in Part 7.

In Java

1. A client-side P2C implementation

java
public final class P2cLoadBalancer {

    private final List<Endpoint> endpoints;

    public P2cLoadBalancer(List<URI> uris) {
        this.endpoints = uris.stream().map(Endpoint::new).toList();
    }

    public <T> T call(Function<URI, T> request) {
        Endpoint chosen = choose();
        chosen.inFlight.incrementAndGet();
        try {
            return request.apply(chosen.uri);
        } finally {
            chosen.inFlight.decrementAndGet();   // always decrement, on success or failure
        }
    }

    private Endpoint choose() {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        Endpoint a = endpoints.get(random.nextInt(endpoints.size()));
        Endpoint b = endpoints.get(random.nextInt(endpoints.size()));
        return a.inFlight.get() <= b.inFlight.get() ? a : b;
    }

    private static final class Endpoint {
        final URI uri;
        final AtomicInteger inFlight = new AtomicInteger();

        Endpoint(URI uri) {
            this.uri = uri;
        }
    }
}

The core is just the three lines in choose(). inFlight must be decremented in finally; otherwise a single exception leaves one server’s count permanently too high, and it never gets traffic again. The two random picks can land on the same server; in practice the effect is small, and if you want to avoid it, pick the second one from the remaining nodes.

2. Readiness and liveness in Spring Boot

yaml
management:
  endpoint:
    health:
      probes:
        enabled: true
      group:
        readiness:
          include: "readinessState"   # the default: leaves shared dependencies such as db and redis out

By default, Spring Boot adds no external dependency to readiness or liveness. This is deliberate: whether to include one is the application’s own call. Only dependencies “unique to this instance” (for example a local temp directory or a sidecar) belong in readiness.

Warm-up: Spring Boot sets readiness to accepting traffic only after every ApplicationRunner and CommandLineRunner has finished. So if you put warm-up logic in a runner, the LB is guaranteed not to send traffic before warm-up completes:

java
@Component
public class CacheWarmUpRunner implements ApplicationRunner {

    private final ProductCatalog catalog;

    public CacheWarmUpRunner(ProductCatalog catalog) {
        this.catalog = catalog;
    }

    @Override
    public void run(ApplicationArguments args) {
        catalog.preloadHotProducts();   // load hot products into the local cache, and let the JIT compile the hot paths early
    }
}

Manual draining: to take an instance out of traffic temporarily (for example while investigating a problem), switch its readiness to refusing traffic:

java
AvailabilityChangeEvent.publish(eventPublisher, this, ReadinessState.REFUSING_TRAFFIC);

3. Nginx upstream configuration

nginx
upstream order_service {
    least_conn;
    server 10.0.1.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.12:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.13:8080 max_fails=3 fail_timeout=10s;
    keepalive 32;                        # idle upstream connections kept per worker
}

server {
    location /api/ {
        proxy_pass http://order_service;
        proxy_http_version 1.1;          # upstream keep-alive needs HTTP/1.1
        proxy_set_header Connection "";  # clear the Connection header sent by the client
        proxy_connect_timeout 1s;
        proxy_read_timeout 5s;
        proxy_next_upstream error timeout http_502 http_503;
        proxy_next_upstream_tries 2;
    }
}

A few things that are easy to misread:

  • Open-source Nginx has only passive health checks: max_fails=3 fail_timeout=10s means “after 3 failures within 10 seconds, send it no traffic for the next 10 seconds”. The active health_check is an NGINX Plus feature
  • Without proxy_http_version 1.1 and an empty Connection, keepalive has no effect: every request opens a new TCP connection to the backend
  • proxy_next_upstream does not retry non-idempotent requests by default: if a POST, PATCH, or similar request fails after it has been sent, Nginx will not resend it to another server unless you explicitly add non_idempotent. That is the right default; do not turn it on casually, or one order request may be processed twice

4. The backend’s keep-alive timeout

properties
# ALB idle timeout is 60 seconds; the backend's must be longer
server.tomcat.keep-alive-timeout=75s

When keep-alive-timeout is not set, Tomcat falls back to connection-timeout. The most dangerous cases are the two sides being exactly equal, or the backend’s being shorter than the LB’s.

5. Getting the real client IP

Behind an L7 LB, every source IP the backend sees is the LB’s. Rate limiting, audit logs, and region detection all go wrong as a result. In Spring Boot, configure it to trust the headers sent by the proxy:

properties
server.forward-headers-strategy=native

Tomcat trusts only proxies within server.tomcat.remoteip.internal-proxies (by default, the various private address ranges), and searches X-Forwarded-For from the right to the left; the first IP outside the trusted range is the client IP. A value forged by the client ends up on the far left, so it is ignored. The most common vulnerability is actually writing request.getHeader("X-Forwarded-For") yourself and taking the first value: the client can put anything it wants there.

Pitfalls and gotchas

  • Health checks that check shared dependencies: when the database stalls, all instances are removed at once, and a partial failure becomes a site-wide outage
  • Liveness checking external dependencies: when an external service goes down, all instances get restarted over and over
  • Health checks that only check “alive”: a node that is slow but not dead keeps taking traffic. Pair them with a load-aware algorithm or passive outlier detection
  • The LB retrying non-idempotent requests: a timeout does not mean the backend did not process the request, and resending can create duplicate orders. Write requests that need retries must be made idempotent first (Part 5)
  • Retrying at every layer: if the client, the LB, and service-to-service calls each make up to 3 attempts, one request can be amplified to as many as 3 × 3 × 3 = 27 calls at the bottom of the stack, crushing it exactly when the system is most fragile (Timeouts, Retries, Backoff, and Jitter in Part 6)
  • Long-lived connections are unbalanced under L4: HTTP/2, gRPC, and WebSocket connections stay pinned to one server once established. Existing connections are not redistributed after you add instances; set a maximum connection lifetime so clients reconnect periodically
  • Backend keep-alive shorter than the LB’s: intermittent 502s
  • Badly tuned draining time: too short cuts off in-flight requests, too long makes every deploy take several minutes
  • New instances taking full traffic on a cold start: latency spikes for the first few tens of seconds, falsely triggering alerts or autoscaling
  • No trusted proxy configured: every request’s source IP is the LB’s, and all IP-based rate limiting stops working

Security

  • Only the client-to-LB leg is encrypted: once TLS terminates at the LB, traffic from the LB to the backend is plaintext. Inside one private network that is usually acceptable, but with compliance requirements or a zero-trust architecture, re-encrypt to the backend (Part 8)
  • A WAF can only sit at L7: L4 cannot see HTTP content, so rules against SQL injection or path probing can only run on an L7 LB or a CDN
  • Management endpoints exposed along with everything else: the LB forwards every path to the backend, so /actuator becomes public too. Put Actuator on a separate management.server.port, have the LB forward only the application’s port, and point the health check at the management port over the internal network
  • Parsing X-Forwarded-For yourself: taking the leftmost value as the client IP lets the client choose its own IP, and all IP-based rate limiting and auditing can be bypassed (see item 5 under In Java above)

When to use it, and when not to

  • In the cloud: use L7 (ALB) for HTTP services; use L4 (NLB) when you need a static IP, very low latency, or a non-HTTP protocol
  • Self-hosted: Nginx, HAProxy, and Envoy are all mature. Choose Envoy when you need dynamic configuration, gRPC awareness, and fine-grained retries and circuit breaking
  • Algorithm: if least outstanding or P2C is available, use it first; when backends are identical and requests are fast and uniform, Round Robin is enough
  • When to re-evaluate: p99 differs widely across instances; adding instances does not lower latency (long-lived connections may not have been redistributed); the error rate rises noticeably during deploys

References

Comments