Skip to content

load balancing: PowerOfTwo scans every backend then picks randomly between the two lightest, which is neither power-of-two-choices nor cheaper than LeastLoaded #1411

Closed

Description

@FlorentinDUBOIS

PowerOfTwo::next_available_backend (lib/src/load_balancing.rs) does not implement the power-of-two-choices
algorithm. It implements least-loaded with a randomised choice between the two lightest backends.

Reading the code at af4005a3: the fold iterates every backend, maintaining first and second
as the two lightest with first.measure <= second.measure (enforced by its own debug_assert!), and
then:

(Some((_, b1)), Some((_, b2))) => {
    if rng().random_bool(0.5) {
        Some(b1.clone())
    } else {
        Some(b2.clone())
    }
}

The two measures are computed, compared throughout the fold, asserted to be ordered — and then
discarded at the decision point in favour of a coin flip.

Why that is not P2C

Power-of-two-choices is: sample two backends uniformly at random, then take the less loaded of the
two.
Its entire value proposition is that O(1) sampling plus a deterministic minimum gives
near-least-loaded balance without ever scanning the set.

This implementation is the mirror image — O(n) scan to find the deterministic best two, then a random
pick between them. Concretely it means:

  • It costs the same as LeastLoaded. Both walk every backend on every request. Whatever
    operational reason led someone to pick POWER_OF_TWO over LEAST_LOADED in a configuration, per-request
    cost was not it.
  • It balances slightly worse than LeastLoaded. Having already paid for the full scan and
    identified the minimum, flipping a coin to sometimes take the second-lightest instead is strictly
    less balanced than taking the minimum.

The one thing it does buy, and why that matters for the naming question

The coin flip is not pointless. Sōzu runs multiple workers, each selecting from its own view. If every
worker deterministically took the global minimum, they would herd onto the same backend — the classic
failure mode that P2C exists to avoid. Randomising between the top two does mitigate that.

So the behaviour is defensible; the name is not. Real P2C would obtain the same anti-herding property
at O(1) instead of O(n).

Which way to resolve it is a product decision

Make the name true. Sample two backends at random and take the less loaded. This is a smaller
function than the current one, is O(1) per request, and gives the anti-herding property by
construction. It changes balance characteristics under load, so it wants a measurement rather than an
assertion.

Or make the name describe the behaviour. If the current algorithm is what operators actually want
— and "least loaded, with anti-herding jitter" is a reasonable thing to want — then it should be
called that, and its O(n) cost documented so nobody chooses it over LEAST_LOADED expecting a cheaper
selection.

Either way, doc/configure.md lists POWER_OF_TWO among the selectable policies without describing
its semantics, and doc/lifetime_of_a_session.md names PowerOfTwo in a bare list. Whichever
resolution is chosen, those should say what the algorithm does.

What I verified, and what I did not

Verified by reading lib/src/load_balancing.rs at af4005a3: the fold's structure, the two
debug_assert!s pinning first <= second and the candidate-population rule, the final match arm, and
the contrast with LeastLoaded's min_by_key shape in the same file.

Not verified: whether this shape was a deliberate choice recorded somewhere I did not find, or
whether the _key: Option<u64> parameter being ignored here is related. I did not benchmark either
algorithm, so the cost claim is complexity-based reasoning from the code, not a measurement.

How this surfaced

While injecting a seeded RNG into the two remaining ambient-entropy sites in this file, as part of the
sans-io conversion. That changeset deliberately does not change this behaviour — it makes the coin
flip reproducible and leaves the algorithm alone.

Activity

  1. FlorentinDUBOIS commented on Sep 22, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Resolved by #1437, squash-merged into main.

    POWER_OF_TWO now implements the real algorithm: two indices drawn uniformly at random without replacement, exactly those two backends measured, the lighter returned. The old fold scanned every backend and — as the changeset's red proof showed — evicted the unique minimum entirely, returning it 0 times in 100 000 draws rather than the ~50% the earlier analysis assumed.

    Renaming the variant was rejected on evidence rather than preference: LoadBalancingAlgorithms derives #[serde(rename_all = "SCREAMING_SNAKE_CASE")] and FileClusterConfig carries deny_unknown_fields, so a rename would refuse every existing configuration file at startup, and UpgradeData is serialised with serde_json, so it would also break hot upgrade across the version boundary. Saved state is unaffected either way — it stores the integer.

    Marked BREAKING in the changelog: traffic distribution changes for any cluster configured with this policy, and no setting reproduces the old distribution.

    Two things found along the way: the old fold tripped its own debug_assert! on loads [0, 1, 5], coin-flipping the heaviest backend into the result in release builds; and the O(1) claim was corrected everywhere, because BackendList::available_backends clones every healthy backend into a fresh Vec before any policy runs — so all six policies are O(n) per request and P2C removes the load reads, not the scan. The CLI help defect found while sweeping is tracked separately as #1429.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions