Skip to content

feat(lb): shuffle-shard clients over the HRW ranking of their affinity key - #1712

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
feat/shuffle-sharding
Sep 30, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
feat/shuffle-sharding

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #524 (PR 2 of 2: shuffle sharding over the HRW ranking; PR 1 was #1706).

What

A cluster can serve each client from a shard of its backends instead of all of them. A client that overloads or poisons its backends then takes down only the clients whose shard lies inside its own.

References:

  • Colm MacCárthaigh, Workload isolation using shuffle sharding, Amazon Builders' Library, 2019. It gives C(N, k) shards against N / k partitions: 28 against 4 for eight backends in shards of two.
  • The shard is the top of the rendezvous ranking: Thaler & Ravishankar, Using name-based mappings to increase hit rates, IEEE/ACM ToN 1998, doi:10.1109/90.663936.

Decisions implemented (maintainer comment on #524)

  • Key: the affinity key from feat(lb): pass a client affinity key to Maglev and HRW on HTTP and TCP #1706. That is the source IP (post PROXY protocol), or the affinity_header / affinity_cookie value, falling back to the IP when absent.
  • Shard: k = max(2, ceil(shard_percent × N / 100)), capped at N. It is the top k of the weighted HRW ranking (hrw_score, now public) over the cluster's configured primary backends.
    • Backends that are down stay members, so a shard can be exhausted.
    • It is deterministic across workers and restarts.
    • A change of N moves a client only at the tail of its ranking.
  • Activation: only when N >= shard_min_backends, which defaults to 8. Off until shard_percent is set.
  • Exhausted shard:
    • FALLBACK (default) spills over to the rest of the cluster, backup tier and fail-open included, and counts backend.shard.spillover.
    • STRICT selects nothing (HTTP 503, TCP close) and counts backend.shard.exhausted.
    • In the fail-open regime a strict shard fails open inside itself only.
  • Priority: a sticky cookie naming a live backend wins, even outside the shard. Connection reuse keeps priority.
  • Upgrade note: explicit in CHANGELOG.md and doc/configure.md.
    • Nothing changes until shard_percent is set.
    • Once set, the cluster derives a key under every policy.
    • Every client behind one NAT, or behind an L4 balancer without PROXY, shares one shard.

Design

  • BackendList::select_with_key (lib/src/backends.rs) narrows the primary candidates to the shard before the cluster's load_balancing policy runs. Any policy therefore picks inside the shard (LEAST_LOADED balances within it, HRW pins to its top member with in-shard failover), and retries stay in it.
  • next_available_backend_with_key keeps its signature. BackendMap::select_backend (HTTP reserve and TCP connect) and the UDP keyed path read the ShardOutcome and count it under the cluster id.
  • Zero allocation: two scratch buffers (shard_scores, shard) are reserved in add_backend beside candidates. select_nth_unstable_by partitions the ranking in O(N), and retain keeps the candidates in list order for Candidates::new.
  • Key derivation widened: cluster_reads_affinity_key (router.rs, shared by the TCP proxy) is true for HRW/MAGLEV or shard_percent. Without this, a sharded ROUND_ROBIN cluster would silently not shard.
  • Config:
    • Cluster proto fields shard_percent = 20, shard_min_backends = 21, shard_mode = 22 (new enum ShardMode { FALLBACK, STRICT }).
    • TOML keys; --shard-percent / --shard-min-backends / --shard-strict on sozu cluster add; a shuffle_sharding column in the cluster table; the fields in Debug.
    • validate_shuffle_sharding runs at config load and on every AddCluster: percent in 1..=100, min ≥ 2, and the knobs are refused without shard_percent.
    • Hot-updatable through BackendMap::set_shuffle_sharding_for_cluster from server.rs::add_cluster.
  • Retry budget interaction (documented): CONN_RETRIES = 3.
    • With k = 2, a request whose two members refuse spills over, or is refused, on its third attempt.
    • With k ≥ 3, that request exhausts its attempts inside the shard (503), and the next one, finding the members in back-off, spills over or is refused at once.
  • UDP: sharding lives in the backend list, so a sharded UDP cluster shards its flows by their flow key.

Protocol/security impact: selection narrowing only; no parser, framing or TLS change. STRICT can answer 503 while other backends are healthy, by design.

Red → green

Each fix was reverted, the test run, the fix restored, and the test run again.

Mutation Fails Evidence
compute_shard never shards e2e in-shard, e2e strict, a_sharded_selection_stays_in_the_shard, an_exhausted_shard_refuses_in_strict_and_spills_in_fallback shard ["pong0", "pong2"], reached ["pong0", "pong1", "pong2", "pong3", …], strict answered Some((200, "pong2"))
STRICT spills over e2e strict, unit strict shard [2, 3] down, strict answered Some((200, "pong0")), key 0: strict never leaves the shard
FALLBACK refuses e2e fallback shard [0, 3] down, fallback answered Some((503, …))
no key for a sharded non-HRW cluster only_hrw_maglev_and_sharded_clusters_derive_a_key a sharded cluster derives a key whatever its policy
shard collected into a fresh Vec a_sharded_selection_allocates_nothing 256 sharded selections made 256 allocations

Green: every test above passes after restoring.

Tests added

  • Unit (lib/src/backends.rs):
    • a_shard_is_the_top_of_the_hrw_ranking
    • a_shard_changes_only_at_its_tail_when_backends_change: add with k fixed, add with k growing, remove a non-member, remove a member
    • a_sharded_selection_stays_in_the_shard (ROUND_ROBIN, LEAST_LOADED, RANDOM, HRW)
    • an_exhausted_shard_refuses_in_strict_and_spills_in_fallback
    • a_strict_shard_fails_open_inside_itself
    • a_sticky_backend_outside_the_shard_wins
    • a_sharded_selection_allocates_nothing
  • Unit (load_balancing.rs): a_shard_size_follows_the_decided_formula.
  • Unit (router.rs): only_hrw_maglev_and_sharded_clusters_derive_a_key.
  • Command crate: shuffle_sharding_reaches_the_add_cluster_order_and_is_validated, add_cluster_with_invalid_shuffle_sharding_rejected.
  • e2e (e2e/src/tests/shuffle_sharding_tests.rs): four backends, shard_percent = 50, shard_min_backends = 4, with the shard predicted via hrw_score. The shard's members are left without a listener, so connections to them are refused.
    • in-shard: every request lands in the predicted shard
    • FALLBACK: 200 from a non-member
    • STRICT: 503

Validation (head 2cda4f0 on main 2e55942)

  • cargo +nightly fmt --all -- --check: 0.
  • cargo clippy --all-features --all-targets --locked -- -D warnings: 0.
  • cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings: 0.
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked: 0.
  • cargo test -p sozu-lib: 1420 passed. -p sozu-command-lib: 217. -p sozu: 123. RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim: ok.
  • cargo test -p sozu-e2e -- shuffle_sharding_tests affinity_key_tests cluster_ip_limit: 15/15. The full e2e suite (before the rebase onto fix(state): apply a listener patch all-or-nothing on main and workers #1708): 532 passed, 0 failed.
  • cd fuzz && cargo +nightly fuzz build: 0.
  • check_doc_citations.py: --self-test, --root ., --root . --base origin/main, --audit --root . all 0.

Docs

  • doc/configure.md:
    • a new "Shuffle sharding" section: literature, formula, stability, keys, TOML example, composition with policy, retries, sticky, reuse and backups, UDP, and the enable-time note
    • metrics rows
    • a "Client affinity" cross-reference
  • doc/metrics.md, doc/configure_cli.md, doc/architecture.md, lib/src/protocol/mux/LIFECYCLE.md, doc/testing.md, bin/config.toml, CHANGELOG.md (Added, with the before-enabling note).
  • The line citations of cluster_h2_command in doc/configure_admin_ops.md became prose, because they drift with every edit of request_builder.rs.

Review fixes (FIX-FIRST on a029ac6)

  • M1: STRICT now decides between refusing and failing open on the primary tier only. The cluster_can_open that also counted backups is replaced by primaries_can_open, so a healthy backup no longer turns a strict shard's fail-open into a 503. Test: a_healthy_backup_does_not_turn_a_strict_fail_open_into_a_refusal. Red with backups counted: panicked … a strict shard fails open inside itself. doc/configure.md "Backups are outside every shard" now states the STRICT/backup interaction explicitly.
  • M2: the upgrade note in CHANGELOG.md and in the doc/configure.md "Before enabling it" note now says:
    • Upgrade the main process and every worker before setting shard_*: an older worker ignores fields 20–22 and serves unsharded.
    • An older CLI's QueryClusterById → AddCluster read-modify-write (cluster h2) drops the fields and silently disables sharding.
  • L2: a FALLBACK fail-open pick that lands back in the shard is reported InShard (settle_spill_outcome) and not counted as backend.shard.spillover. Test: a_fallback_fail_open_pick_inside_the_shard_is_not_a_spill_over. Red without the settle: 127.0.0.1:20004 is a shard member, left: SpilledOver right: InShard.
  • L3: tests added.
    • a_strict_shard_failing_health_checks_refuses_while_others_are_healthy. Red with the primaries_can_open guard forced false: key 0: strict must refuse, not fail open.
    • Non-uniform weights in a_shard_is_the_top_of_the_hrw_ranking, which also asserts that the weights move some shard.
    • e2e test_re_adding_a_cluster_without_shard_percent_turns_sharding_off, re-added under HRW so the key is still derived. Red when Server::add_cluster skips set_shuffle_sharding_for_cluster without shard_percent: sharded Some((503, …)), then unsharded Some((503, …)).
    • The backup-tier interaction is covered by M1's test.
  • L4: compute_shard counts the primaries and checks shard_size / min_backends before hashing, so a cluster below the threshold pays no hash. The has_tier_candidate walk is gone, including for unsharded clusters.
  • L5:
    • The weight wording now reads "ranks higher for more keys, not proportional once k > 1".
    • The UDP DefaultHasher cross-toolchain caveat is on "across restarts".
    • The backend.shard.* rows are aligned between configure.md and metrics.md.
    • The --affinity-header / --affinity-cookie help mentions that sharding reads the key under any policy.
  • L1 (done): the worker mirrors validate_shuffle_sharding on AddCluster next to the health-check mirror in server.rs.

…y key

A cluster can now serve each client from a shard of its backends instead
of all of them, so a client that overloads or poisons its backends takes
down only the clients whose shard lies inside its own (Colm
MacCarthaigh, "Workload isolation using shuffle sharding", Amazon
Builders' Library, 2019): C(N, k) shards against N / k partitions (#524).

A client's shard is the top k = max(2, ceil(shard_percent * N / 100)),
capped at N, of the rendezvous (HRW; Thaler and Ravishankar, IEEE/ACM
ToN 1998) ranking of its affinity key from #1706 over the cluster's
configured primary backends. The ranking uses the weighted HRW score
(hrw_score, now public), so a shard is the same on every worker and
across restarts, and a change of N moves a client only at the tail of
its ranking. Members that go down stay members, so a shard can be
exhausted.

BackendList::select_with_key narrows the primary candidates to the
shard before the cluster's policy runs, so any policy picks inside it
and retries stay in it. The two buffers it needs are reserved by
add_backend beside `candidates`, and select_nth_unstable_by partitions
the ranking in O(N): a sharded selection allocates nothing. An exhausted
shard spills over to the unsharded tiers in FALLBACK (the default,
backend.shard.spillover) or selects nothing in STRICT
(backend.shard.exhausted: HTTP 503, TCP close); in the fail-open regime a
strict shard fails open inside itself only. Backups are outside every
shard. STRICT decides between refusing and failing open on the primary tier
only: backups sit outside every shard, so a healthy backup does not turn
a strict shard's fail-open into a refusal. A FALLBACK fail-open pick that
lands back inside the shard counts as in-shard, not as a spill-over.
Sharding sizes the shard before hashing, so a cluster below
shard_min_backends pays no hash. A sticky cookie naming a live backend
still wins, and connection reuse still wins. BackendMap counts the
outcome under the cluster id.

A sharded cluster derives the client key under every policy
(cluster_reads_affinity_key, shared by the mux router and the TCP
proxy), not only HRW and MAGLEV.

Config: Cluster proto fields shard_percent (1..=100, off when unset),
shard_min_backends (default 8, at least 2) and shard_mode (ShardMode
FALLBACK | STRICT), TOML keys, --shard-percent / --shard-min-backends /
--shard-strict on `sozu cluster add`, a shuffle_sharding column in the
cluster table; validate_shuffle_sharding at config load and on every
AddCluster refuses the knobs without shard_percent. Hot-updatable
through BackendMap::set_shuffle_sharding_for_cluster; the worker mirrors
the validation on AddCluster, as it does for health checks.

Tests: unit tests for the k formula, the HRW top-k, tail-only change
when a backend is added or removed, in-shard selection under four
policies, strict refusal vs fallback spill-over, shard-restricted
fail-open with and without a healthy backup, strict refusal with an
unhealthy shard, fallback fail-open picks inside the shard, non-uniform
weights, sticky precedence, zero allocations, config and state
validation, and key derivation for a sharded round-robin cluster; e2e
(e2e/src/tests/shuffle_sharding_tests.rs) for in-shard, FALLBACK and
STRICT with the whole predicted shard down, and re-adding the cluster
without shard_percent turning sharding off.

Docs: doc/configure.md "Shuffle sharding" with the literature and an
enable-time note (upgrade the main process and every worker, and retire
older CLIs whose read-modify-write drops the fields, before setting
shard_*), metrics tables, configure_cli.md, architecture.md,
mux LIFECYCLE.md, testing.md, bin/config.toml, CHANGELOG. Line citations
of cluster_h2_command in configure_admin_ops.md become prose, since
they drifted with every edit of request_builder.rs.

Refs #524

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit a810211 into main Sep 30, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/shuffle-sharding branch September 30, 2026 10:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant