TExcelTAD
Home › Randomized Algorithms & Probabilistic Analysis › The Power of Two Choices

The Power of Two Choices

Put each ball into the less loaded of two random bins, instead of one random bin. That tiny change reduces the maximum load of nn balls in nn bins from Θ(ln⁡n/ln⁡ln⁡n)\Theta(\ln n / \ln\ln n) (Balls into Bins: The Maximum Load) to ln⁡ln⁡n/ln⁡2+O(1)\ln\ln n / \ln 2 + O(1): an exponential improvement for the price of one extra probe. A third choice only improves the constant. The result is due to Azar, Broder, Karlin and Upfal (1994; journal version 1999), and it underlies load balancers, distributed hash tables and cuckoo hashing. This lesson states the theorem, explains the layered-induction idea behind it, and measures the effect.

The process and the theorem

text
D-CHOICE(n, m, d)                  // m balls, n bins, d >= 1 choices per ball
0  load[0 .. n-1] = 0
1  for ball = 0 to m - 1
2      choose bins b_1 .. b_d independently and uniformly
3      put the ball in a b_j with the smallest load (ties: any rule)
4  return max(load)

Theorem (Azar, Broder, Karlin and Upfal, 1999). For m=nm = n and any fixed d≥2d \ge 2, the maximum load of D-CHOICE is

ln⁡ln⁡nln⁡d+Θ(1)with high probability.\frac{\ln \ln n}{\ln d} + \Theta(1) \quad \text{with high probability.}

For d=1d = 1 it is (1+o(1))ln⁡nln⁡ln⁡n(1 + o(1))\frac{\ln n}{\ln\ln n}. Going from one choice to two changes the order of growth; going from two to dd divides the leading term by log⁡2d\log_2 d.

Why: layered induction (sketch)

Let βi\beta_i be the number of bins with load at least ii at the end. A ball lands at height i+1i + 1 or more only if all dd of its choices already have load at least ii, which (as long as at most βi\beta_i bins are that high) has probability at most (βi/n)d(\beta_i / n)^d. So the number of bins reaching height i+1i + 1 is at most a binomial with mean n(βi/n)dn(\beta_i/n)^d, and with a Chernoff bound, roughly,

βi+1n≲(βin)d.\frac{\beta_{i+1}}{n} \lesssim \left(\frac{\beta_i}{n}\right)^{d} .

Starting from β4≤n/4\beta_4 \le n/4 (at most n/4n/4 bins can hold 4 or more of nn balls), the fractions fall doubly exponentially: β4+j/n≲4−dj\beta_{4+j}/n \lesssim 4^{-d^j}. They drop below 1/n1/n once dj≈log⁡4nd^j \approx \log_4 n, that is after j≈ln⁡ln⁡n/ln⁡dj \approx \ln\ln n / \ln d more levels. Making this rigorous requires conditioning on the high-probability events level by level and a separate argument for the last O(1)O(1) levels, where Chernoff bounds are too weak; see Mitzenmacher and Upfal, chapter "Balanced allocations". With one choice, by contrast, βi+1/n≈βi/(n i)\beta_{i+1}/n \approx \beta_i / (n\,i) for the Poisson tail, which decays only like 1/i!1/i!.

The program measures the fraction of bins with load at least ii for one and two choices and compares the two-choice fractions with the square of the previous level.

python · try it yourself
import random

rng = random.Random(120)
n = 30000
one, two = [0] * n, [0] * n
for _ in range(n):
    a, b = rng.randrange(n), rng.randrange(n)
    one[a] += 1
    two[a if two[a] <= two[b] else b] += 1

def tail(load, i):
    return sum(x >= i for x in load) / n

print(" i   one choice: Pr[load >= i]   two choices: Pr[load >= i]   (previous two-choice level)^2")
prev = None
for i in range(1, 7):
    t1, t2 = tail(one, i), tail(two, i)
    sq = f"{prev ** 2:.2e}" if prev is not None else "-"
    print(f"{i:2}   {t1:26.2e}   {t2:27.2e}   {sq:>29}")
    prev = t2
print("max load: one choice", max(one), " two choices", max(two))
 i   one choice: Pr[load >= i]   two choices: Pr[load >= i]   (previous two-choice level)^2
 1                     6.29e-01                      7.58e-01                               -
 2                     2.67e-01                      2.32e-01                        5.75e-01
 3                     8.10e-02                      9.53e-03                        5.40e-02
 4                     1.88e-02                      3.33e-05                        9.09e-05
 5                     3.43e-03                      0.00e+00                        1.11e-09
 6                     5.33e-04                      0.00e+00                        0.00e+00
max load: one choice 7  two choices 4

With one choice the fractions shrink by a factor that grows only slowly with ii. With two choices each level stays below the square of the one before, and the fractions collapse: the doubly exponential decay that the layered induction predicts. (The square is only the leading behaviour of an upper bound; the fluid limit of the process, studied by Mitzenmacher, gives the precise fractions.)

Watching both strategies

The lab runs both processes on the same random stream: the two-choice side uses the one-choice side's bin as its first candidate. With 60 bins and 300 balls, run 1 ends with a fullest bin of 16 for one choice and 6 for two choices; runs 2 to 5 give 11, 9, 11, 12 against 7 each time. The one-choice maximum varies a lot from run to run; the two-choice maximum barely moves, and the average load is 5.

One random bin per ball300 balls, 0 bins emptymax 1660 binsLess loaded of two random bins300 balls, 0 bins emptymax 660 bins

That last observation is a theorem too: for m≫nm \gg n balls, the two-choice maximum is mn+ln⁡ln⁡nln⁡2+O(1)\frac{m}{n} + \frac{\ln\ln n}{\ln 2} + O(1) with high probability, so the gap above the average does not grow with mm (Berenbrink, Czumaj, Steger and Vöcking, 2000), while for one choice it grows like (m/n)ln⁡n\sqrt{(m/n)\ln n}.

More choices, and a twist

The program compares d=1,2,3d = 1, 2, 3 for growing nn (averages over a few seeded runs; the C++ version below goes to a million bins and d=4d = 4).

python · try it yourself
import random
from math import log

def max_load(n, d, rng):
    load = [0] * n
    for _ in range(n):
        best = rng.randrange(n)
        for _ in range(d - 1):
            c = rng.randrange(n)
            if load[c] < load[best]:
                best = c
        load[best] += 1
    return max(load)

rng = random.Random(121)
print("     n    d=1    d=2    d=3   ln ln n / ln 2")
for n, runs in [(100, 20), (1000, 6), (10000, 2), (30000, 1)]:
    row = [sum(max_load(n, d, rng) for _ in range(runs)) / runs for d in (1, 2, 3)]
    print(f"{n:6}  " + "  ".join(f"{x:5.2f}" for x in row) + f"   {log(log(n)) / log(2):14.2f}")
     n    d=1    d=2    d=3   ln ln n / ln 2
   100   4.20   2.60   2.00             2.20
  1000   5.50   3.00   2.33             2.79
 10000   6.00   3.50   3.00             3.20
 30000   7.00   3.00   3.00             3.37

The jump from d=1d = 1 to d=2d = 2 is large; further choices help much less. Vöcking (2003) found a surprising twist: split the bins into dd groups, take one choice from each group, and break ties towards the leftmost group ("always go left"). The maximum load drops to ln⁡ln⁡ndln⁡ϕd+O(1)\frac{\ln\ln n}{d \ln \phi_d} + O(1), where ϕd\phi_d is the growth rate of the dd-th order Fibonacci numbers (ϕ2≈1.618\phi_2 \approx 1.618, the golden ratio). Asymmetric tie-breaking beats any symmetric rule, even with the same number of probes.

In C++

The dd-choice process in C++ for one million balls and bins, with a fixed-seed std::mt19937; the stream differs from Python's, so individual maxima can differ by one.

cpp · try it yourself
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <random>
#include <vector>

int max_load(int n, int d, std::mt19937& rng) {
    std::vector<int> load(n, 0);
    for (int ball = 0; ball < n; ++ball) {
        int best = rng() % n;
        for (int j = 1; j < d; ++j) {
            int c = rng() % n;
            if (load[c] < load[best]) best = c;
        }
        ++load[best];
    }
    return *std::max_element(load.begin(), load.end());
}

int main() {
    std::mt19937 rng(121);
    for (int n : {10000, 1000000}) {
        std::printf("n = %7d:", n);
        for (int d = 1; d <= 4; ++d) std::printf("  d=%d max %2d", d, max_load(n, d, rng));
        std::printf("   ln ln n / ln 2 = %.2f\n", std::log(std::log(n)) / std::log(2.0));
    }
}
n =   10000:  d=1 max  6  d=2 max  3  d=3 max  3  d=4 max  2   ln ln n / ln 2 = 3.20
n = 1000000:  d=1 max  9  d=2 max  4  d=3 max  3  d=4 max  3   ln ln n / ln 2 = 3.79

In practice

  • Load balancing. Sending each request to the less busy of two random servers needs only two load queries and avoids the herd behaviour of "send to the least loaded server overall", where stale load information makes every client pick the same server. Mitzenmacher's analysis of the supermarket model (1996) showed that in a queueing system two choices reduce the expected waiting time exponentially. Load balancers such as NGINX and HAProxy offer a "random with two choices" policy.
  • Hashing. Two-choice hashing keeps chains of length O(log⁡log⁡n)O(\log\log n). Cuckoo hashing goes further: each key has two possible slots and may move later, which makes the maximum load 1 (Advanced & Succinct Data Structures).

Test yourself

What is the maximum load when nn balls go into nn bins, each to the less loaded of two random bins?

  1. Θ(ln⁡n/ln⁡ln⁡n)\Theta(\ln n / \ln\ln n)
  2. ln⁡ln⁡n/ln⁡2+O(1)\ln\ln n / \ln 2 + O(1)
  3. O(1)O(1)
  4. Θ(n)\Theta(\sqrt{n})

In the layered-induction argument for dd choices, how does the fraction of bins with load at least i+1i+1 relate to the fraction with load at least ii?

  1. It is about half of it
  2. It is at most about its dd-th power
  3. It is equal
  4. It is about 1/i1/i of it

How much does a third choice improve on two, for large nn?

  1. Exponentially
  2. The leading term goes from ln⁡ln⁡n/ln⁡2\ln\ln n/\ln 2 to ln⁡ln⁡n/ln⁡3\ln\ln n/\ln 3, a constant factor
  3. Not at all
  4. It makes the load constant

With m≫nm \gg n balls and two choices, how does the gap between the maximum and the average load behave?

  1. It grows like m\sqrt{m}
  2. It stays ln⁡ln⁡n/ln⁡2+O(1)\ln\ln n/\ln 2 + O(1), independent of mm
  3. It grows like ln⁡m\ln m
  4. It shrinks to 0