Reverse Proxy Load Balancing: Queues, Health Checks, and a Reproducible Scheduler
Reverse Proxy Load Balancing: Queues, Health Checks, and a Reproducible Scheduler
Search
Ask the AI

Reverse Proxy Load Balancing: Queues, Health Checks, and a Reproducible Scheduler

A reverse proxy can terminate TLS, route requests and balance load. Equal request counts do not imply equal work: service times, connection reuse and backend capacity affect queues and tails. Separate the ideal queue model, Nginx smooth weighted round robin and consistent hashing, with evidence for each.

1. The Queuing Theory of Load Balancing

A shared FCFS queue with Poisson arrivals, independent exponential service and \(c\) homogeneous servers can be modeled as \(M/M/c\). Round Robin does not split Poisson arrivals into independent \(M/M/1\) queues: each backend receives every cth arrival, with different interarrival and dependency structure. Independent random splitting gives the corresponding Poisson-thinning model.

In \(M/M/1\), exponential service links the mean and variance \(\sigma^2\). To vary general service-time variance at a fixed mean, use an M/G/1 model with its arrival assumptions and the Pollaczek-Khinchine formula. A long job can delay later jobs in one serial queue, but one job alone does not establish saturation.

Least-Connections selects by active connection counts; it is not the same as a pooled queue dispatching to the first free server. Keep-alive, HTTP/2 multiplexing and task cost affect that count. In the ideal \(M/M/c\) model, define λ as total arrival rate, μ as per-server service rate and ρ=λ/(cμ)<1. The delay probability \(P(W > 0)\) is then Erlang C:

$$ C(c, \lambda/\mu) = \frac{\frac{(c \rho)^c}{c!} \frac{1}{1-\rho}}{\sum_{k=0}^{c-1} \frac{(c \rho)^k}{k!} + \frac{(c \rho)^c}{c!} \frac{1}{1-\rho}} $$

Pooling can improve utilization and waiting in particular homogeneous models; it does not prove dynamic routing strictly superior for every workload. The original diagram below is a pooled-queue illustration. Its O(1) dispatch and idle-worker pull are not properties of every least_conn implementation.


graph TD
    Proxy[Reverse Proxy / eBPF XDP]
    
    subgraph M/M/c Dynamic Queueing (Least Connections)
        Queue((Global Virtual Queue))
        B1[Backend Node 1]
        B2[Backend Node 2]
        B3[Backend Node 3]
        
        Proxy ==>|O(1) Dispatch| Queue
        Queue -->|Idle Worker Pull| B1
        Queue -->|Idle Worker Pull| B2
        Queue -->|Idle Worker Pull| B3
    end
    
    style Queue fill:#e6f3ff,stroke:#0066cc

2. Source Code Analysis: Nginx Smooth Weighted Round Robin (SWRR)

With 3:1 weights, smooth weighted round robin spreads choices rather than requiring a fixed A, A, A, B batch. The Nginx core is ngx_http_upstream_round_robin.c; ngx_http_upstream_module.c is the path mixed into the original prose. The retained shorthand omits full filters: max_fails=0 disables failure-based exclusion, while its max_fails<=fails test incorrectly skips that peer; fail_timeout, tried flags and connection limits are also missing.


// Simplified Nginx SWRR core logic
// ngx_http_upstream_round_robin.c
ngx_http_upstream_rr_peer_t *peer, *best = NULL;
ngx_uint_t total = 0;

for (peer = peers->peer; peer; peer = peer->next) {
    if (peer->down || peer->max_fails <= peer->fails) {
        continue;
    }
    
    peer->current_weight += peer->effective_weight;
    total += peer->effective_weight;
    
    if (best == NULL || peer->current_weight > best->current_weight) {
        best = peer;
    }
}

if (best == NULL) { return NULL; }

best->current_weight -= total;
return best;

The algorithm accumulates effective_weight and subtracts total from the selected peer. The original A, B, A, A is one phase arrangement; with 3:1 weights, zero initial values and A winning ties, the first four choices are A,A,B,A. Smoothing cannot eliminate every transient queue. This arithmetic example checks those exact conditions:

# Healthy peers, fixed weights, zero initial current_weight, A wins ties.
weights = [3, 1]
current = [0, 0]
order = []
for _ in range(4):
    current = [x + w for x, w in zip(current, weights)]
    chosen = max(range(2), key=lambda i: current[i])
    current[chosen] -= sum(weights)
    order.append("AB"[chosen])
assert order == ["A", "A", "B", "A"]

Failure, recovery and concurrent state changes can alter the sequence.

3. Consistent Hashing and Virtual Node Mathematical Distribution

Key-based routing can improve cache reuse. Changing n in \(H(k) \pmod n\) remaps many keys, but the fraction depends on node counts and mapping rules rather than always approaching \(100\%\). Ring hashing can use a space such as \([0, 2^{32}-1]\); membership changes usually affect part of the ring. Request load also depends on key popularity.

In an ideal random ring, placing \(V\) virtual positions for each of \(N\) nodes gives \(N \times V\) positions and reduces relative variation in owned intervals. MurmurHash3 is one possible hash, not a universal Ketama/Maglev default, and avalanche behavior alone does not prove balanced application work.

For N>1, V independent uniform positions per node, and uniform keys/requests, the coefficient of variation follows below. Absolute standard deviation \(\sigma_{load}\) also includes the mean share 1/N:

$$ CV_{load} = \frac{\sigma_{load}}{\mathbb{E}[load]} = \sqrt{\frac{N-1}{NV+1}} $$

For large N with NV much greater than 1, the expression is approximately 1/√V. For V from \(100\) to \(256\), that approximation is about 10% to 6.25%, not a \(1\%\) guarantee. Use the exact formula for finite N. Hot keys can still create hotspots. Envoy v1.36.0 Maglev constructs a lookup table rather than this virtual-node ring; its documented example table size is 65537. Check ring-hash and Maglev parameters separately.

4. eBPF: Preemptive Health Checks at the Kernel Level

Probe interval, timeout and failure threshold determine detection time. Three 5-second timeouts are one configuration, not a fixed L7 lower bound. TCP metrics supply transport clues; readiness probes can check application dependencies. Use the evidence for the failure being investigated.

A version-dependent tcp_drop probe or listen-backlog metric describes the measured host/path; remote state needs remote collection. The condition \(Q_d \ge Q_{max}\) can drive a custom policy, but map updates, health propagation and draining all take time. It does not guarantee microsecond eviction before the first 502; “0-RTT” is not a protocol guarantee for this operation.

5. VRRP split-brain and arbitration

VRRP split-brain: The original 10G, 50ms BGP and 50% packet-loss narrative names Arista, but has no matching topology, timer settings or logs. VRRP failover depends on advertisement timing, priority and tracking; 50ms alone does not establish the cause. Duplicate VIPs cause MAC flapping only under relevant MAC configurations. BFD/BGP and VIP arbitration address different layers. A Raft lock alone does not fence an unreachable old master; lease-loss behavior and fencing need an explicit design.

6. Load Balancing Health Evidence Matrix

Queues, health checks, connection reuse, retry policy, and upstream cold starts all affect reverse-proxy behavior. The matrix below lists observable evidence for distinguishing routing policy, health probes, and upstream application failures.

Symptom Evidence to collect Likely cause Validation action
One upstream is overloaded for a long time Upstream request count, active connections, response time, and weights. Wrong weights, connection reuse skew, or uneven hash distribution. Compare round robin, least_conn, and consistent-hash distributions.
Health checks pass but users see 502 Probe path, real business path, error log, and timeout values. The probe only checks a port and misses dependencies. Make health checks cover critical dependencies or split readiness levels.
Retries trigger a cascade Retry count, idempotency, failure ratio, and upstream queue length. Unsafe requests are retried or synchronized retries amplify load. Add budgets, jitter, circuit breaking, and retries only for safe requests.
Tail latency rises after deploy Cold-start time, connection-pool state, warmup traffic, and p95/p99. New instances receive full traffic before they are warm. Use gradual rollout, slow-start weights, and connection-pool prewarming.

FAQ

Should a proxy retry every 5xx response?

Choose retries from request semantics and the failure stage. Non-idempotent POST needs a clear guarantee such as deduplication/idempotency keys or knowledge that the request was not applied. Bound GET attempts and total deadlines too. With at most \(R\) total attempts per original request, attempt load can reach R times the original rate; that is not increased successful throughput. Set backoff, jitter and retry budgets for the workload.

References

Leave a Reply

Scroll down