Course contents

03. Scaling and Load Balancing Lesson 6 of 8

Least Connections

Balance by work in progress: why least connections beats round robin on uneven requests, slow start for newcomers, long-lived connections and two choices.

15 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Least connections sends each request to the server with the fewest requests (or connections) in flight.
  • Heavy requests and slow servers raise in-flight counts, so new work flows elsewhere without any configuration.
  • It removes queueing behind heavy requests, but a heavy request still takes as long as it takes.
  • An empty newcomer looks ideal and gets flooded; slow start ramps its share up.
  • Counts of long-lived connections say little about load; with many balancers, power of two choices avoids herding.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Least connections is a load balancing algorithm that sends each new request or connection to the backend with the fewest currently in progress. At layer 4 it counts open TCP connections; at layer 7 the same idea counts outstanding HTTP requests and is often called least outstanding requests or least request.

Why it exists

Round robin and its weighted variant balance counts, using no information about what the servers are doing. When requests differ in cost, or a server slows down without failing, equal counts produce unequal load. The number of requests in flight is a cheap, live signal of load that a balancer already has: it increments when it forwards a request and decrements when the response comes back. Routing on it adapts automatically.

How it works

The counter. For each backend the balancer keeps an active count. On forward: +1. On response, error or timeout: −1. A new request goes to the backend with the minimum count; ties are broken by list order, randomly or by round robin depending on the implementation.

Why it adapts. By Little's law, requests in flight ≈ arrival rate × time in system. A server that is slow (degraded hardware, a noisy neighbour) or busy with heavy requests holds each request longer, so its count is higher and it is picked less. That is the "join the shortest queue" policy from queueing theory, which minimises waiting when the queue lengths are known.

What it cannot fix. Balancing removes waiting, not work. If one request needs two seconds of CPU, it takes two seconds on any server. Tail latency driven by heavy requests themselves stays; tail latency driven by quick requests queueing behind heavy ones goes away.

Weighted least connections. Plain least connections equalises in-flight counts regardless of capacity, so a server with twice the cores should be allowed twice the count. Weighted variants divide the count by a weight before comparing.

Power of two choices. Instead of finding the global minimum, pick two backends at random and send the request to the one with fewer in flight. This needs information about only two servers, works well when many balancers each see only their own traffic, and avoids every balancer choosing the same idle server. Its worst-case imbalance is exponentially smaller than pure random selection, which is why Envoy's least-request algorithm and many service meshes use it.

When to use it

  • Request-level balancing at layer 7 for APIs whose request costs vary.
  • Fleets where individual servers can slow down (shared hosts, garbage collection, background jobs).
  • Mixed instance sizes, using the weighted variant.
  • As a general default when you do not want to maintain weights.

When not to

  • Long-lived connections with uneven activity (WebSockets, gRPC streams, database proxies): the count no longer reflects load.
  • When you need key affinity for caches or sessions; use consistent hashing.
  • Very many independent balancers with no shared view; prefer power of two choices.
  • Extremely uniform, short requests on identical servers, where round robin is just as good and simpler.

Trade-offs

Choice You gain You pay
Least connections over round robin Adapts to slow servers and uneven requests, no weights Per-backend counters; newcomers flooded without slow start
Power of two choices over global least connections Works with local, partial information; no herding Slightly less even than a perfect global minimum
Weighted least connections Handles mixed instance sizes Weights to maintain again
Counting requests (L7) over connections (L4) Accurate with multiplexed and keep-alive connections Must terminate and parse the protocol

Alternatives

  • Round robin / weighted round robin: simpler and predictable; fine for uniform work.
  • Random: stateless, good with many balancers, but blind to load.
  • Latency-based (peak EWMA): weights backends by recently observed response time, catching slowness even before it shows up as in-flight requests.
  • Server-reported load: backends publish a load score (CPU, queue depth) that the balancer uses, as in some service meshes and gRPC's weighted round robin with backend metrics.
  • Consistent hashing: when key locality matters more than perfect balance.

Failure modes

  • Newcomer flood: a restarted or newly scaled-out server has zero in flight and receives almost every request until its count catches up. With cold caches it may slow down or crash again. Use slow start (ramp the share over 30–120 seconds).
  • Fast failure looks attractive: a broken server that answers every request instantly with an error has the lowest count and attracts more traffic. Combine with outlier detection on error rate.
  • Misleading counts: idle long-lived connections inflate a server's count; multiplexed HTTP/2 connections hide many requests behind one.
  • Herding: many balancers with stale or local counts all send to the same apparently idle server at once.
  • Unequal capacity: plain least connections gives a large and a small server the same in-flight count, overloading the small one.

In production

HAProxy (leastconn), nginx (least_conn), Envoy (LEAST_REQUEST, power of two choices by default) and cloud layer-7 balancers all provide it. Enable slow start where available, set outlier detection to eject backends with high error rates, and prefer counting requests over connections for HTTP/2 and gRPC. For long-lived connections, cap connections per backend and rebalance by closing a fraction gracefully during deploys or when imbalance grows. Monitor per-backend in-flight counts and latency together; a backend with low count and high error rate is the classic "fast failure" trap.

Common misconceptions

  • "Least connections measures CPU." It counts requests or connections in flight; slowness shows up only indirectly.
  • "It fixes tail latency." It fixes queueing behind slow work, not slow work itself.
  • "The newest server is the best choice." It has the fewest connections, not the warmest caches.
  • "More information is always better, so global least connections beats two choices." With many balancers, stale global information causes herding; two random samples with fresh local data often do better.

Interview angle

When an interviewer asks "which algorithm?", least connections (or least outstanding requests) is a strong default for request-level balancing, but justify it: uneven request costs and servers that slow down. Then show depth: slow start for new instances, outlier detection for fast-failing ones, why WebSockets need a different signal, and power of two choices when many balancers or clients do the picking.

Model assumptions

The simulation is a simplified model, not a benchmark. Three servers have 6 workers each, an 80 ms mean service time and room for 12 waiting requests; "variable request sizes" uses a lognormal service time with cv 2.5 instead of 0.35, at the same mean. The balancer counts requests in flight (least outstanding requests) and breaks ties by list order. A degraded server takes four times as long and still passes health checks (every 500 ms; 3 successes restore a server). The simulator has no power-of-two-choices or slow-start mode; the lesson compares least connections with random and describes the others. Arrivals are random (Poisson); network hops take a fixed 5–25 ms. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. The balancer counts work in progress

    For every server, a least-connections balancer keeps one number: how many requests it has sent there that have not been answered yet. A new request goes to the server with the lowest number; ties go to the first in the list.

    The counter goes up when a request is forwarded and down when its response passes back. At 180 requests per second the three counters stay within a request or two of each other.

    Scene: The load balancer tracks requests in flight to each of three servers and sends each new request to the server with the fewest. The counts stay close together and nothing fails.

    Key idea: Least connections routes by requests in flight, a live signal of how busy each server is.

  2. 2. Round robin and uneven requests

    Now request sizes vary: most are quick, a few take many times the 80 ms average, with the same average overall. To see why that matters we switch the balancer to round robin for a moment.

    Round robin keeps dealing requests to a server that is stuck on several heavy ones. Quick requests queue behind them, P95 climbs and some requests are rejected, while another server has idle workers.

    Scene: Request sizes vary widely and the balancer uses round robin. Some servers build queues while others have idle workers; latency is high and some requests are rejected.

    Key idea: Counting turns ignores how long each request holds a server.

  3. 3. Back to least connections

    Switch back to least connections. A server busy with heavy requests has more in flight, so new requests go elsewhere until it catches up. Queues stay short, the rejections stop, and median and P95 latency drop below round robin’s.

    What it cannot change is the heavy request itself: a request that needs a second of work still takes a second, so P99 stays high. Balancing removes waiting, not work.

    Scene: With least connections and the same variable requests, queues stay short, nothing is rejected and median and P95 latency are lower than with round robin.

    Key idea: Least connections removes queueing behind heavy requests; it cannot make heavy requests cheap.

  4. 4. A slow server gets less, automatically

    Traffic eases to 140 requests per second. One second in, App 2 becomes four times slower: a noisy neighbour on its host. It still answers health checks, so nothing removes it.

    Its requests take longer, so its in-flight count rises and the balancer picks it less often. No weights were changed and nobody was paged; traffic shifted to App 1 and App 3 on its own.

    Scene: App 2 slows down but stays in rotation. The balancer sends it noticeably fewer requests than App 1 and App 3, and error rate stays low.

    Key idea: Slowness shows up as more work in progress, so least connections adapts without configuration.

  5. 5. The newcomer gets flooded

    App 2 is fixed. App 3 restarts after a deploy and rejoins once it passes three health checks. At that moment it has zero requests in flight while the others have several.

    Least connections therefore sends it almost every new request until its count catches up. Here that burst is harmless, but a real server that just started has cold caches and an unwarmed runtime; flooding it can make it slow or crash it again. Balancers offer slow start: ramp a new server’s share up over a minute or so.

    Scene: App 3 restarts and is put back after three good health checks. Right after that, most new requests go to App 3 until its in-flight count matches the others.

    Key idea: An empty server looks like the best choice to least connections; use slow start for new or restarted servers.

  6. 6. When a connection is not a unit of work

    Our model counts requests, which is what layer-7 balancers call least outstanding requests. A layer-4 balancer counts TCP connections instead, and those can mislead. A server holding 5,000 idle WebSockets looks busiest while doing nothing; a server with 50 connections each streaming video may be saturated. HTTP/2 and gRPC multiplex many requests over one long connection, so the connection count barely moves at all.

    For long-lived connections, balance by a better signal (active streams, CPU, a reported load score) or rebalance periodically by closing connections gracefully.

    Scene: Three healthy servers behind the least-connections balancer. An annotation notes that the balancer counts requests in flight, not TCP connections.

    Key idea: Least connections is only as good as the thing it counts.

  7. 7. Random, and the power of two choices

    Least connections needs an up-to-date count of every server. With many balancers, each sees only its own traffic and they can all pile onto the same idle server. Picking at random needs no state at all. Traffic is back at 180 requests per second; switch to random and latency rises and rejections return: random has no idea who is busy.

    The common compromise is power of two choices: pick two servers at random and send the request to the one with fewer in flight. That small step removes most of random’s imbalance and avoids the herd effect, which is why Envoy and others use it as their least-request algorithm. (This simulator has no two-choices mode; it sits between the two you see here.)

    Scene: At 180 requests per second the balancer picks servers at random. With variable request sizes, latency is higher than with least connections and some requests are rejected.

    Key idea: Comparing just two random servers gets most of the benefit of comparing all of them.

  8. 8. Choosing a load-aware algorithm

    Least connections (least outstanding requests) is a strong default for request-level balancing: it adapts to slow servers and uneven requests with no tuning. Pair it with slow start for new servers and outlier detection for sick ones.

    Check what it counts. For long-lived connections use a better load signal, and with many independent balancers prefer power of two choices.

    Scene: Three healthy servers with variable request sizes behind a least-connections balancer.

    Key idea: Balance by work in progress, measured honestly, and protect newcomers.