Repository navigation
feat(lb): shuffle-shard clients over the HRW ranking of their affinity key - #1712
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 30, 2026 09:08
…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
force-pushed
the
feat/shuffle-sharding
branch
from
September 30, 2026 09:47
a029ac6 to
2cda4f0
Compare
This was referenced Sep 30, 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.
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:
C(N, k)shards againstN / kpartitions: 28 against 4 for eight backends in shards of two.Decisions implemented (maintainer comment on #524)
affinity_header/affinity_cookievalue, falling back to the IP when absent.k = max(2, ceil(shard_percent × N / 100)), capped atN. It is the topkof the weighted HRW ranking (hrw_score, now public) over the cluster's configured primary backends.Nmoves a client only at the tail of its ranking.N >= shard_min_backends, which defaults to 8. Off untilshard_percentis set.FALLBACK(default) spills over to the rest of the cluster, backup tier and fail-open included, and countsbackend.shard.spillover.STRICTselects nothing (HTTP 503, TCP close) and countsbackend.shard.exhausted.CHANGELOG.mdanddoc/configure.md.shard_percentis set.Design
BackendList::select_with_key(lib/src/backends.rs) narrows the primary candidates to the shard before the cluster'sload_balancingpolicy runs. Any policy therefore picks inside the shard (LEAST_LOADEDbalances within it,HRWpins to its top member with in-shard failover), and retries stay in it.next_available_backend_with_keykeeps its signature.BackendMap::select_backend(HTTP reserve and TCP connect) and the UDP keyed path read theShardOutcomeand count it under the cluster id.shard_scores,shard) are reserved inadd_backendbesidecandidates.select_nth_unstable_bypartitions the ranking in O(N), andretainkeeps the candidates in list order forCandidates::new.cluster_reads_affinity_key(router.rs, shared by the TCP proxy) is true forHRW/MAGLEVorshard_percent. Without this, a shardedROUND_ROBINcluster would silently not shard.Clusterproto fieldsshard_percent = 20,shard_min_backends = 21,shard_mode = 22(new enumShardMode { FALLBACK, STRICT }).--shard-percent/--shard-min-backends/--shard-strictonsozu cluster add; ashuffle_shardingcolumn in the cluster table; the fields inDebug.validate_shuffle_shardingruns at config load and on everyAddCluster: percent in1..=100, min ≥ 2, and the knobs are refused withoutshard_percent.BackendMap::set_shuffle_sharding_for_clusterfromserver.rs::add_cluster.CONN_RETRIES = 3.k = 2, a request whose two members refuse spills over, or is refused, on its third attempt.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.Protocol/security impact: selection narrowing only; no parser, framing or TLS change.
STRICTcan 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.
compute_shardnever shardsa_sharded_selection_stays_in_the_shard,an_exhausted_shard_refuses_in_strict_and_spills_in_fallbackshard ["pong0", "pong2"], reached ["pong0", "pong1", "pong2", "pong3", …],strict answered Some((200, "pong2"))STRICTspills overshard [2, 3] down, strict answered Some((200, "pong0")),key 0: strict never leaves the shardFALLBACKrefusesshard [0, 3] down, fallback answered Some((503, …))only_hrw_maglev_and_sharded_clusters_derive_a_keya sharded cluster derives a key whatever its policyVeca_sharded_selection_allocates_nothing256 sharded selections made 256 allocationsGreen: every test above passes after restoring.
Tests added
lib/src/backends.rs):a_shard_is_the_top_of_the_hrw_rankinga_shard_changes_only_at_its_tail_when_backends_change: add withkfixed, add withkgrowing, remove a non-member, remove a membera_sharded_selection_stays_in_the_shard(ROUND_ROBIN, LEAST_LOADED, RANDOM, HRW)an_exhausted_shard_refuses_in_strict_and_spills_in_fallbacka_strict_shard_fails_open_inside_itselfa_sticky_backend_outside_the_shard_winsa_sharded_selection_allocates_nothingload_balancing.rs):a_shard_size_follows_the_decided_formula.router.rs):only_hrw_maglev_and_sharded_clusters_derive_a_key.shuffle_sharding_reaches_the_add_cluster_order_and_is_validated,add_cluster_with_invalid_shuffle_sharding_rejected.e2e/src/tests/shuffle_sharding_tests.rs): four backends,shard_percent = 50,shard_min_backends = 4, with the shard predicted viahrw_score. The shard's members are left without a listener, so connections to them are refused.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: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).cluster_h2_commandindoc/configure_admin_ops.mdbecame prose, because they drift with every edit ofrequest_builder.rs.Review fixes (FIX-FIRST on a029ac6)
STRICTnow decides between refusing and failing open on the primary tier only. Thecluster_can_openthat also counted backups is replaced byprimaries_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.CHANGELOG.mdand in thedoc/configure.md"Before enabling it" note now says:shard_*: an older worker ignores fields 20–22 and serves unsharded.QueryClusterById→AddClusterread-modify-write (cluster h2) drops the fields and silently disables sharding.FALLBACKfail-open pick that lands back in the shard is reportedInShard(settle_spill_outcome) and not counted asbackend.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.a_strict_shard_failing_health_checks_refuses_while_others_are_healthy. Red with theprimaries_can_openguard forced false:key 0: strict must refuse, not fail open.a_shard_is_the_top_of_the_hrw_ranking, which also asserts that the weights move some shard.test_re_adding_a_cluster_without_shard_percent_turns_sharding_off, re-added underHRWso the key is still derived. Red whenServer::add_clusterskipsset_shuffle_sharding_for_clusterwithoutshard_percent:sharded Some((503, …)), then unsharded Some((503, …)).compute_shardcounts the primaries and checksshard_size/min_backendsbefore hashing, so a cluster below the threshold pays no hash. Thehas_tier_candidatewalk is gone, including for unsharded clusters.k > 1".DefaultHashercross-toolchain caveat is on "across restarts".backend.shard.*rows are aligned betweenconfigure.mdandmetrics.md.--affinity-header/--affinity-cookiehelp mentions that sharding reads the key under any policy.validate_shuffle_shardingonAddClusternext to the health-check mirror inserver.rs.