Load Balancing Algorithms: Workloads and Benchmarks
Compare round robin, least-connections, and two-choice routing under mixed request durations with a reproducible workload and operational trade-offs.
Compare round robin, least-connections, and two-choice routing under mixed request durations with a reproducible workload and operational trade-offs.
Load Balancing Algorithms: Workloads and Benchmarks
An algorithm name is not a performance guarantee. I start by checking what the proxy counts: requests, open connections, or queued work. Equal request counts work when backend capacities and request costs are similar. Long connections or a skewed queue can make that same rule perform poorly.
This guide compares three common policies and includes a small simulation. The benchmark uses the same synthetic request stream for each policy; it is a starting point for experiments, not a prediction of production performance.
What changes the result
Backend health determines which hosts the proxy considers eligible. A delayed health check can leave a failing host in rotation. Equal weights can also overload a smaller instance, so measure outcomes per backend.
Round robin counts assignments, not work. Least-connections responds to open connections, which helps when connection duration tracks backend work. That signal has limits: one HTTP/2 connection can carry many requests, and a short request can use more CPU than a long idle connection.
Queue depth matters too. A server with few active connections may still have a long queue or a slow dependency. Some proxies count queued requests, enforce connection limits, or reject work at a circuit-breaker threshold. Check what the proxy includes in its load signal.
The routing layer changes what the algorithm can see. A Layer 4 proxy usually picks a backend per connection or flow; an HTTP proxy can make a request-level choice. Retries, connection reuse, session affinity, and health ejection all affect the measured workload. Compare policies at the same layer and with the settings you plan to deploy.
Three routing policies
| Policy | Signal used for a choice | Useful when | Watch for |
|---|---|---|---|
| Round robin | Position in a rotating sequence, often adjusted by weight | Backends have similar capacity and request costs | It does not react to current queues or long requests |
| Least connections | Number of active connections | Connection duration roughly tracks backend work | Connection count can misrepresent multiplexed requests or queued work |
| Power of two choices | Load observed on two randomly selected eligible backends | A cheap load signal is available and single-choice imbalance matters | Results depend on the sampled signal, its freshness, and tie handling |
“Least connections” and “least requests” are not interchangeable labels. For example, Envoy documents a least-request policy that compares active requests; HAProxy documents how backend connection limits can leave connections pending in a queue. Read the selected proxy’s definition and confirm which work its metric includes before comparing policies. See the Envoy load-balancing documentation and the HAProxy 3.2 configuration manual.
The power-of-two rule samples two backends and sends a request to the one with the smaller observed load. Research on the “supermarket model” analyzes this choice under a specific queueing model; production proxies have different health, capacity, and request-cost signals. The paper is useful for understanding why two samples can help, but it does not establish that the policy wins for every workload. See Mitzenmacher’s randomized load-balancing analysis.
Keep routing separate from retries and circuit breakers
A load-balancing policy selects an eligible backend for an attempt. A retry decides whether to make another attempt after a timeout or error; repeating a non-idempotent operation can duplicate its effect. A circuit breaker limits work sent to an overloaded or failing upstream and may reject requests before they reach a backend. A service mesh can implement some of these controls in a proxy, but they remain different decisions with different failure behavior. Envoy documents circuit-breaker limits separately from its load-balancing policies in its circuit-breaking guide.
When testing a routing policy, hold retry budgets and circuit-breaker limits constant. Otherwise a lower response-time percentile may come from dropping more requests or spending more attempts, rather than routing work more effectively.
Run a small simulation
This Python 3 simulation uses the same deterministic request stream for each policy:
- 10,000 arrivals in a Poisson process averaging 400 requests per second.
- Four identical backends, each with four worker slots.
- 90% of requests take 8 ms; the remaining 10% take 220 ms.
- No backend failures, network delay, retries, or session affinity.
- Each request occupies one backend connection while active or queued.
It prints queue wait and total response-time percentiles plus the largest number of outstanding requests assigned to any one backend. These measurements describe only this simplified model. Save the code as benchmark.py and run python3 benchmark.py:
from heapq import heappop, heappush
from math import ceil
from random import Random
BACKENDS = 4
WORKERS_PER_BACKEND = 4
REQUESTS = 10_000
ARRIVAL_RATE_PER_SECOND = 400.0
SEED = 17
def make_workload():
rng = Random(SEED)
now = 0.0
requests = []
for _ in range(REQUESTS):
now += rng.expovariate(ARRIVAL_RATE_PER_SECOND)
service_time = 0.008 if rng.random() < 0.90 else 0.220
requests.append((now, service_time))
return requests
def percentile(values, fraction):
ordered = sorted(values)
return ordered[ceil(fraction * len(ordered)) - 1]
def simulate(policy, requests):
workers = [[0.0] * WORKERS_PER_BACKEND for _ in range(BACKENDS)]
outstanding = [[] for _ in range(BACKENDS)]
chooser = Random(SEED + 1)
response_times = []
queue_waits = []
max_outstanding = 0
next_backend = 0
for arrival, service_time in requests:
for completions in outstanding:
while completions and completions[0] <= arrival:
heappop(completions)
counts = [len(completions) for completions in outstanding]
if policy == "round robin":
backend = next_backend
next_backend = (next_backend + 1) % BACKENDS
elif policy == "least connections":
least = min(counts)
tied = [index for index, count in enumerate(counts) if count == least]
backend = chooser.choice(tied)
else: # power of two choices
first, second = chooser.sample(range(BACKENDS), 2)
if counts[first] < counts[second]:
backend = first
elif counts[second] < counts[first]:
backend = second
else:
backend = chooser.choice((first, second))
worker_available = heappop(workers[backend])
start = max(arrival, worker_available)
finish = start + service_time
heappush(workers[backend], finish)
heappush(outstanding[backend], finish)
queue_waits.append(start - arrival)
response_times.append(finish - arrival)
max_outstanding = max(max_outstanding, len(outstanding[backend]))
return queue_waits, response_times, max_outstanding
requests = make_workload()
for name in ("round robin", "least connections", "power of two choices"):
waits, responses, peak = simulate(name, requests)
print(
f"{name:20} "
f"queue p95={percentile(waits, 0.95) * 1000:.2f} ms, "
f"response p50={percentile(responses, 0.50) * 1000:.2f} ms, "
f"p95={percentile(responses, 0.95) * 1000:.2f} ms, "
f"max outstanding/backend={peak}"
)
The simulation gives each request one connection and counts both active and queued requests as outstanding. Real proxies differ: some count connections, some count requests, and protocols such as HTTP/2 multiplex many requests over one connection. The worker-slot model also treats all requests as independent jobs; it does not model CPU contention, shared databases, network latency, health-check lag, or retries.
Try changing one condition at a time: use a uniform request duration, reduce a backend’s worker capacity, or increase the arrival rate. The results should prompt a closer measurement, not settle the design choice. For a production comparison, replay representative request traces in a staging environment and record per-backend queue depth, connection or request counts, error rate, and response percentiles.
Choosing a policy
Start with the simplest policy that matches the traffic and the proxy. Round robin is often adequate for equivalent backends and similar work. Least-connections can help when connection duration tracks resource use. A two-choice policy can use a small sample of current load without scanning every backend. If request costs vary sharply, collect a metric closer to actual work, then verify the metric is fresh and comparable across hosts.
The load-balancing decision guide summarizes which questions to ask before choosing. For stable key placement, see consistent hashing for load balancing. The companion load balancing fundamentals post covers Layer 4 and Layer 7 routing responsibilities.
Conclusion
Algorithm names do not tell you what a proxy measures or what it does when a backend fails. Declare the workload, use the same health and retry settings, then compare queueing and response-time distributions. A benchmark can narrow the options; production-like measurements decide whether the change helps.
Category
Related Posts
Load Balancing Algorithms: A Decision Guide
Choose a load-balancing policy by backend health, capacity, request duration, queueing, and proxy behavior, with links to focused algorithm deep dives.
Consistent Hashing for Load Balancing
Learn how consistent-hash rings, virtual nodes, and bounded-load policies reduce reassignment, and when sticky sessions still make sense.
Cache Stampede Prevention
Compare cache-stampede controls by the duplicate work they prevent and the failure modes they add, from local single-flight to distributed leases.