Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

System Design (High-Level Design)  Module 4 – Networking for system designers

Load balancing: L4 vs L7 and health checks

How layer-4 and layer-7 load balancers differ, how to design health checks that never empty the pool, and how to drain, warm up and pin servers safely.

  • Intermediate
  • 25 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Compare layer-4 and layer-7 load balancing by what each one reads and decides
  • Predict how long-lived connections load the servers behind a layer-4 balancer
  • Design health checks that judge each server on its own, with a detection time you have calculated
  • Plan how servers leave and join the pool, with draining and slow start
  • Decide when sticky sessions are acceptable and what they cost

Before you start

What you’ll learn · Before you start

What you will learn

  • Compare layer-4 and layer-7 load balancing by what each one reads and decides
  • Predict how long-lived connections load the servers behind a layer-4 balancer
  • Design health checks that judge each server on its own, with a detection time you have calculated
  • Plan how servers leave and join the pool, with draining and slow start
  • Decide when sticky sessions are acceptable and what they cost

Before you start

On this page

A careless deploy dropped 2,638 requests in this lesson’s run, and four long-lived connections gave one server 2.44 times its share. A load balancer spreads incoming traffic over a group of servers and stops sending it to servers that fail. Its two kinds differ in how much of that traffic they read. A layer-4 (L4) load balancer: A load balancer that reads only addresses, ports and the transport protocol. It picks a server when a TCP connection or UDP flow starts and sends everything on it to that server. balancer sees only addresses, ports and the transport protocol, so it chooses a server once for each TCP connection or UDP flow and forwards everything on it. A layer-7 (L7) load balancer: A load balancer that ends the client's connection and reads each HTTP request, so it can route by path or header, retry a request elsewhere and spread the requests of one connection. balancer ends the client’s connection, reads each HTTP request and chooses a server for every request, by its path, a header or a cookie if you ask it to. L4 is cheaper and works for any protocol; L7 can route, retry and spread individual requests, for more work per request. Whichever you use, three habits decide whether users notice failures and deploys: health checks that judge each server on its own, draining a server before it leaves, and a slow start when it joins.

An L4 balancer reads ports, an L7 balancer reads requests

The 4 and the 7 are layers of the OSI model: layer 4 is the transport layer (TCP and UDP), layer 7 the application layer (HTTP and the protocols built on it).

An L4 balancer never looks inside the byte stream. Amazon’s Network Load Balancer, which works at layer 4, picks a target for a TCP connection from a hash of the protocol, both addresses and ports, and the TCP sequence number, and keeps that connection on the same target for its whole life (Network Load Balancer). A Kubernetes Service in kube-proxy’s iptables mode is an L4 balancer too: by default it picks a backend pod at random for each new connection (Virtual IPs and Service Proxies). Because it reads nothing above the ports, an L4 balancer can carry any protocol (a database, a message broker, real-time game traffic over UDP) and can pass TLS through untouched, so only the server holds the certificate.

An L7 balancer is a reverse proxy that understands HTTP. It holds two connections, one to the client and one to the server, and makes a decision for every request: Amazon’s Application Load Balancer, which works at layer 7, evaluates its listener rules (path, host, headers, method, query string) and then picks a target from the matching group (Application Load Balancer). It also reuses its connections to each server for the requests of many clients, and adds X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Port headers so that servers still learn who the client was (How Elastic Load Balancing works). The price is work on every request: TLS, parsing and a second hop. gRPC’s own comparison of proxy designs lists higher latency and the proxy’s throughput as the costs of balancing in a proxy (gRPC Load Balancing).

In the figure, look at what each balancer reads and how often it chooses a server; the table under it sets the two side by side:

An L4 balancer sends a whole TCP connection to one server; an L7 balancer reads each HTTP request and routes it by path.Layer 4: one choice per connectionLayer 7: one choice per requestClientL4 balancerreads addresses and ports,never the requestServer Bgets every requeston this connectionClientL7 balancerends TLS, readseach HTTP requestAPI serversImage serversone TCP connectionall of its packetsGET /api/cartGET /img/42.jpg/api/*/img/*

What each kind of balancer sees, and what it decides

Text description of the diagram

The figure has two panels, one above the other.

  1. Layer 4, one choice per connection. A client opens one TCP connection to an L4 balancer, which reads only addresses and ports, never the request inside. It sends all of that connection's packets to one server, server B, so server B gets every request sent on the connection.
  2. Layer 7, one choice per request. A client sends two requests, GET /api/cart and GET /img/42.jpg, to an L7 balancer, which ends the TLS connection and reads each HTTP request. It sends requests whose path starts with /api/ to the API servers and requests whose path starts with /img/ to the image servers.
Layer-4 and layer-7 load balancing
Criterion Layer 4 (L4)Layer 7 (L7)
What it reads Addresses, ports and the protocolThe whole HTTP request: method, path, headers, cookies
What it balances Connections or UDP flowsRequests, even several on one connection
Routes by path or header NoYes
Retries elsewhere Only a failed connection attemptWhole requests, when they are safe to repeat
TLS Can pass it through to the serverUsually ends it, so that it can read the request
Protocols Any protocol over TCP or UDPHTTP/1.1, HTTP/2, gRPC, WebSockets
Work per request Low: nothing to parseHigher: TLS, parsing and its own connections
When to choose Non-HTTP traffic, TLS kept to the server, huge packet ratesWebsites, HTTP APIs and gRPC that need routing or retries

Large sites often use both. An L4 tier spreads connections over a fleet of L7 proxies, and the proxies route each request to a service. Google’s Maglev is a well-documented example of the first tier: a software balancer on ordinary Linux servers, with the network’s routers spreading packets over the Maglev machines (Maglev, NSDI 2016).

Key idea

An L4 balancer reads addresses and ports and chooses once per connection; an L7 balancer reads every request and chooses each time, which lets it route and retry at the price of TLS and parsing.

Checkpoint

Check: What L4 and L7 balancers read

  1. One question One public name must send /api to one service and /img to another. Which balancer can do that?

    Choose one answer.

    Show the answer: One question

    Answer: An L7 balancer, because it reads each request's path

    A path is part of the HTTP request. An L4 balancer reads addresses, ports and the protocol and never looks inside the byte stream, so routing by path is an L7 balancer's job.

An L4 balancer balances connections, not requests

Balancing connections works well while connections are short and similar. It breaks down when a few long-lived connections carry most of the traffic, which is exactly what HTTP/2 and gRPC clients do: they open one connection and send every request over it. Step through four such clients behind an L4 balancer, then a fourth server joining:

Interactive · step by step Four long-lived connections behind an L4 balancer Step through the connections as they open, watch what a new server gets, then the same traffic balanced per request.
Four long-lived connections behind an L4 balancer, step 5 of 5. Showing Mobile gateway, Search service, Billing job, Admin panel, Server A (200 a second), Server B (200 a second), Server C (200 a second), Server D (200 a second). In focus: Mobile gateway, Search service, Billing job, Admin panel.Mobile gateway600 requests a secondSearch service100 requests a secondBilling job50 requests a secondAdmin panel50 requests a secondServer A200 a secondServer B200 a secondServer C200 a secondServer D200 a second

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Connections open. Each client opens one HTTP/2 connection and sends every request on it. The L4 balancer picks a server once per connection, in turn, A, B, C and then A again, and never looks inside.
  2. Load follows connections. Server A carries the mobile gateway and the admin panel: 650 requests a second against 100 for B and 50 for C. The busiest server does 2.44 times its fair share of 267.
  3. Server D joins. A fourth server joins, but no connection is new, so the balancer has nothing to give it. D stays idle until a client reconnects, and the busiest server now does 3.25 times a fair share.
  4. The same traffic at L7. An L7 balancer ends each connection and picks a server for every request. With three servers they get 267, 267 and 266 a second; with four, 200 each, D's quarter at once.
  5. Or make clients reconnect. A server that sends GOAWAY once a connection reaches a maximum age, as gRPC's MAX_CONNECTION_AGE does, makes clients reconnect, and an L4 balancer can then spread the new connections.

This model gives four such clients to three servers and then adds a fourth server. The same program is in every tab, and the lines under the tabs are what it prints:

One program · 14 languages Four long-lived connections, balanced at L4 and at L7

Python 3.14 · main.py

# Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
# all their requests on it: a mobile gateway, search, billing and an admin panel.
RATES = [600, 100, 50, 50]  # requests a second
PINNED = [0, 1, 2, 0]  # the server each connection got when it opened: A, B, C, A
TOTAL = sum(RATES)


def layer4(servers: int) -> list[int]:
    # L4: every request follows its connection to the server picked when it opened.
    load = [0] * servers
    for rate, server in zip(RATES, PINNED):
        load[server] += rate
    return load


def layer7(servers: int) -> list[int]:
    # L7: the balancer reads each request and picks a server for it, round robin here.
    load = [0] * servers
    for i in range(TOTAL):
        load[i % servers] += 1
    return load


def show(label: str, load: list[int]) -> None:
    servers = ", ".join(f"{name} {n}" for name, n in zip("ABCD", load))
    # The busiest server's load against a fair share, in hundredths, rounded.
    ratio = (max(load) * len(load) * 100 + TOTAL // 2) // TOTAL
    print(f"{label}: {servers}; busiest {ratio // 100}.{ratio % 100:02}x a fair share")


rates = ", ".join(str(rate) for rate in RATES)
print(f"Four clients, one connection each, send {rates} requests a second.")
show("L4, 3 servers", layer4(3))
show("L7, 3 servers", layer7(3))
print("Server D joins; no client reconnects.")
show("L4, 4 servers", layer4(4))
show("L7, 4 servers", layer7(4))

In Python: zip pairs each client's rate with the server its connection got, and the busiest ratio is worked out in whole hundredths with //, so no float is printed.

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
const RATES = [600, 100, 50, 50]; // requests a second
const PINNED = [0, 1, 2, 0]; // the server each connection got when it opened: A, B, C, A
const TOTAL = RATES.reduce((sum, rate) => sum + rate, 0);

function layer4(servers) {
  // L4: every request follows its connection to the server picked when it opened.
  const load = new Array(servers).fill(0);
  RATES.forEach((rate, c) => (load[PINNED[c]] += rate));
  return load;
}

function layer7(servers) {
  // L7: the balancer reads each request and picks a server for it, round robin here.
  const load = new Array(servers).fill(0);
  for (let i = 0; i < TOTAL; i++) load[i % servers] += 1;
  return load;
}

function show(label, load) {
  const servers = load.map((n, i) => `${"ABCD"[i]} ${n}`).join(", ");
  // The busiest server's load against a fair share, in hundredths, rounded.
  const ratio = Math.floor((Math.max(...load) * load.length * 100 + TOTAL / 2) / TOTAL);
  const share = `${Math.floor(ratio / 100)}.${String(ratio % 100).padStart(2, "0")}`;
  console.log(`${label}: ${servers}; busiest ${share}x a fair share`);
}

console.log(`Four clients, one connection each, send ${RATES.join(", ")} requests a second.`);
show("L4, 3 servers", layer4(3));
show("L7, 3 servers", layer7(3));
console.log("Server D joins; no client reconnects.");
show("L4, 4 servers", layer4(4));
show("L7, 4 servers", layer7(4));

In JavaScript: Math.floor stands in for integer division, which JavaScript lacks; every value stays far below 2⁵³, so the arithmetic is exact.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
  // Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
  // all their requests on it: a mobile gateway, search, billing and an admin panel.
  static final int[] RATES = {600, 100, 50, 50}; // requests a second
  static final int[] PINNED = {0, 1, 2, 0}; // the server each connection got when it opened
  static final int TOTAL = Arrays.stream(RATES).sum();

  static int[] layer4(int servers) {
    // L4: every request follows its connection to the server picked when it opened.
    int[] load = new int[servers];
    for (int c = 0; c < RATES.length; c++) load[PINNED[c]] += RATES[c];
    return load;
  }

  static int[] layer7(int servers) {
    // L7: the balancer reads each request and picks a server for it, round robin here.
    int[] load = new int[servers];
    for (int i = 0; i < TOTAL; i++) load[i % servers]++;
    return load;
  }

  static void show(String label, int[] load) {
    List<String> servers = new ArrayList<>();
    for (int i = 0; i < load.length; i++) servers.add("ABCD".charAt(i) + " " + load[i]);
    // The busiest server's load against a fair share, in hundredths, rounded.
    int ratio = (Arrays.stream(load).max().orElse(0) * load.length * 100 + TOTAL / 2) / TOTAL;
    String share = ratio / 100 + "." + (ratio % 100 < 10 ? "0" : "") + ratio % 100;
    System.out.println(
        label + ": " + String.join(", ", servers) + "; busiest " + share + "x a fair share");
  }

  public static void main(String[] args) {
    List<String> rates = Arrays.stream(RATES).mapToObj(String::valueOf).toList();
    System.out.println(
        "Four clients, one connection each, send "
            + String.join(", ", rates)
            + " requests a second.");
    show("L4, 3 servers", layer4(3));
    show("L7, 3 servers", layer7(3));
    System.out.println("Server D joins; no client reconnects.");
    show("L4, 4 servers", layer4(4));
    show("L7, 4 servers", layer7(4));
  }
}

In Java: The rates are an int[] because Arrays.stream sums and finds the maximum of a plain int array without boxing.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <algorithm>
#include <numeric>
#include <print>
#include <string>
#include <vector>

// Four clients keep one long-lived HTTP/2 connection each, as gRPC
// clients do, and send all their requests on it: a mobile gateway,
// search, billing and an admin panel.
const std::vector<int> RATES{600, 100, 50, 50}; // requests a second
// The server each connection got when it opened: A, B, C, A.
const std::vector<int> PINNED{0, 1, 2, 0};
const int TOTAL = std::reduce(RATES.begin(), RATES.end());

std::vector<int> layer4(int servers) {
  // L4: every request follows its connection to the server
  // picked when it opened.
  std::vector<int> load(servers);
  for (std::size_t c = 0; c < RATES.size(); c++)
    load[PINNED[c]] += RATES[c];
  return load;
}

std::vector<int> layer7(int servers) {
  // L7: the balancer reads each request and picks a server
  // for it, round robin here.
  std::vector<int> load(servers);
  for (int i = 0; i < TOTAL; i++)
    load[i % servers]++;
  return load;
}

void show(const std::string &label, const std::vector<int> &load) {
  std::string servers;
  for (std::size_t i = 0; i < load.size(); i++)
    servers += std::format("{}{} {}", i ? ", " : "", "ABCD"[i], load[i]);
  // The busiest server's load against a fair share, in hundredths, rounded.
  const int ratio =
      (std::ranges::max(load) * static_cast<int>(load.size()) * 100 +
       TOTAL / 2) /
      TOTAL;
  std::println("{}: {}; busiest {}.{:02}x a fair share", label, servers,
               ratio / 100, ratio % 100);
}

int main() {
  std::println(
      "Four clients, one connection each, send {:n} requests a second.", RATES);
  show("L4, 3 servers", layer4(3));
  show("L7, 3 servers", layer7(3));
  std::println("Server D joins; no client reconnects.");
  show("L4, 4 servers", layer4(4));
  show("L7, 4 servers", layer7(4));
}

In C++: std::reduce adds up the rates, and {:n} prints the range of rates without its brackets, separated by commas.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
int[] rates = [600, 100, 50, 50]; // requests a second
int[] pinned = [0, 1, 2, 0]; // the server each connection got when it opened: A, B, C, A
var total = rates.Sum();

var rateList = string.Join(", ", rates);
Console.WriteLine($"Four clients, one connection each, send {rateList} requests a second.");
Show("L4, 3 servers", Layer4(3));
Show("L7, 3 servers", Layer7(3));
Console.WriteLine("Server D joins; no client reconnects.");
Show("L4, 4 servers", Layer4(4));
Show("L7, 4 servers", Layer7(4));

int[] Layer4(int servers)
{
    // L4: every request follows its connection to the server picked when it opened.
    var load = new int[servers];
    for (var c = 0; c < rates.Length; c++) load[pinned[c]] += rates[c];
    return load;
}

int[] Layer7(int servers)
{
    // L7: the balancer reads each request and picks a server for it, round robin here.
    var load = new int[servers];
    for (var i = 0; i < total; i++) load[i % servers]++;
    return load;
}

void Show(string label, int[] load)
{
    var servers = string.Join(", ", load.Select((n, i) => $"{"ABCD"[i]} {n}"));
    // The busiest server's load against a fair share, in hundredths, rounded.
    var ratio = (load.Max() * load.Length * 100 + total / 2) / total;
    Console.WriteLine($"{label}: {servers}; busiest {ratio / 100}.{ratio % 100:D2}x a fair share");
}

In C#: {ratio % 100:D2} pads the hundredths to two digits inside the interpolated string; Layer4, Layer7 and Show are local functions after the top-level statements.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

#include <stdio.h>

// Four clients keep one long-lived HTTP/2 connection each, as gRPC
// clients do, and send all their requests on it: a mobile gateway,
// search, billing and an admin panel.
static const int RATES[] = {600, 100, 50, 50}; // requests a second
// The server each connection got when it opened: A, B, C, A.
static const int PINNED[] = {0, 1, 2, 0};
enum { CLIENTS = sizeof RATES / sizeof RATES[0] };

static int total(void) {
  int sum = 0;
  for (int c = 0; c < CLIENTS; c++)
    sum += RATES[c];
  return sum;
}

static void layer4(int load[4]) {
  // L4: every request follows its connection to the server
  // picked when it opened.
  for (int c = 0; c < CLIENTS; c++)
    load[PINNED[c]] += RATES[c];
}

static void layer7(int load[4], int servers) {
  // L7: the balancer reads each request and picks a server
  // for it, round robin here.
  for (int i = 0; i < total(); i++)
    load[i % servers]++;
}

static void show(const char *label, const int load[4], int servers) {
  int busiest = 0;
  printf("%s: ", label);
  for (int i = 0; i < servers; i++) {
    printf("%s%c %d", i ? ", " : "", "ABCD"[i], load[i]);
    if (load[i] > busiest)
      busiest = load[i];
  }
  // The busiest server's load against a fair share, in hundredths, rounded.
  const int ratio = (busiest * servers * 100 + total() / 2) / total();
  printf("; busiest %d.%02dx a fair share\n", ratio / 100, ratio % 100);
}

int main(void) {
  printf("Four clients, one connection each, send ");
  for (int c = 0; c < CLIENTS; c++)
    printf("%s%d", c ? ", " : "", RATES[c]);
  printf(" requests a second.\n");
  for (int servers = 3; servers <= 4; servers++) {
    if (servers == 4)
      printf("Server D joins; no client reconnects.\n");
    int l4[4] = {0}, l7[4] = {0};
    layer4(l4);
    layer7(l7, servers);
    show(servers == 3 ? "L4, 3 servers" : "L4, 4 servers", l4, servers);
    show(servers == 3 ? "L7, 3 servers" : "L7, 4 servers", l7, servers);
  }
  return 0;
}

In C: The loads live in fixed arrays of four, enough for the largest fleet here, and printf joins the rates with a comma before every one but the first.

Recorded with Apple clang 21.0.0 (C23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang -std=c23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.c -o main && ./main

PHP 8.5 · main.php

<?php

declare(strict_types=1);

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
const RATES = [600, 100, 50, 50]; // requests a second
const PINNED = [0, 1, 2, 0]; // the server each connection got when it opened: A, B, C, A

/** @return list<int> */
function layer4(int $servers): array
{
    // L4: every request follows its connection to the server picked when it opened.
    $load = array_fill(0, $servers, 0);
    foreach (RATES as $c => $rate) {
        $load[PINNED[$c]] += $rate;
    }
    return $load;
}

/** @return list<int> */
function layer7(int $servers): array
{
    // L7: the balancer reads each request and picks a server for it, round robin here.
    $load = array_fill(0, $servers, 0);
    for ($i = 0; $i < array_sum(RATES); $i++) {
        $load[$i % $servers]++;
    }
    return $load;
}

/** @param list<int> $load */
function show(string $label, array $load): void
{
    $servers = [];
    foreach ($load as $i => $n) {
        $servers[] = 'ABCD'[$i] . " {$n}";
    }
    $total = array_sum(RATES);
    // The busiest server's load against a fair share, in hundredths, rounded.
    $ratio = intdiv(max($load) * count($load) * 100 + intdiv($total, 2), $total);
    $share = sprintf('%d.%02d', intdiv($ratio, 100), $ratio % 100);
    echo "{$label}: " . implode(', ', $servers) . "; busiest {$share}x a fair share\n";
}

echo 'Four clients, one connection each, send ' . implode(', ', RATES) . " requests a second.\n";
show('L4, 3 servers', layer4(3));
show('L7, 3 servers', layer7(3));
echo "Server D joins; no client reconnects.\n";
show('L4, 4 servers', layer4(4));
show('L7, 4 servers', layer7(4));

In PHP: intdiv divides whole numbers, since / would give a float, and array_sum and max work straight on the lists.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
const RATES: [usize; 4] = [600, 100, 50, 50]; // requests a second
const PINNED: [usize; 4] = [0, 1, 2, 0]; // the server each connection got when it opened

fn total() -> usize {
    RATES.iter().sum()
}

fn layer4(servers: usize) -> Vec<usize> {
    // L4: every request follows its connection to the server picked when it opened.
    let mut load = vec![0; servers];
    for (rate, &server) in RATES.iter().zip(&PINNED) {
        load[server] += rate;
    }
    load
}

fn layer7(servers: usize) -> Vec<usize> {
    // L7: the balancer reads each request and picks a server for it, round robin here.
    let mut load = vec![0; servers];
    for i in 0..total() {
        load[i % servers] += 1;
    }
    load
}

fn show(label: &str, load: &[usize]) {
    let servers: Vec<String> = load
        .iter()
        .zip("ABCD".chars())
        .map(|(n, name)| format!("{name} {n}"))
        .collect();
    // The busiest server's load against a fair share, in hundredths, rounded.
    let ratio = (load.iter().max().unwrap_or(&0) * load.len() * 100 + total() / 2) / total();
    let (units, hundredths) = (ratio / 100, ratio % 100);
    println!(
        "{label}: {}; busiest {units}.{hundredths:02}x a fair share",
        servers.join(", ")
    );
}

fn main() {
    let rates: Vec<String> = RATES.iter().map(usize::to_string).collect();
    println!(
        "Four clients, one connection each, send {} requests a second.",
        rates.join(", ")
    );
    show("L4, 3 servers", &layer4(3));
    show("L7, 3 servers", &layer7(3));
    println!("Server D joins; no client reconnects.");
    show("L4, 4 servers", &layer4(4));
    show("L7, 4 servers", &layer7(4));
}

In Rust: The counts are usize because they index the load vector; zip walks the rates beside the server each connection got.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
const RATES = [600, 100, 50, 50]; // requests a second
const PINNED = [0, 1, 2, 0]; // the server each connection got when it opened: A, B, C, A
const TOTAL = RATES.reduce((sum, rate) => sum + rate, 0);

function layer4(servers: number): number[] {
  // L4: every request follows its connection to the server picked when it opened.
  const load = new Array<number>(servers).fill(0);
  RATES.forEach((rate, c) => (load[PINNED[c]] += rate));
  return load;
}

function layer7(servers: number): number[] {
  // L7: the balancer reads each request and picks a server for it, round robin here.
  const load = new Array<number>(servers).fill(0);
  for (let i = 0; i < TOTAL; i++) load[i % servers] += 1;
  return load;
}

function show(label: string, load: number[]): void {
  const servers = load.map((n, i) => `${"ABCD"[i]} ${n}`).join(", ");
  // The busiest server's load against a fair share, in hundredths, rounded.
  const ratio = Math.floor((Math.max(...load) * load.length * 100 + TOTAL / 2) / TOTAL);
  const share = `${Math.floor(ratio / 100)}.${String(ratio % 100).padStart(2, "0")}`;
  console.log(`${label}: ${servers}; busiest ${share}x a fair share`);
}

console.log(`Four clients, one connection each, send ${RATES.join(", ")} requests a second.`);
show("L4, 3 servers", layer4(3));
show("L7, 3 servers", layer7(3));
console.log("Server D joins; no client reconnects.");
show("L4, 4 servers", layer4(4));
show("L7, 4 servers", layer7(4));

In TypeScript: The functions take and return number[] arrays; everything else is the JavaScript program.

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import (
	"fmt"
	"slices"
	"strings"
)

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
var (
	rates  = []int{600, 100, 50, 50} // requests a second
	pinned = []int{0, 1, 2, 0}       // the server each connection got when it opened: A, B, C, A
)

func total() int {
	sum := 0
	for _, rate := range rates {
		sum += rate
	}
	return sum
}

func layer4(servers int) []int {
	// L4: every request follows its connection to the server picked when it opened.
	load := make([]int, servers)
	for c, rate := range rates {
		load[pinned[c]] += rate
	}
	return load
}

func layer7(servers int) []int {
	// L7: the balancer reads each request and picks a server for it, round robin here.
	load := make([]int, servers)
	for i := range total() {
		load[i%servers]++
	}
	return load
}

func show(label string, load []int) {
	servers := make([]string, len(load))
	for i, n := range load {
		servers[i] = fmt.Sprintf("%c %d", "ABCD"[i], n)
	}
	// The busiest server's load against a fair share, in hundredths, rounded.
	ratio := (slices.Max(load)*len(load)*100 + total()/2) / total()
	fmt.Printf("%s: %s; busiest %d.%02dx a fair share\n",
		label, strings.Join(servers, ", "), ratio/100, ratio%100)
}

func main() {
	parts := make([]string, len(rates))
	for i, rate := range rates {
		parts[i] = fmt.Sprint(rate)
	}
	fmt.Printf("Four clients, one connection each, send %s requests a second.\n",
		strings.Join(parts, ", "))
	show("L4, 3 servers", layer4(3))
	show("L7, 3 servers", layer7(3))
	fmt.Println("Server D joins; no client reconnects.")
	show("L4, 4 servers", layer4(4))
	show("L7, 4 servers", layer7(4))
}

In Go: slices.Max finds the busiest server, and the rates are formatted one by one, because fmt.Sprint of a slice would print its brackets.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
let rates = [600, 100, 50, 50]  // requests a second
let pinned = [0, 1, 2, 0]  // the server each connection got when it opened: A, B, C, A
let total = rates.reduce(0, +)

func layer4(_ servers: Int) -> [Int] {
  // L4: every request follows its connection to the server picked when it opened.
  var load = Array(repeating: 0, count: servers)
  for (rate, server) in zip(rates, pinned) { load[server] += rate }
  return load
}

func layer7(_ servers: Int) -> [Int] {
  // L7: the balancer reads each request and picks a server for it, round robin here.
  var load = Array(repeating: 0, count: servers)
  for i in 0..<total { load[i % servers] += 1 }
  return load
}

func show(_ label: String, _ load: [Int]) {
  let servers = zip("ABCD", load).map { "\($0) \($1)" }.joined(separator: ", ")
  // The busiest server's load against a fair share, in hundredths, rounded.
  let ratio = ((load.max() ?? 0) * load.count * 100 + total / 2) / total
  let hundredths = ratio % 100 < 10 ? "0\(ratio % 100)" : "\(ratio % 100)"
  print("\(label): \(servers); busiest \(ratio / 100).\(hundredths)x a fair share")
}

let rateList = rates.map(String.init).joined(separator: ", ")
print("Four clients, one connection each, send \(rateList) requests a second.")
show("L4, 3 servers", layer4(3))
show("L7, 3 servers", layer7(3))
print("Server D joins; no client reconnects.")
show("L4, 4 servers", layer4(4))
show("L7, 4 servers", layer7(4))

In Swift: zip pairs the letters A to D with the loads, and the two digits of the hundredths are padded by hand, since Swift without Foundation has no format strings.

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

# Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
# all their requests on it: a mobile gateway, search, billing and an admin panel.
RATES = [600, 100, 50, 50].freeze # requests a second
PINNED = [0, 1, 2, 0].freeze # the server each connection got when it opened: A, B, C, A
TOTAL = RATES.sum

# L4: every request follows its connection to the server picked when it opened.
def layer4(servers)
  load = Array.new(servers, 0)
  RATES.zip(PINNED) { |rate, server| load[server] += rate }
  load
end

# L7: the balancer reads each request and picks a server for it, round robin here.
def layer7(servers)
  load = Array.new(servers, 0)
  TOTAL.times { |i| load[i % servers] += 1 }
  load
end

def show(label, load)
  servers = load.each_with_index.map { |n, i| "#{'ABCD'[i]} #{n}" }.join(', ')
  # The busiest server's load against a fair share, in hundredths, rounded.
  ratio = ((load.max * load.size * 100) + (TOTAL / 2)) / TOTAL
  puts format('%<label>s: %<servers>s; busiest %<units>d.%<hundredths>02dx a fair share',
              label: label, servers: servers, units: ratio / 100, hundredths: ratio % 100)
end

puts "Four clients, one connection each, send #{RATES.join(', ')} requests a second."
show('L4, 3 servers', layer4(3))
show('L7, 3 servers', layer7(3))
puts 'Server D joins; no client reconnects.'
show('L4, 4 servers', layer4(4))
show('L7, 4 servers', layer7(4))

In Ruby: RuboCop asks for annotated format tokens, so format names each value it pads, such as %<hundredths>02d.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
val rates = intArrayOf(600, 100, 50, 50) // requests a second
val pinned = intArrayOf(0, 1, 2, 0) // the server each connection got when it opened: A, B, C, A
val total = rates.sum()

fun layer4(servers: Int): IntArray {
    // L4: every request follows its connection to the server picked when it opened.
    val load = IntArray(servers)
    rates.zip(pinned).forEach { (rate, server) -> load[server] += rate }
    return load
}

fun layer7(servers: Int): IntArray {
    // L7: the balancer reads each request and picks a server for it, round robin here.
    val load = IntArray(servers)
    for (i in 0 until total) load[i % servers]++
    return load
}

fun show(
    label: String,
    load: IntArray,
) {
    val servers = load.withIndex().joinToString(", ") { (i, n) -> "${"ABCD"[i]} $n" }
    // The busiest server's load against a fair share, in hundredths, rounded.
    val ratio = (load.max() * load.size * 100 + total / 2) / total
    val share = "${ratio / 100}.${(ratio % 100).toString().padStart(2, '0')}"
    println("$label: $servers; busiest ${share}x a fair share")
}

fun main() {
    val rateList = rates.joinToString(", ")
    println("Four clients, one connection each, send $rateList requests a second.")
    show("L4, 3 servers", layer4(3))
    show("L7, 3 servers", layer7(3))
    println("Server D joins; no client reconnects.")
    show("L4, 4 servers", layer4(4))
    show("L7, 4 servers", layer7(4))
}

In Kotlin: withIndex pairs every load with its server's position, and padStart pads the hundredths, since the common standard library has no String.format.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

// Four clients keep one long-lived HTTP/2 connection each, as gRPC clients do, and send
// all their requests on it: a mobile gateway, search, billing and an admin panel.
const rates = [600, 100, 50, 50]; // requests a second
// The server each connection got when it opened: A, B, C, A.
const pinned = [0, 1, 2, 0];
final total = rates.reduce((a, b) => a + b);

List<int> layer4(int servers) {
  // L4: every request follows its connection to the server picked when it opened.
  final load = List.filled(servers, 0);
  for (final (c, rate) in rates.indexed) {
    load[pinned[c]] += rate;
  }
  return load;
}

List<int> layer7(int servers) {
  // L7: the balancer reads each request and picks a server for it, round robin here.
  final load = List.filled(servers, 0);
  for (var i = 0; i < total; i++) {
    load[i % servers]++;
  }
  return load;
}

void show(String label, List<int> load) {
  final servers = [for (final (i, n) in load.indexed) '${'ABCD'[i]} $n']
      .join(', ');
  // The busiest server's load against a fair share, in hundredths, rounded.
  final ratio =
      (load.reduce((a, b) => a > b ? a : b) * load.length * 100 + total ~/ 2) ~/
      total;
  final share = '${ratio ~/ 100}.${'${ratio % 100}'.padLeft(2, '0')}';
  print('$label: $servers; busiest ${share}x a fair share');
}

void main() {
  print(
    'Four clients, one connection each, send ${rates.join(', ')} requests a second.',
  );
  show('L4, 3 servers', layer4(3));
  show('L7, 3 servers', layer7(3));
  print('Server D joins; no client reconnects.');
  show('L4, 4 servers', layer4(4));
  show('L7, 4 servers', layer7(4));
}

In Dart: ~/ is integer division, and a record pattern in the for loop takes each rate with its position.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

Four clients, one connection each, send 600, 100, 50, 50 requests a second.
L4, 3 servers: A 650, B 100, C 50; busiest 2.44x a fair share
L7, 3 servers: A 267, B 267, C 266; busiest 1.00x a fair share
Server D joins; no client reconnects.
L4, 4 servers: A 650, B 100, C 50, D 0; busiest 3.25x a fair share
L7, 4 servers: A 200, B 200, C 200, D 200; busiest 1.00x a fair share

At L4 the mobile gateway’s single connection lands on server A and takes 600 requests a second with it, so A carries 650 while C carries 50: the busiest server does 2.44 times its fair share. Adding server D changes nothing for the existing connections, so D sits idle until a client reconnects, and the imbalance grows to 3.25 times. At L7 every request is a new decision, the load is even, and the new server gets its quarter at once.

Three fixes are common. Put an HTTP/2-aware L7 proxy in front of the servers, so that it spreads individual requests. Let the clients balance requests themselves over a list of servers, which removes the extra hop but needs that logic in every client. Or make the servers close connections after a while: gRPC’s MAX_CONNECTION_AGE makes a server send GOAWAY once a connection reaches a maximum age, letting its calls finish, so that clients reconnect and an L4 balancer can spread them again (gRPC proposal A9).

Key idea

An L4 balancer’s unit is the connection, so a few long-lived connections decide the load, and a new server gets nothing until clients reconnect; balance requests, or make connections end, to spread them.

Checkpoint

Check: Connections or requests

  1. One question Behind an L4 balancer, server A holds two long-lived connections carrying 600 and 50 requests a second, out of 800 a second shared by three servers. How many times its fair share does A carry? Give two decimals.

    Type a number.

    A hint

    A fair share is the total divided by the number of servers.

    Show the answer: One question

    Answer: 2.44 times (anything from 2.43 to 2.45 counts)

    A fair share is 800 ÷ 3 ≈ 266.7 requests a second, and A carries 650, so 650 ÷ 266.7 ≈ 2.44 times, the number the program printed. An L7 balancer would have given each server 267 or 266.

A dead server leaves the pool after interval times threshold

A balancer learns that a server is broken in two ways. Active checks send it a probe on a schedule and count the answers. Passive checks watch real traffic: open-source nginx marks a server failed when requests to it fail (max_fails is 1 within fail_timeout, 10 s by default), and Envoy’s outlier detection, which it calls a form of passive health checking, ejects a host after a run of server errors (nginx upstream module, Envoy outlier detection). Both are kinds of health check: A test a load balancer runs against each server, actively with a probe on a schedule or passively by watching real traffic, to decide which servers stay in its pool..

With active checks, the time to notice a dead server is about the check interval times the number of failures it takes to leave. HAProxy checks every 2 s by default and takes a server out after 3 failures in a row, so it notices in about 6 s (HAProxy manual, inter and fall). An Application Load Balancer’s defaults are a check every 30 s and 2 failures, about a minute (ALB health checks). At 200 requests a second per server, that minute sends about 12,000 requests to a server that cannot answer them, unless passive checks or retries catch them first. Faster checks shorten that window but make servers flap in and out of the pool during a brief pause, so pick the interval from how many failed requests you can afford.

The two defaults side by side, at the same 200 requests a second per server:

Defaults Check every Failures to leave Time to notice Requests sent to a dead server
HAProxy 2 s 3 about 6 s about 1,200
Application Load Balancer 30 s 2 about 60 s about 12,000

Key idea

A dead server keeps receiving requests for about the check interval times the failure threshold, so choose both from the number of failed requests you can afford.

Checkpoint

Check: How fast a dead server leaves

  1. One question A balancer checks every server every 5 s and takes one out after 2 failed checks in a row. A server crashes just after passing a check. About how many seconds until it leaves the pool?

    Type a number.

    A hint

    Count the checks that have to fail after the crash.

    Show the answer: One question

    Answer: 10 seconds (anything from 9.5 to 10.5 counts)

    The next two checks fail at 5 s and 10 s, and the second takes the server out: interval times threshold, 5 × 2 = 10 s. Until then requests still go to it, unless passive checks or retries catch them first.

A health check should test each server’s own health

What a check tests matters more than how often it runs. Kubernetes separates two questions. A liveness probe: A Kubernetes check of whether a container can still make progress. When it fails often enough, the kubelet restarts the container. probe asks whether the process can make progress at all; when it fails often enough, the kubelet restarts the container. A readiness probe: A Kubernetes health check whose failure only stops traffic to a container, while a failing liveness probe restarts it. Checks of the back-end services a container needs belong in readiness, not liveness. More in “Redundancy, failover and static stability” probe asks whether the server should get traffic right now; when it fails, the pod’s address is removed from the endpoints of every Service that selects it, and nothing restarts. The same page warns that a careless liveness probe can cause cascading failures, restarting containers under high load (Kubernetes probes).

The dangerous check is one that calls a dependency every server shares. Step through the incident the program below runs first, under a check that queries the shared database:

Interactive · message by message A shared database slows, and a deep check empties the pool Step through the incident under a check that queries the database, then compare it with checks of each server's own health.
A shared database slows, and a deep check empties the pool, step 5 of 5. Messages so far: Balancer to Six servers: check, deep query; Six servers to Database: query times out.Balancerchecks every 2 s, 3 to leaveSix serversin the pool: 6Databaseshared by all sixcheck, deep queryquery times out27 % against 77.5 %

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Before 30 s. Every server passes its check every 2 s. The balancer spreads 1,200 requests a second over six servers, and 70 % of them never touch the database.
  2. 30 s, the database slows. The shared database slows down. The 30 % of requests that need it fail, and the check, which runs a query on the database, times out on all six servers at the same moment.
  3. 34 s, the pool is empty. The third failed check in a row arrives for every server together, so all six leave the pool. Now even the 70 % of requests that never needed the database go unanswered.
  4. 60 to 62 s, back. The database recovers at 60 s. Two passed checks in a row bring the servers back at 62 s, after 28 s with no healthy server at all.
  5. The other designs. From 30 to 70 s the deep check answered 27 % of requests. A check of each server's own health, or a deep check that fails open and sends to all servers when none passes, answered 77.5 %.

This model runs six servers behind a balancer with HAProxy’s default check timing, and compares four check designs in two incidents: the shared database slows down, or one server’s disk fills up.

Four health-check designs in two incidents JavaScript · health/health_checks.mjs
// Four health-check designs, two incidents: which requests still get an answer?
// Six servers share one database. 70 % of requests are answered from each server's own cache; 30 % need the
// database. The balancer checks every server every 2 s; 3 failed checks in a row take a server out of the pool,
// 2 passes in a row bring it back.
const SERVERS = 6;
const PER_TICK = 120; // requests per 100 ms tick: 1,200 a second
const NEEDS_DATABASE = 0.3;
const CHECK_EVERY = 20; // ticks (2 s)
const FALL = 3;
const RISE = 2;

const incidents = [
  // From t = 30 s to t = 60 s (ticks 300 to 599).
  { name: "database slow 30 s", databaseSlow: (t) => t >= 300 && t < 600, broken: () => false },
  { name: "server 3 disk full 30 s", databaseSlow: () => false, broken: (t, s) => s === 2 && t >= 300 && t < 600 },
];

// What each design's check tests. A slow database makes a check that queries it time out.
const designs = [
  { name: "process up", passes: () => true, failOpen: false },
  { name: "deep check", passes: (inc, t, s) => !inc.broken(t, s) && !inc.databaseSlow(t), failOpen: false },
  { name: "deep, fail open", passes: (inc, t, s) => !inc.broken(t, s) && !inc.databaseSlow(t), failOpen: true },
  { name: "local checks", passes: (inc, t, s) => !inc.broken(t, s), failOpen: false },
];

function run(design, inc) {
  const inPool = new Array(SERVERS).fill(true);
  const streak = new Array(SERVERS).fill(0); // consecutive results that disagree with the current state
  let answered = 0;
  let offered = 0;
  let emptyTicks = 0;
  for (let t = 0; t < 900; t++) {
    if (t % CHECK_EVERY === 0) {
      for (let s = 0; s < SERVERS; s++) {
        const ok = design.passes(inc, t, s);
        if (ok === inPool[s]) streak[s] = 0;
        else if (++streak[s] >= (inPool[s] ? FALL : RISE)) {
          inPool[s] = !inPool[s];
          streak[s] = 0;
        }
      }
    }
    let targets = [...inPool.keys()].filter((s) => inPool[s]);
    if (targets.length === 0) {
      if (t >= 300 && t < 700) emptyTicks++;
      if (design.failOpen) targets = [...inPool.keys()]; // no healthy server: send to all of them
    }
    if (t < 300 || t >= 700) continue; // count the requests from t = 30 s to t = 70 s
    offered += PER_TICK;
    for (const s of targets) {
      const share = PER_TICK / targets.length;
      const success = inc.broken(t, s) ? 0 : inc.databaseSlow(t) ? 1 - NEEDS_DATABASE : 1;
      answered += share * success;
    }
  }
  return { answered: answered / offered, emptySeconds: emptyTicks / 10 };
}

console.log("Requests answered from t = 30 s to 70 s,");
console.log("and time with no healthy server");
for (const inc of incidents) {
  console.log(`\nIncident: ${inc.name}`);
  console.log(`${"check design".padEnd(17)}${"answered".padStart(9)}${"none healthy".padStart(14)}`);
  for (const d of designs) {
    const r = run(d, inc);
    console.log(`${d.name.padEnd(17)}${`${(100 * r.answered).toFixed(1)} %`.padStart(9)}${`${r.emptySeconds} s`.padStart(14)}`);
  }
}

Output

Requests answered from t = 30 s to 70 s,
and time with no healthy server

Incident: database slow 30 s
check design      answered  none healthy
process up          77.5 %           0 s
deep check          27.0 %          28 s
deep, fail open     77.5 %          28 s
local checks        77.5 %           0 s

Incident: server 3 disk full 30 s
check design      answered  none healthy
process up          87.5 %           0 s
deep check          98.3 %           0 s
deep, fail open     98.3 %           0 s
local checks        98.3 %           0 s

Recorded with Node.js 24.21.0 on macOS 26 arm64. To run it yourself: mise exec node@24.21.0 -- node health_checks.mjs

The deep check, which runs a database query, is the best design for the broken disk and the worst for the slow database. When the database slows, every server fails the same check at the same moment, the pool is empty for 28 s, and even the 70 % of requests that never needed the database go unanswered: 27 % answered, against 77.5 % for the other designs. A check that only asks whether the process is up keeps every server in the pool, including the broken one, which then fails one request in six. A check of each server’s own health (its process, its disk, its warm cache) gets both incidents right.

Amazon’s Builders’ Library describes the same trade. Checks that fail together on many servers do more harm than good, so fast-acting balancer checks are best kept to local health, and the balancer should fail open: Keeping traffic flowing to every server when all of them fail their health checks at once, because a check that fails everywhere together is more likely wrong than the whole fleet. More in “Redundancy, failover and static stability”: when every server fails its checks, send traffic to all of them anyway (Implementing health checks). Real balancers do this. An Application Load Balancer whose targets are all unhealthy routes to all of them, and Envoy stops honouring health status once fewer than 50 % of a cluster’s hosts are healthy, its default panic threshold (Envoy panic threshold).

A Kubernetes Service does not fail open on readiness: a pod that fails its readiness probe leaves the Service’s endpoints, so if every pod fails at once, the Service has no pod to send traffic to. The probes page suggests a readiness probe may check the back-end services a pod depends on, which helps when the fault is in one pod’s own connection; for a dependency all pods share, it is the 27 % row above.

Key idea

Check what is local to each server, and let the balancer fail open: a check of a shared dependency fails everywhere at once and empties the pool when it is needed most.

Checkpoint

Check: What a health check should test

  1. One question Every server of a pool fails its health check in the same second. Why does a well-designed balancer send traffic to all of them anyway?

    Choose one answer.

    Show the answer: One question

    Answer: Checks failing everywhere at once more likely test something the servers share, and an empty pool answers nothing

    When every server fails at once, the cause is rarely in every server; it is in something they share. Taking all of them out turns a partial outage into a full one, so balancers such as an Application Load Balancer, and Envoy below its panic threshold, send traffic to all of them.

Leave the pool, drain, then stop

When a server leaves on purpose, for a deploy or a scale-in, the order of steps decides how many requests break. Take it out of the balancer’s pool first, so that no new requests arrive. Let the requests already in progress finish, up to a limit. Only then stop the process. An Application Load Balancer calls this the deregistration delay: a leaving target is draining for up to 300 s by default, finishes sooner once it has no requests in flight, and clients get a 5xx error if the target closes connections before then (target group attributes). That order is connection draining: Taking a server out of a load balancer's pool first, letting the requests it is serving finish up to a time limit, and only then stopping it, so that no request is cut off.; step through it for one server:

Interactive · message by message One server leaves during a deploy, in the safe order Step through one old server as it leaves the pool, drains and stops, and a new one takes its place.
One server leaves during a deploy, in the safe order, step 6 of 6. Messages so far: Old server to Balancer: last short answers; Balancer to New server: new requests.Balancer400 requests a secondOld serverstopped, nothing cut offNew serverin the poollast short answersnew requests

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Leave the pool first. The deploy takes the old server out of the balancer's pool. From now on it gets no new requests, and the other three take 133 a second each instead of 100.
  2. Short requests finish. Most requests in flight take 50 to 300 ms, so they finish within a fraction of a second of the server leaving the pool.
  3. An upload is still running. One request in fifty is an upload of 5 to 25 s. Draining until idle, with a limit of 30 s, waits for every upload in flight.
  4. Idle, then stop. Once it has no request in flight the server stops. Nothing was cut off.
  5. The replacement joins. The new server takes 10 s to boot, then joins the pool and gets its share of new requests.
  6. The other orders. Stopping first and letting the checks find out dropped 2,638 requests over the four servers; stopping at once after leaving the pool, 259; a 2 s drain, 144 uploads. Draining until idle lost none, and the deploy took 130 s instead of 40 s.

This model replaces four servers one at a time while 400 requests a second arrive, 2 % of them uploads that take 5 to 25 s:

Four ways to take a server out during a deploy Python · drain/drain_demo.py
"""A rolling deploy of 4 servers, replaced one at a time, with four ways of taking each old server out.

400 requests a second arrive evenly and go round robin to the servers in the balancer's pool. 98 % take 50-300 ms;
2 % are uploads of 5-25 s. A replacement joins the pool 10 s after the old server stops.
"""
import random

RATE = 400  # requests a second
START = 60.0  # the deploy starts at t = 60 s
BOOT = 10.0  # seconds before a replacement takes traffic
CHECK_EVERY, FALL = 2.0, 3  # health checks every 2 s, 3 failures to leave the pool


def durations(seed=7):
    rng = random.Random(seed)
    while True:
        if rng.random() < 0.02:
            yield 5 + 20 * rng.random()  # an upload
        else:
            yield 0.05 + 0.25 * rng.random()


def deploy(strategy):
    """Returns (dropped requests, seconds the deploy took)."""
    pool = [0, 1, 2, 3]  # servers in the balancer's pool (ids); a replacement gets a new id
    ends = {s: [] for s in pool}  # when each server's in-flight requests finish
    dead = set()  # stopped, but the balancer may still send to them
    dropped, rr, served_by = 0, 0, durations()
    plan = [("leave", START, 0)]  # (event, time, server)
    t, n, next_id = 0.0, 0, 4
    while plan:
        plan.sort(key=lambda e: e[1])
        event, at, server = plan[0]
        if t >= at:  # handle the next deploy step before routing more requests
            plan.pop(0)
            if event == "leave":
                if strategy == "stop at once, checks find out":
                    dead.add(server)
                    first_check = (at // CHECK_EVERY + 1) * CHECK_EVERY
                    plan.append(("out of pool", first_check + (FALL - 1) * CHECK_EVERY, server))
                    plan.append(("stop", at, server))
                else:
                    pool.remove(server)
                    drain = {"stop at once": 0.0, "drain 2 s, then stop": 2.0}.get(strategy)
                    if drain is None:  # drain until idle, at most 30 s
                        busy_until = max([e for e in ends[server] if e > at], default=at)
                        drain = min(busy_until - at, 30.0)
                    plan.append(("stop", at + drain, server))
            elif event == "out of pool":
                pool.remove(server)
            elif event == "stop":
                dropped += sum(1 for e in ends[server] if e > at)  # cut off mid-request
                ends[server] = []
                dead.add(server)
                plan.append(("join", at + BOOT, next_id))
                next_id += 1
            elif event == "join":
                pool.append(server)
                ends[server] = []
                if server - 4 < 3:  # replace the next old server
                    plan.append(("leave", at, server - 3))
                else:
                    return dropped, at - START
            continue
        target = pool[rr % len(pool)]
        rr += 1
        if target in dead:
            dropped += 1  # sent to a server that has already stopped
        else:
            ends[target] = [e for e in ends[target] if e > t] + [t + next(served_by)]
        n += 1
        t = n / RATE


LABELS = {
    "stop at once, checks find out": "stop; checks find out",
    "stop at once": "stop at once",
    "drain 2 s, then stop": "drain 2 s, then stop",
    "drain until idle, 30 s max": "drain until idle, 30 s",
}
print(f"{'how a server leaves':23}{'dropped':>8}{'deploy':>9}")
for strategy, label in LABELS.items():
    lost, took = deploy(strategy)
    print(f"{label:23}{lost:>8}{took:>7.0f} s")

Output

how a server leaves     dropped   deploy
stop; checks find out      2638     40 s
stop at once                259     40 s
drain 2 s, then stop        144     48 s
drain until idle, 30 s        0    130 s

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 drain_demo.py

Stopping the process first and leaving the balancer to find out from its checks is the worst order: for about 6 s per server, new requests go to a server that is gone, and with the requests cut off in flight, 2,638 fail. Stopping at once after leaving the pool still cuts off everything in flight, 259 requests, most of them long uploads. A 2 s drain saves the short requests and loses 144 uploads. Draining until the server is idle, with a 30 s limit, loses nothing, and the deploy takes 130 s instead of 40 s. So set the drain limit above the longest request you are not willing to cut off, and expect it to set the pace of your deploys. Connections that last for hours, such as WebSockets, cannot be waited for; the server has to ask its clients to reconnect elsewhere, as gRPC’s GOAWAY does.

While one server of four is out, the other three take 133 requests a second each instead of 100, a third more. Keep that headroom, or deploys become overloads.

Key idea

Leave the pool, drain for longer than the longest request you will not cut off, then stop; the drain sets the pace of the deploy, and the servers that stay need the headroom.

Checkpoint

Check: Draining before a server stops

  1. One question In which order should a server leave during a deploy so that no request in flight is cut off?

    Choose one answer.

    Show the answer: One question

    Answer: Leave the balancer's pool, wait for the requests in flight up to a limit, then stop the process

    Leave the pool, drain, then stop. In the run, draining until idle with a 30 s limit lost no request, at the price of a deploy of 130 s instead of 40 s.

A new server needs a ramp, not a full share

A server that has just started is slower than its neighbours: its caches are empty, its connection pools have not filled and a just-in-time compiler may not have compiled its hot code yet. Given a full share of traffic at once, it answers slowly or times out. slow start (load balancing): Ramping a new or returning server's share of traffic up over a set time, instead of giving it a full share at once, while its caches and connection pools warm up. ramps its share up instead. HAProxy’s slowstart grows a returning server’s weight and connection limit linearly from 0 to 100 % over the time you set, and an Application Load Balancer increases the requests it sends to a new target linearly over its slow start duration (HAProxy manual, slowstart; target group attributes). With a 60 s linear ramp, a new server gets a quarter of a full share after 15 s and half after 30 s. Envoy’s slow start can also ramp non-linearly, through an aggression setting, and never starts below 10 % of the full weight by default (Envoy slow start).

The same 60 s linear ramp for a server whose full share is 100 requests a second, as in the deploy above:

After joining Share of a full weight Requests a second
0 s 0 % 0
15 s 25 % 25
30 s 50 % 50
45 s 75 % 75
60 s 100 % 100

Slow start and least-request balancing pull in opposite directions. A new server has no requests in progress, so a policy that picks the server with the fewest sees it as the best choice. The Application Load Balancer does not allow slow start together with its least outstanding requests algorithm, so with that algorithm the warm-up has to come from somewhere else, such as warming the caches before the server joins.

Key idea

Ramp a new server’s share up while its caches and pools warm, and remember that a least-requests policy sees an idle new server as the best choice.

Checkpoint

Check: Slow start for new servers

  1. One question A new server joins with a linear slow start of 90 s. What share of a full weight, in per cent, does it get after 30 s?

    Type a number.

    Show the answer: One question

    Answer: 33.3 % (anything from 32.8 to 33.8 counts)

    A linear ramp gives a new server t ÷ duration of its full share: 30 ÷ 90 ≈ 33.3 %, and the whole share after 90 s. With 100 requests a second as a full share, that is about 33 requests a second after 30 s.

Stickiness is an optimisation you can lose

A sticky sessions: A load balancer setting that sends each user's requests back to the same server, usually because that server keeps the user's session in its memory. More in “Quality attributes and how to trade them off” sends all of one client’s requests to the same server. An L7 balancer does it with a cookie: the Application Load Balancer’s duration-based stickiness sets a cookie named AWSALB that names the chosen target (target group attributes). An L4 balancer can only use the client’s address. A Kubernetes Service with sessionAffinity: ClientIP keeps a client on one pod for 10,800 s (3 hours) by default, and nginx’s ip_hash hashes only the first three octets of an IPv4 address, so every client in the same /24 network lands on the same server (Virtual IPs and Service Proxies, nginx upstream module).

Stickiness costs three things. Load becomes uneven, because some clients are much busier than others and many users can share one address behind an office or carrier network. A failed server still loses its sessions, because stickiness decides where requests go, not where data lives. And new servers fill slowly, because existing sessions stay where they are: the Application Load Balancer’s guide warns of uneven load after a large scale-out and suggests expiring the cookies to rebalance. Step through the second cost:

Interactive · step by step A sticky cart when its server fails Step through one shopper whose cart lives in a server's memory, then the same shopper with the cart in a shared store.
A sticky cart when its server fails, step 4 of 4. Showing Shopper, L7 balancer, Server A (failed), Server B (reads the cart), Shared session store (cart: 3 items). In focus: Shared session store, Server B.ShopperL7 balancersets a sticky cookieServer AfailedServer Breads the cartShared session storecart: 3 itemsread cart

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Pinned by a cookie. The balancer picks server A for the shopper and sets a cookie that names it, so every later request goes to A. A keeps the cart in its own memory.
  2. Server A fails. Server A crashes. The cookie still names it, so the balancer has to send the shopper's next request somewhere else.
  3. The cart is gone. Server B answers, but it never held this cart. Stickiness decided where the requests went; it never kept a copy of the data.
  4. Keep the cart in a store. With the cart in a shared store, any server can read it. A moved shopper now costs at most a cache miss, which is the only kind of loss stickiness should risk.

So use stickiness only where losing it costs speed, not data. A per-user cache on the server is a fair case: a moved user gets a cache miss. A long-lived connection is sticky by nature: a WebSocket stays with the server that accepted the upgrade. A temporary bridge while you move in-memory sessions into a shared store is fine too. A cart or a login that exists only in one server’s memory is not: the Twelve-Factor App keeps processes stateless and calls sticky sessions a violation of its rules (Processes).

HTTP Header Checker Look at a site's response headers for the cookies and headers a load balancer adds.

Key idea

Stickiness decides where requests go, not where data lives, so use it only where losing it costs a cache miss or a reconnect, never the only copy of a cart or a login.

Checkpoint

Check: When stickiness is acceptable

  1. One question nginx's ip_hash pins clients by the first three octets of an IPv4 address. Where do clients at 203.0.113.5 and 203.0.113.250 go?

    Choose one answer.

    Show the answer: One question

    Answer: To the same server, because only 203.0.113 is hashed

    ip_hash hashes the first three octets, so every client in the same /24 network lands on the same server. An office or a carrier network behind one prefix puts all of its users on one server.

Choosing a balancer, one question at a time

  • The protocol is not HTTP, TLS must reach the server untouched, or packet rates are extreme: L4.
  • You need routing by path or host, per-request balancing of HTTP/2 or gRPC, or retries: L7, retrying only requests that are safe to repeat. RFC 9110 calls PUT, DELETE and the safe methods idempotent and says a client should not retry other methods automatically unless it knows they are idempotent (RFC 9110, section 9.2.2). HAProxy’s default retry-on setting retries only a request that could not be sent at all.
  • Health checks: local and cheap, with a detection time you have calculated, and a balancer that fails open.
  • Leaving and joining: drain for longer than your longest normal request, and ramp new servers up.
  • Stickiness: an optimisation you can lose, never the only copy of state.

Retrying every request that failed

A balancer that sends a timed-out POST to another server can place an order twice, because the first server may have placed it just before the timeout. Retry only a request that never reached a server, which is all HAProxy retries by default, or one whose method RFC 9110 calls idempotent; any other failure goes back to the client as an error.

Answer the four questions in the table for a system of your own; it rules out what does not fit and says why:

Interactive · answer and compare Which balancer fits your traffic? Answer four questions about your traffic. The table marks what fits, what fits with a caveat and what is ruled out, and why.
Is the traffic HTTP, HTTP/2 or gRPC?
Do you need routing by path or host, retries of failed requests, or the requests of long-lived connections spread?
Must TLS end only at the servers, so that no balancer holds a certificate?
Is the traffic so large that the L7 proxies themselves need spreading over many machines?

Answer the questions above: the table then marks what fits your case and says why the rest does not.

An L4 balancer, an L7 balancer and the two in tiers, against the four things that decide between them
Balancer Any protocol TLS kept to the server Routing each request Work per request
An L4 balancer Reads: addresses, ports and the protocol Good any TCP or UDP traffic: databases, brokers, games Good passes TLS through, so only the servers hold the keys Poor one choice per connection: one server carried 2.44x its share Good nothing to parse
An L7 balancer Reads: every HTTP request: method, path, headers Mixed HTTP/1.1, HTTP/2, gRPC and WebSockets Mixed ends TLS to read requests, and can encrypt again to the servers Good routes by path or header and spreads every request Mixed TLS, parsing and a second hop on every request
L4 in front of L7 proxies Reads: connections first, then each request Mixed the L7 tier needs HTTP; the L4 tier carries anything Mixed TLS ends at the L7 proxies Good the L7 tier routes and spreads the requests Mixed two tiers to run, each scaled on its own
How the answers decide
  • “Is the traffic HTTP, HTTP/2 or gRPC?” No, another protocol over TCP or UDP: rules out An L7 balancer and L4 in front of L7 proxies. An L7 balancer reads HTTP requests, so it has nothing to parse in another protocol; an L4 balancer spreads its connections or flows.
  • “Do you need routing by path or host, retries of failed requests, or the requests of long-lived connections spread?” Yes: rules out An L4 balancer. Routing by path, retrying a request elsewhere and spreading the requests of one connection all need the request itself, which an L4 balancer never reads.
  • “Must TLS end only at the servers, so that no balancer holds a certificate?” Yes: adds a caveat to An L7 balancer and L4 in front of L7 proxies. An L7 balancer has to end TLS to read requests. It can encrypt again towards the servers, but then it holds a certificate too.
  • “Is the traffic so large that the L7 proxies themselves need spreading over many machines?” Yes: adds a caveat to An L7 balancer. One tier of L7 proxies needs something in front to spread connections over its machines, which is the job of an L4 tier.

Checkpoint

Check: Choosing a balancer

  1. One question Sensors keep long-lived TCP connections to a fleet of brokers and speak MQTT, not HTTP. What spreads them over the brokers?

    Choose one answer.

    Show the answer: One question

    Answer: An L4 balancer that spreads the connections

    Non-HTTP traffic over TCP or UDP is an L4 balancer's job. It keeps each connection on one broker, and health checks take failed brokers out of the pool for new connections.

Practise: track health checks and fail open

Write the two decisions a balancer makes from its checks, the rise and fall of one server and the fail-open choice for the pool, and run the sample tests in your browser:

Exercise · Medium · Python

Track health checks and fail open

Write the two decisions a load balancer makes from health checks, in health.py.

track(results, rise=2, fall=3) follows one server through its health checks. The server starts "up". results lists the checks in the order they ran (True for a pass), and the function returns the server's state after each check, as a list of "up" and "down". An up server goes down after fall failed checks in a row; a down server comes back up after rise passed checks in a row. A single result the other way starts the count again.

routable(states, fail_open=True) returns the names of the servers the balancer may send requests to, sorted. states maps each server's name to "up" or "down". Servers that are up get traffic. When no server is up, a balancer that fails open sends traffic to all of them anyway, and one that does not sends it to none.

For example, track([False, False, False, True, True]) is ["up", "up", "down", "down", "up"], and routable({"a": "down", "b": "down"}) is ["a", "b"].

Starter code · health.py

def track(results, rise=2, fall=3):
    """The server's state ("up" or "down") after each health check."""
    # Replace this line with your code.
    return []


def routable(states, fail_open=True):
    """Sorted names of the servers that may get requests."""
    # Replace this line with your code.
    return []
The sample tests · test_health.py
from health import routable, track


def test_goes_down_after_fall_failures():
    """goes down only after 3 failed checks in a row"""
    assert track([True, False, False, True, False, False, False]) == ["up", "up", "up", "up", "up", "up", "down"]


def test_comes_back_after_rise_passes():
    """comes back up only after 2 passed checks in a row"""
    assert track([False, False, False, True, False, True, True]) == ["up", "up", "down", "down", "down", "down", "up"]


def test_other_thresholds():
    """uses the rise and fall it is given"""
    assert track([False, True, False, False], rise=1, fall=1) == ["down", "up", "down", "down"]
    assert track([False, False, True, True, True], rise=3, fall=2) == ["up", "down", "down", "down", "up"]
    assert track([]) == []


def test_routable_up_servers():
    """sends only to up servers, sorted by name"""
    assert routable({"c": "up", "a": "up", "b": "down"}) == ["a", "c"]
    assert routable({"c": "up", "a": "up", "b": "down"}, fail_open=False) == ["a", "c"]


def test_fail_open():
    """fails open when no server is up, unless told not to"""
    assert routable({"b": "down", "a": "down"}) == ["a", "b"]
    assert routable({"b": "down", "a": "down"}, fail_open=False) == []
A hint

Keep two values while you walk through the results: the current state and how many results in a row disagreed with it. A result that agrees with the state resets the count to 0. When the count reaches fall (for an up server) or rise (for a down one), flip the state and reset the count. For routable, filter the up servers first, then decide what to return when that list is empty.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then check yourself, one question at a time, weakest idea first:

Practice that adapts to you

Practise this lesson

16 questions about 8 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 16 Which balancer can pass TLS through to the servers untouched, so that only the servers hold the certificate?

    Choose one answer.

    Show the answer: Question 1 of 16

    Answer: An L4 balancer

    An L4 balancer reads addresses, ports and the protocol, so it can pass TLS through untouched. An L7 balancer ends the client's connection to read requests, which means ending TLS.

  2. Question 2 of 16 A multiplayer game sends its real-time state as UDP packets. What spreads players over the game servers?

    Choose one answer.

    Show the answer: Question 2 of 16

    Answer: An L4 balancer that keeps each UDP flow on one server

    UDP has no connection, but each flow (the same addresses and ports) must stay on one game server, which is what an L4 balancer's flow hash does. Moving single packets between servers would split a game in two.

  3. Question 3 of 16 When does an L4 balancer choose a server for an HTTP/2 client's traffic?

    Choose one answer.

    Show the answer: Question 3 of 16

    Answer: Once, when the client's connection opens

    An L4 balancer decides once per TCP connection or UDP flow. That works while connections are short and similar, and breaks down when a few long-lived connections carry most of the traffic.

  4. Question 4 of 16 Each client of a gRPC service keeps one HTTP/2 connection open for hours. After scaling from 4 to 8 servers behind an L4 balancer, the new servers stay idle. What fixes it?

    Choose one answer.

    Show the answer: Question 4 of 16

    Answer: Balance each request, with an HTTP/2-aware L7 proxy or client-side balancing, or make servers close old connections now and then

    An L4 balancer chooses once per connection, and these connections never end, so new servers only get clients that reconnect. Balancing per request fixes it at the source; a maximum connection age (gRPC's MAX_CONNECTION_AGE) makes clients reconnect and spreads connections over time.

  5. Question 5 of 16 Which kind of health check notices a broken server by watching the real requests sent to it?

    Choose one answer.

    Show the answer: Question 5 of 16

    Answer: A passive check, such as outlier detection

    Active checks probe each server on a schedule; passive checks watch real traffic and mark a server failed after a run of errors. Many systems use both.

  6. Question 6 of 16 Health checks run every 10 s and a server leaves the pool after 3 failed checks in a row. It crashes just after passing a check. About how many seconds pass before it leaves the pool?

    Type a number.

    Show the answer: Question 6 of 16

    Answer: 30 seconds (anything from 29 to 31 counts)

    The next three checks fail at 10 s, 20 s and 30 s, and the third takes it out: interval × threshold, 10 × 3 = 30 s. At 200 requests a second, about 6,000 requests go to the dead server in that time unless retries or passive checks catch them.

  7. Question 7 of 16 A pod's readiness probe fails. What does Kubernetes do?

    Choose one answer.

    Show the answer: Question 7 of 16

    Answer: It removes the pod's address from the endpoints of every Service that selects it, and restarts nothing

    Kubernetes separates the two questions: liveness asks whether the process can make progress at all and restarts it when not; readiness asks whether it should get traffic now and removes it from the Service's endpoints.

  8. Question 8 of 16 Every server's readiness check runs a query on the shared database. What happens when that database slows down for a minute?

    Choose one answer.

    Show the answer: Question 8 of 16

    Answer: Every server fails its check at about the same time, and the pool empties unless the balancer fails open

    A shared dependency fails the same check on every server together. In the lesson's run, that design answered 27 % of requests during the incident against 77.5 % for local checks. Check what is local to each server, and let the balancer fail open when every server looks unhealthy.

  9. Question 9 of 16 Uploads to a service take up to 25 s. How should each old server leave during a deploy?

    Choose one answer.

    Show the answer: Question 9 of 16

    Answer: Leave the balancer's pool first, let its requests finish with a drain limit above 25 s, then stop

    The drain must outlast the longest request you do not want to cut off. In the lesson's run, stopping first dropped 2,638 requests, a 2 s drain 144, and draining until idle (at most 30 s) none, at the price of a longer deploy.

  10. Question 10 of 16 Why can a deploy not simply drain a server's WebSocket connections the way it drains its HTTP requests?

    Choose one answer.

    Show the answer: Question 10 of 16

    Answer: They can last for hours, so the server has to ask clients to reconnect elsewhere instead of waiting

    Drains have limits because some work never ends on its own. For long-lived connections the server closes them on purpose, as gRPC's GOAWAY does, so clients reconnect to servers still in the pool.

  11. Question 11 of 16 With a 60 s linear slow start, what share of a full weight, in per cent, does a new server get 15 s after it joins?

    Type a number.

    Show the answer: Question 11 of 16

    Answer: 25 %

    A linear ramp of 60 s gives 15 ÷ 60 = 25 % after 15 s, half after 30 s and the full share after 60 s.

  12. Question 12 of 16 Why do slow start and a least-outstanding-requests policy pull in opposite directions?

    Choose one answer.

    Show the answer: Question 12 of 16

    Answer: A new server has no requests in progress, so the policy sees it as the best choice and floods it

    The Application Load Balancer does not allow slow start together with least outstanding requests, so with that policy the warm-up has to come from somewhere else, such as warming caches before the server joins.

  13. Question 13 of 16 When are sticky sessions a reasonable choice?

    Choose one answer.

    Show the answer: Question 13 of 16

    Answer: When losing the stickiness costs only speed, such as a cache miss or a reconnect

    Stickiness is fine as an optimisation, for warm per-user caches or long-lived connections. It is not storage: when a server fails or leaves, its sticky users move and lose whatever lived only there. Shared addresses make source-address stickiness more uneven, not less.

  14. Question 14 of 16 A service with cookie stickiness grows from 4 to 8 servers during a sale. Why do the new servers stay quiet for a while?

    Choose one answer.

    Show the answer: Question 14 of 16

    Answer: Existing sessions keep going to the servers their cookies name, so only new sessions reach the new servers

    New servers fill slowly because existing sessions stay where they are. Expiring the stickiness cookies spreads the sessions again over the larger pool.

  15. Question 15 of 16 One domain serves /api from one service and /img from an image service, and the team wants a failed GET retried on another server. Which balancer?

    Choose one answer.

    Show the answer: Question 15 of 16

    Answer: An L7 balancer with path rules, retrying only requests that are safe to repeat

    Routing by path needs the request, so it is layer 7, and so is resending a request to another server. GET is safe to repeat (RFC 9110 lists PUT, DELETE and the safe methods as idempotent); a POST is not, unless the API makes it so.

  16. Question 16 of 16 Clients reach a pool of PostgreSQL read replicas over long-lived connections that speak PostgreSQL's own protocol. What should sit in front of the replicas?

    Choose one answer.

    Show the answer: Question 16 of 16

    Answer: An L4 balancer that spreads connections, with a check that runs a cheap query on each replica itself

    The protocol is not HTTP, so an HTTP balancer has nothing to parse; an L4 balancer spreads the connections. The check asks each replica about itself (can it answer a query, is it too far behind), which is local to that replica.

Design practice: checks and deploys that hold

Two briefs follow: health checks for a service with shared dependencies, and a deploy that drops long-lived connections. Decide what you would change first in each case, and use the figures above to test the idea: the shared-database incident for the checks, and the draining server for the deploy.

Checkpoint

Your first decision

  1. Question 1 of 2 Design brief: a payments API depends on a shared database, a fraud-scoring service and a local cache. Which failure should take one server out of the pool?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Its own broken local cache or full disk, which only that server has

    Ask of each dependency whether taking this one server out helps. Local faults belong in the check; shared ones belong in the request path, with the balancer failing open if every server looks unhealthy.

  2. Question 2 of 2 Design brief: every deploy of a chat service drops its WebSocket connections, which last for hours. What is the first change?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Leave the pool first, then have the server close its connections on purpose so clients reconnect elsewhere

    Connections that last for hours cannot be drained, only handed over: the server asks its clients to reconnect, as gRPC's GOAWAY does, and they reconnect to servers still in the pool.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    Design the health checks for a payments API whose servers depend on a shared database, a fraud-scoring service and a local cache. Which failures should take a server out of the balancer's pool, and what should happen when every server fails its check at once?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    Every deploy of your chat service drops about 3 % of WebSocket connections, and newly started servers answer slowly for two minutes after they join. What is going wrong, and how should servers leave and join the load balancer?

    Model answer, Pro. First step and follow-ups

Interview questions

Warm-up (fresher to mid level): what is the difference between a layer-4 and a layer-7 load balancer, and when would you pick each? A layer-4 balancer works at the transport layer: it sees addresses, ports and the protocol, picks a server when a TCP connection or UDP flow starts, and keeps the whole connection on that server. It is fast, works for any protocol and can pass TLS through. A layer-7 balancer ends the client’s connection, reads every HTTP request and picks a server per request, so it can route by path or header, retry safe requests elsewhere and spread HTTP/2 or gRPC requests that share one connection. That costs TLS and parsing work on every request. Pick L4 for non-HTTP traffic, end-to-end TLS or very high packet rates, and L7 for websites and APIs that need routing or per-request balancing. Many systems use both: L4 in front, spreading connections over L7 proxies.

Key takeaways

  • An L4 balancer decides once per connection from addresses and ports; an L7 balancer reads and decides per request.
  • Long-lived connections defeat L4 balancing: in the run, one gateway made a server carry 2.44 times its share, and a new server stayed idle until clients reconnected.
  • Detection time is about the check interval times the failure threshold; size it from the failed requests you can afford.
  • Check what is local to each server, and let the balancer fail open: a shared-dependency check emptied the pool and answered 27 % of requests where local checks answered 77.5 %.
  • Leave the pool, drain, then stop: in the run that order took dropped requests from 2,638 to 0, for a slower deploy.
  • Ramp new servers up, and treat stickiness as an optimisation you can lose.

Terms in this lesson

connection draining
Taking a server out of a load balancer's pool first, letting the requests it is serving finish up to a time limit, and only then stopping it, so that no request is cut off.
health check
A test a load balancer runs against each server, actively with a probe on a schedule or passively by watching real traffic, to decide which servers stay in its pool.
layer-4 (L4) load balancer
A load balancer that reads only addresses, ports and the transport protocol. It picks a server when a TCP connection or UDP flow starts and sends everything on it to that server.
layer-7 (L7) load balancer
A load balancer that ends the client's connection and reads each HTTP request, so it can route by path or header, retry a request elsewhere and spread the requests of one connection.
liveness probe
A Kubernetes check of whether a container can still make progress. When it fails often enough, the kubelet restarts the container.
slow start (load balancing)
Ramping a new or returning server's share of traffic up over a set time, instead of giving it a full share at once, while its caches and connection pools warm up.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.