Repository navigation
fix(load-balancing): implement real power-of-two-choices for POWER_OF_TWO - #1437
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 22, 2026 09:05
FlorentinDUBOIS
force-pushed
the
fix/load-balancing-power-of-two
branch
from
September 22, 2026 11:06
c975fa7 to
be093ca
Compare
…_TWO `PowerOfTwo::next_available_backend` walked every backend keeping the two lightest, then coin-flipped between them. That is neither the algorithm the name promises nor cheaper than `LeastLoaded`: it paid the same O(n) load reads per request and then discarded the ordering it had just computed. It now draws two DISTINCT backends uniformly at random and keeps the less loaded of the two, reading two backend loads whatever the cluster size. An exact tie is still broken by the seeded coin flip introduced in #1412: ties are the common case (every backend starts at zero load) and awarding them by index would herd every worker onto the same backend, which is the effect P2C exists to prevent. That is a claim about load READS, not an O(1)-per-request claim. Every selection, under every policy, first builds the candidate set in `BackendList::available_backends` (lib/src/backends.rs), which walks the cluster's backend list and clones each healthy backend into a fresh Vec; `next_available_backend_with_key` calls it before any policy is consulted. All six policies are therefore O(n) per request and none of them removes that walk. What P2C removes is the load reads layered on top of it: 2 instead of n. That is measurable work under `LoadMetric::ConnectionTime`, where every read is a `PeakEWMA::observe` call taking an `Instant::now()` stamp, and small under `Connections`/`Requests`. doc/configure.md, bin/config.toml, doc/lifetime_of_a_session.md and doc/architecture.md say so now, and they no longer advise picking P2C to shorten a per-request scan that lives in the caller: the reason to prefer it over LEAST_LOADED is balance without a global minimum, not cost. What the old code did was also worse than "near least loaded", measured by restoring the fold under the new tests. Over 5000 selections across four equally loaded backends it sent backends 0 and 1 exactly zero requests and split the rest between the last two it walked; on two backends carrying 7 and 1 connections it returned the 7-connection backend on the very first call; and with one uniquely light backend among 100 it returned that backend 0 times out of 100_000, an estimated sample size of 0.00 rather than the N/2 a reading of the fold that assumed it retained the minimum would predict. No configuration reproduces that distribution, and nothing should want to. Renaming the variant to describe the old behaviour was the other candidate resolution and was rejected on evidence, not preference. `LoadBalancingAlgorithms` derives serde with `rename_all = "SCREAMING_SNAKE_CASE"`, and two live surfaces carry the value as the STRING `"POWER_OF_TWO"`: the TOML cluster config (`FileClusterConfig::load_balancing`, command/src/config.rs) and the hot-upgrade payload (`UpgradeData::config`, serialized with serde_json in bin/src/upgrade.rs). A rename would therefore refuse every existing config file at startup and break a hot upgrade across the version boundary. Fixing the algorithm breaks no external surface at all: the variant keeps its name and its protobuf tag 3, and the saved state file already encodes `Cluster.load_balancing` as that integer, never as the name (command/tests/state_compat_v1_1_1.rs). The rewrite also removes a latent bug in the old fold. Its trailing `else` branch fired both when the new measure was lighter than `first` AND when it was heavier than `second`, evicting both candidates in the second case. On backend loads [0, 1, 5] that left the pair inverted, tripping the function's own `first <= second` debug_assert (a debug-build panic) and, in a release build, coin-flipping the HEAVIEST backend into the result half the time. The two-read bound is measured rather than asserted structurally, because a test that only checks "a backend came back" passes for the O(n) fold too: `power_of_two_touches_exactly_two_backends` counts the per-backend `PeakEWMA::observe` timestamps one selection leaves behind (64 backends in, exactly 2 measured; the old fold measured all 64), and `power_of_two_sample_size_is_two_not_the_whole_set` recovers the same sample size from the selection distribution alone. The tie-break needed its own test: the sampled pair is uniform, so the two sample positions are exchangeable and the marginal distribution cannot see which member of a tie won — substituting `true` for the coin flip leaves `power_of_two_tie_break_distribution_does_not_collapse` green. `power_of_two_tie_break_is_decided_by_the_coin_flip_not_by_sample_position` pins it directly, by freezing the peak-EWMA decay so two equally loaded backends tie exactly while `PeakEWMA::observe` still stamps `last_event`, which makes the order the two samples were measured in readable from outside. Under that substitution it reports 0 of 2000 ties resolved in favour of the second-measured sample. doc/configure.md, bin/config.toml and doc/lifetime_of_a_session.md also say which policies read `load_balancing_parameters.weight`, because the first draft of that paragraph claimed RANDOM was the only one and three of the six policies were never checked. Verified at source: RANDOM reads it inline (lib/src/load_balancing.rs:311), `Rendezvous::score` scales its rendezvous score by `backend_weight` (:632) and `Maglev::rebuild` hands out lookup-table slots in proportion to it (:813); the RoundRobin (:180-216), LeastLoaded (:352-396) and PowerOfTwo (:517-581) impls read no weight at all. HRW and Maglev both fall back to RoundRobin when called with no affinity key (:659-662, :940-942), so their weight is live only on the UDP datapath, which is the one caller that passes `Some(key)` (lib/src/udp.rs:1347). The captured-sequence test's recapture note now scopes itself to both kinds of legitimate change -- a `rand` upgrade and a deliberate change to the selection procedure -- and states the rule that distinguishes a legitimate recapture from papering over a regression: recapture only when that literal is the only failing assertion and every semantic `power_of_two_*` test is green with its body untouched. A prose-to-prose citation is checked by no rule in .github/scripts/check_doc_citations.py, which resolves source targets only, so this changeset silently rotted `doc/configure_admin_ops.md:230` by moving its target 46 lines down doc/configure.md. The citation is re-pointed and the script's header now names the blind spot, the three citations it covers, and why a fourth rule is not worth writing for three. BREAKING CHANGE: traffic distribution changes for every cluster configured with POWER_OF_TWO. No configuration key, CLI value, protobuf tag, saved state file or hot-upgrade payload changes, and no setting restores the old distribution. Refs #1411 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
fix/load-balancing-power-of-two
branch
from
September 22, 2026 12:23
be093ca to
6a37cb1
Compare
This was referenced Sep 22, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PowerOfTwo::next_available_backendwalked every backend keeping the twolightest, then coin-flipped between them. That is neither the algorithm the
name promises nor cheaper than
LeastLoaded: it paid the same O(n) loadreads per request and then discarded the ordering it had just computed.
It now draws two DISTINCT backends uniformly at random and keeps the less
loaded of the two, reading two backend loads whatever the cluster size. An
exact tie is still broken by the seeded coin flip introduced in #1412: ties
are the common case (every backend starts at zero load) and awarding them by
index would herd every worker onto the same backend, which is the effect P2C
exists to prevent.
That is a claim about load READS, not an O(1)-per-request claim. Every
selection, under every policy, first builds the candidate set in
BackendList::available_backends(lib/src/backends.rs), which walks thecluster's backend list and clones each healthy backend into a fresh Vec;
next_available_backend_with_keycalls it before any policy is consulted.All six policies are therefore O(n) per request and none of them removes
that walk. What P2C removes is the load reads layered on top of it: 2
instead of n. That is measurable work under
LoadMetric::ConnectionTime,where every read is a
PeakEWMA::observecall taking anInstant::now()stamp, and small under
Connections/Requests. doc/configure.md,bin/config.toml, doc/lifetime_of_a_session.md and doc/architecture.md say so
now, and they no longer advise picking P2C to shorten a per-request scan
that lives in the caller: the reason to prefer it over LEAST_LOADED is
balance without a global minimum, not cost.
What the old code did was also worse than "near least loaded", measured by
restoring the fold under the new tests. Over 5000 selections across four
equally loaded backends it sent backends 0 and 1 exactly zero requests and
split the rest between the last two it walked; on two backends carrying 7
and 1 connections it returned the 7-connection backend on the very first
call; and with one uniquely light backend among 100 it returned that backend
0 times out of 100_000, an estimated sample size of 0.00 rather than the N/2
a reading of the fold that assumed it retained the minimum would predict. No
configuration reproduces that distribution, and nothing should want to.
Renaming the variant to describe the old behaviour was the other candidate
resolution and was rejected on evidence, not preference.
LoadBalancingAlgorithmsderives serde with
rename_all = "SCREAMING_SNAKE_CASE", and two livesurfaces carry the value as the STRING
"POWER_OF_TWO": the TOML clusterconfig (
FileClusterConfig::load_balancing, command/src/config.rs) and thehot-upgrade payload (
UpgradeData::config, serialized with serde_json inbin/src/upgrade.rs). A rename would therefore refuse every existing config
file at startup and break a hot upgrade across the version boundary. Fixing
the algorithm breaks no external surface at all: the variant keeps its name
and its protobuf tag 3, and the saved state file already encodes
Cluster.load_balancingas that integer, never as the name(command/tests/state_compat_v1_1_1.rs).
The rewrite also removes a latent bug in the old fold. Its trailing
elsebranch fired both when the new measure was lighter than
firstAND when itwas heavier than
second, evicting both candidates in the second case. Onbackend loads [0, 1, 5] that left the pair inverted, tripping the function's
own
first <= seconddebug_assert (a debug-build panic) and, in a releasebuild, coin-flipping the HEAVIEST backend into the result half the time.
The two-read bound is measured rather than asserted structurally, because a
test that only checks "a backend came back" passes for the O(n) fold too:
power_of_two_touches_exactly_two_backendscounts the per-backendPeakEWMA::observetimestamps one selection leaves behind (64 backends in,exactly 2 measured; the old fold measured all 64), and
power_of_two_sample_size_is_two_not_the_whole_setrecovers the same samplesize from the selection distribution alone. The tie-break needed its own
test: the sampled pair is uniform, so the two sample positions are
exchangeable and the marginal distribution cannot see which member of a tie
won — substituting
truefor the coin flip leavespower_of_two_tie_break_distribution_does_not_collapsegreen.power_of_two_tie_break_is_decided_by_the_coin_flip_not_by_sample_positionpins it directly, by freezing the peak-EWMA decay so two equally loaded
backends tie exactly while
PeakEWMA::observestill stampslast_event,which makes the order the two samples were measured in readable from
outside. Under that substitution it reports 0 of 2000 ties resolved in
favour of the second-measured sample.
doc/configure.md, bin/config.toml and doc/lifetime_of_a_session.md also say
which policies read
load_balancing_parameters.weight, because the firstdraft of that paragraph claimed RANDOM was the only one and three of the six
policies were never checked. Verified at source: RANDOM reads it inline
(lib/src/load_balancing.rs:311),
Rendezvous::scorescales its rendezvousscore by
backend_weight(:632) andMaglev::rebuildhands out lookup-tableslots in proportion to it (:813); the RoundRobin (:180-216), LeastLoaded
(:352-396) and PowerOfTwo (:517-581) impls read no weight at all. HRW and
Maglev both fall back to RoundRobin when called with no affinity key
(:659-662, :940-942), so their weight is live only on the UDP datapath, which
is the one caller that passes
Some(key)(lib/src/udp.rs:1347).The captured-sequence test's recapture note now scopes itself to both kinds
of legitimate change -- a
randupgrade and a deliberate change to theselection procedure -- and states the rule that distinguishes a legitimate
recapture from papering over a regression: recapture only when that literal
is the only failing assertion and every semantic
power_of_two_*test isgreen with its body untouched.
A prose-to-prose citation is checked by no rule in
.github/scripts/check_doc_citations.py, which resolves source targets only,
so this changeset silently rotted
doc/configure_admin_ops.md:230by movingits target 46 lines down doc/configure.md. The citation is re-pointed and the
script's header now names the blind spot, the three citations it covers, and
why a fourth rule is not worth writing for three.
BREAKING CHANGE: traffic distribution changes for every cluster configured
with POWER_OF_TWO. No configuration key, CLI value, protobuf tag, saved
state file or hot-upgrade payload changes, and no setting restores the old
distribution.
Refs #1411
Signed-off-by: Florentin Dubois [email protected]