Skip to content

feat(lb): pass a client affinity key to Maglev and HRW on HTTP and TCP - #1706

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
feat/lb-affinity-key-l7-tcp
Sep 30, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
feat/lb-affinity-key-l7-tcp

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 29, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #524 (PR 1 of 2: the affinity key; shuffle sharding follows in PR 2).

Problem

Only the UDP datapath handed HRW / MAGLEV a key. HTTP, HTTPS and TCP selected with None, so a cluster configured with either policy silently fell back to round-robin: a client's requests visited every backend in turn, contrary to the documentation.

Design

  • Key derivation. affinity_key_from_ip and affinity_key_from_value (lib/src/load_balancing.rs) use the DEFAULT_HASH_SEED-seeded FNV-1a + splitmix64 hash the policies already use, with distinct domain tags for addresses and values.
    • Deterministic across workers and restarts; the values are pinned by a unit test.
    • ::ffff:a.b.c.d keys as a.b.c.d.
  • HTTP/HTTPS (H1 and H2). Router::plan_connect derives the key right after routing (affinity_key in router.rs), for HRW/MAGLEV clusters only; every other policy derives none and selects exactly as before.
    • Source: the cluster's affinity_header value (case-insensitive name, first occurrence) or affinity_cookie value (exact name), else the source IP after the PROXY protocol.
    • Header blocks and the cookie jar are read in place and hashed without copying. Values are hashed raw: a quoted cookie and its unquoted spelling are two keys.
    • An affinity_cookie named like the listener's sticky cookie reads the value captured before that cookie is elided.
    • Stored in HttpContext::affinity_key, so a replay reuses it like the routed cluster.
  • TCP. TcpSession::connect_to_backend keys on effective_session_address, which is the PROXY-v2 source when the cluster expects one.
  • Where the key enters selection (on top of refactor(mux): selection reserves, a failed dial releases #1709's shapes):
    • HTTP: BackendSelector::select(cluster, affinity, key) → BackendMap::reserve_backend(cluster, key, now) / reserve_sticky_backend(cluster, cookie, key, now) → select_backend → next_available_backend_with_key.
    • TCP: BackendMap::backend_from_cluster_id(cluster, key, now).
  • Precedence.
    • A sticky cookie naming a live backend still wins over the key.
    • Connection reuse keeps priority (owner decision): the key applies only when a new backend connection is dialled. A request reusing a backend connection its session holds (H1 keep-alive, H2 multiplexed) follows that connection. Behind an upstream proxy or CDN multiplexing tenants over warm keep-alive/H2 connections, tenants follow the connection's backend. Documented and pinned by e2e tests.
  • Config plumbing.
    • Proto Cluster.affinity_header = 18, affinity_cookie = 19.
    • TOML keys, --affinity-header / --affinity-cookie on sozu cluster add, an affinity_key column in the cluster table, lengths-only Debug.
    • validate_affinity_key runs at config load and on every AddCluster: at most one of the two, each an RFC 9110 token. Host and Cookie are refused case-insensitively, since Sōzu never keeps them as headers.
    • The main state refuses a cluster that names a key and serves a TCP frontend, in both orders (AddCluster after AddTcpFrontend, and the reverse). The TOML loader refuses the keys on a tcp cluster.
    • Hot-updatable.

Protocol/security impact: a header/cookie key is client-chosen, so a client can pick its backend. That is the same property as a sticky cookie, and it is documented. No parser, framing or TLS change.

Check before upgrading

HTTP, HTTPS and TCP clusters already configured with HRW or MAGLEV ran round-robin and now pin each client by its source IP. Clusters whose clients arrive from few addresses — behind a NAT, or an L4 balancer without the PROXY protocol — concentrate on few backends. Switch policy, enable the PROXY protocol, or key on a header or cookie. The note is in both CHANGELOG.md and doc/configure.md.

Allocations

  • deriving_an_affinity_key_allocates_nothing: 256 derivations make 0 allocations.
  • stamping_a_dialled_backend_allocates_nothing is unchanged at 0.

Red / green

Each case was run with the fix reverted, then restored.

  • e2e (e2e/src/tests/affinity_key_tests.rs). Each test predicts every key's backend with the library's Rendezvous: provable outcomes, not statistical ones.
    • Key dropped in RegistrySelector::select (after the refactor(mux): selection reserves, a failed dial releases #1709 rebase): HTTP, HTTP header, HTTPS, H2 header/cookie and H2-reuse all fail. For example: source 127.0.0.2: predicted pong0 …, reached ["pong0","pong1","pong2","pong3"].
    • Key dropped in TcpSession::connect_to_backend: source 10.0.0.1: predicted backend-0 for every session, reached [backend-0 … backend-3].
    • Header/cookie keying disabled: h2 X-Tenant: tenant-0: predicted pong0 …, reached ["pong3" ×4].
    • Reuse pinning, with reuse disabled in Router::decide_after_gate (reuse_token.filter(|_| false)):
      • one keep-alive connection: predicted Some("pong1") for both … reached [Some("pong1"), Some("pong0")]
      • one H2 connection: predicted Some("pong2") for both … reached [Some("pong2"), Some("pong3")]
    • Green: 7/7 (HTTP IP, HTTP header, HTTPS IP+cookie, H2 header+cookie, TCP PROXY-v2, H1 keep-alive reuse, H2 reuse), 3 consecutive runs.
  • Unit.
    • key 0 must stay on one backend under HRW → green.
    • 256 derivations made 128 heap allocations, expected none → green.
    • Sticky-named cookie: left: Some(1686…) right: Some(1733…) with the capture arm removed → green.
    • Also added: pinned hash values, derivation rules, Host/Cookie refusal, the TCP-frontend/key refusal in both orders.

Validation (head c70f65a, rebased on main 4420d13 = #1709)

  • 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: 1407 passed. -p sozu-command-lib: 212. -p sozu: passed.
  • cargo test -p sozu-e2e -- affinity_key_tests cluster_ip_limit: 11/11.
  • 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 ("Client affinity", reuse behaviour, upgrade check, raw values, refused names, forwarding-policy interactions), doc/configure_cli.md, doc/architecture.md, doc/lifetime_of_a_session.md, lib/src/protocol/mux/LIFECYCLE.md, bin/config.toml, doc/testing.md, CHANGELOG.md (Fixed with the upgrade check, Added).

FlorentinDUBOIS added a commit that referenced this pull request Sep 30, 2026
Refs #1684. This is the third PR of the sequence the maintainer set in #1684 (comment): G2 = (a), the UDP shape with reservation at selection.

It is based on `origin/main` `4918ad4f`, which includes #1698 (G1), #1700 (G3), #1704 and #1705.

## Design

- **Selection reserves.**
  - `BackendMap::reserve_backend(cluster, now)` and `reserve_sticky_backend(cluster, cookie, now)` choose a backend, then raise its `active_connections` by one (`Backend::reserve_connection`). The raise happens under the same borrow as the choice.
  - The next selection weighs that reservation exactly as it weighed the count `Backend::try_connect` took at the dial.
  - Nothing connects during selection.
  - The empty and no-candidate handling that `backend_from_cluster_id` had moved into a private `BackendMap::select_backend`, which both paths share.
- **The embedder dials.**
  - The router's seam returns a backend and no socket.
  - `Mux::dial_backend` connects to `BackendId::address` after the selection borrow is released. The address travels inside `BackendId`, which is the `(BackendId, SocketAddr)` shape the maintainer asked for.
- **A failed dial releases, through the ledger.**
  - A `connect(2)` error pushes the new `BackendChange::DialFailed(Instant)` and returns `BackendError::ConnectionFailures`.
  - Applying `DialFailed` calls `Backend::release_failed_dial`, which does `dec_connections`, `failures += 1` and `retry_policy.fail(at, rng)`.
  - `BackendRegistry::apply_all` now takes the worker's `&RefCell<BackendMap>`. It borrows it only in the `DialFailed` arm, to draw the backoff jitter from the map's generator; every other change leaves the map alone.
  - The existing drain before each `Router::plan_connect` applies the release before the next selection reads the counters. The backend then sits exactly where a failed `Backend::try_connect` left it.
- **A successful dial keeps the reservation** as its connection's count. `ConnectionClosed` releases it, as before.
- **A factory `sim/` can reach:** `pub fn BackendId::new(slot, backend_id, address)`.
  - A slot means something only to the registry that issued it; the mux still mints through `BackendRegistry::id_for`.
  - A selector holds no socket, so a simulator implements one without `mio`. `git grep -q mio -- sim/Cargo.toml` still exits 1.
- **LIFECYCLE §9, invariant 14** gains the bullet "Selection reserves, failure releases". The "Drain before any read" bullet drops its argument for selecting and dialling in one call.
- **Unchanged:** the TCP proxy (`tcp.rs`) still calls `BackendMap::backend_from_cluster_id` and `Backend::try_connect`.

### Renames, for #1706 (#524, `feat/lb-affinity-key-l7-tcp`)

#1706 adds an affinity `key` to `select_and_dial` and `backend_from_cluster_id`. Whichever PR merges second rebases onto the other:
- `router::BackendDialer` → `router::BackendSelector`
- `BackendDialer::select_and_dial` → `BackendSelector::select`, same `(cluster_id, affinity)` parameters
- `router::DialedBackend` → `router::SelectedBackend`, which drops its `socket` field
- crate-private `RegistryDialer` → `RegistrySelector`
- `Router::backend_from_request` now returns `BackendId`, where it returned `(TcpStream, BackendId)`

`BackendMap::backend_from_cluster_id` keeps its signature. The mux now calls the new `reserve_backend` and `reserve_sticky_backend`, so #1706's `key` belongs on those as well.

### Pre-existing `active_connections` leak, not fixed here

Three exits of `Mux::dial_backend` after a successful `connect(2)` drop the new connection without releasing its connection count:
1. `Connection::new_h2_client` returning `None`, when the buffer pool is exhausted (`BackendConnectionError::MaxBuffers`).
2. A refused `Connection::start_stream`, when the backend's maximum concurrent streams is reached.
3. The `register_socket` rollback. It releases the `active_requests` charge and the gauges, but not `active_connections`.

On `main` each of these already leaked the `+1` that `Backend::try_connect` took on success. Now each leaks the reservation, which is the same `+1` taken earlier. **This change does not make it worse:** on each of these paths the count is the same before and after. So I did not fix it here, and LIFECYCLE §9 names the three exits.

**Proposed follow-up:** push `BackendChange::ConnectionClosed` for the reserved slot on all three exits, the same release a closing connection emits. Pin it with one test per exit, asserting `active_connections == 0` after the drain.

### Behaviour

- A successful dial behaves the same.
- A failed synchronous dial leaves the same end state (`active_connections`, `failures`, backoff), applied at the next drain.
- The AllDown → Available availability event now fires after a successful selection rather than after a successful connect.
- The pinned pick sequences (`backend_selection_pick_sequences_are_pinned`) are unchanged.

## Measurements

Measured with a throwaway probe (`size_of`, plus `test_allocations::allocations()` around `Mux::dial_backend`), not committed.

| | before (`080351ba`) | after |
|---|---|---|
| heap allocations per `Mux::dial_backend`, selection to linked stream (3 runs) | 6, 6, 6 | 6, 6, 6 |
| steady-state selection (`backend_selection_allocates_nothing_in_steady_state`) | 0 | 0 |
| router stamping (`stamping_a_dialled_backend_allocates_nothing`) | 0 | 0 |
| `size_of::<BackendChange>()` / `BackendDelta` | 16 / 24 B | 16 / 24 B (`Instant` fits the niche) |
| `Backend` / `BackendList` / `BackendMap` / `MuxClear` | 208 / 72 / 472 / 4984 B | unchanged |

No new allocation, syscall or dynamic dispatch is added on the dial path.
- The `connect(2)` moved from `Backend::try_connect` to `Mux::dial_backend`; it is the same single syscall.
- The `BackendMap` borrow happens only on a failed dial.

## Tests: red, then green

For each mutation below, I changed the production code, quoted the failing assertion, then restored it. All pass green afterwards.

- **Mutation:** `Backend::reserve_connection` returns `Ok(())` without `inc_connections`.
  - `a_second_selection_observes_the_first_selections_reservation`: `the second selection landed on the first one's backend: the first selection did not reserve its connection (first=backend-a active=0, second=backend-a active=0)`
  - `power_of_two_weighs_every_reservation`: `2 selections must hold 2 reservations, got [0, 0]`
  - `a_failed_dial_releases_its_reservation_and_records_the_failure`: `selection reserves`, `left: 0 right: 1`
- **Mutation:** `release_failed_dial` without `dec_connections`.
  - `a_failed_dial_releases_its_reservation_and_records_the_failure` and `a_synchronously_failed_dial_releases_its_reservation` both fail with `a failed dial must release exactly its one reservation (saturating at 0)`, `left: 1 right: 0`
- **Mutation:** `Mux::dial_backend` returns the connect error without pushing `DialFailed`.
  - `a_synchronously_failed_dial_releases_its_reservation`: `the failed dial must release the reservation selection took`, `left: 1 right: 0`
- **Mutation:** an extra `inc_connections` after a successful connect.
  - `a_successful_dial_counts_its_connection_once`: `one dial must hold exactly one connection on its backend`, `left: 2 right: 1`

Notes on the new and changed tests:
- `a_second_selection_observes_the_first_selections_reservation` replaces `a_second_selection_observes_the_first_dials_connection`. It now selects twice with no dial and no drain in between. A `RENAMED_TESTS` entry keeps the #1550 CHANGELOG citation resolving.
- `a_synchronously_failed_dial_releases_its_reservation` dials `255.255.255.255:80`, which fails before any packet leaves (`ENETUNREACH`, or `EACCES` with a default route). It asserts the `Err`, so a host where that connect succeeds fails the test instead of passing it.
- `invariant_14_*` in `h2.rs`: all 6 pass, and every assertion is unchanged. Only two things changed:
  - their `reconcile` helper gains an `unreachable!` arm for `DialFailed`, since no invariant-14 scenario dials;
  - two `registry.apply(delta)` calls now pass a local `BackendMap`.
- `stamping_a_dialled_backend_allocates_nothing` now uses a socket-free `StubSelector` whose id comes from `BackendId::new`. That is the shape a simulator will use.

## Docs

- `lib/src/protocol/mux/LIFECYCLE.md`: §3.2 and §9 invariant 14.
- `router.rs`: the `BackendSelector` doc, rewritten. The old doc argued that selection and dial had to be one call; it now describes reservation and release.
- `doc/lifetime_of_a_session.md` and `doc/benchmark.md`: the dial path.
- `doc/rate-limit-design.md` and `lib/src/server.rs`: they now say where the non-blocking dial lives, `Mux::dial_backend` for HTTP and `Backend::try_connect` for TCP.
- `e2e/src/tests/tests.rs`: a TO SEE THIS RED note now points at the dial's new site and says its measurement was taken at the old one.
- `doc/testing.md` §5: how a simulator's selector mints ids, and the reservation rule it must keep.
- `CHANGELOG.md`: a BREAKING (library API) entry, listing the renames.

## Validation

Run on head `208ed9eb`, rebased onto `4918ad4f`. Each exit code was checked directly, never through a pipe:
- `cargo +nightly fmt --all -- --check` -> exit 0
- `cargo clippy --all-targets --locked -- -D warnings` -> exit 0
- `cargo clippy --all-targets --all-features --locked -- -D warnings` -> exit 0
- `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` -> exit 0
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0
- `cargo test --workspace --locked --exclude sozu-e2e` -> exit 0 (1865 passed, 0 failed, 17 ignored, all ignores already on main)
- `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0 (31 passed)
- `cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::` -> exit 0 (515 passed)
- `cd fuzz && cargo +nightly fuzz build` -> exit 0
- `python3 .github/scripts/check_doc_citations.py` -> exit 0
- `python3 .github/scripts/check_doc_citations.py --base origin/main` -> exit 0
- `python3 .github/scripts/check_doc_citations.py --self-test` -> exit 0
- `python3 .github/scripts/check_doc_citations.py --root .github/scripts/testdata/citations` -> exit 1 (the broken fixture must fail)



Signed-off-by: Florentin Dubois <[email protected]>
Only the UDP datapath handed the consistent-hashing policies a key. HTTP,
HTTPS and TCP selected with none, so a cluster configured with HRW or
MAGLEV silently fell back to round-robin and a client's requests visited
every backend in turn (#524).

These datapaths now derive a client key for a cluster using either
policy, and none for any other policy, which selects exactly as before:

- TCP: the client source IP, the PROXY-v2 source when the cluster
  expects one (TcpSession::connect_to_backend).
- HTTP/HTTPS (H1 and H2): the value of the cluster's new affinity_header
  or affinity_cookie when the request carries it non-empty, else the
  source IP (post PROXY protocol). Router::plan_connect derives it right
  after routing, reads the header blocks and cookie jar in place and
  hashes without allocating, and stores it in HttpContext::affinity_key
  so a replay reuses it like the routed cluster. An affinity_cookie named
  like the listener's sticky cookie reads the value captured before that
  cookie was elided. Values are hashed raw.

The key is the DEFAULT_HASH_SEED-seeded FNV + splitmix64 hash the
policies already use (affinity_key_from_ip, affinity_key_from_value), so
every worker and restart pins a client to the same backend; an
IPv4-mapped address keys as its IPv4 form. It enters selection through
BackendSelector::select, BackendMap::reserve_backend and
BackendMap::reserve_sticky_backend (HTTP), and
BackendMap::backend_from_cluster_id (TCP), which take it as a parameter.
A sticky cookie naming a live backend still wins, and connection reuse
still wins: the key applies only when a new backend connection is
dialled, so tenants multiplexed by an upstream proxy over one warm
keep-alive or H2 connection follow that connection's backend.

affinity_header / affinity_cookie are Cluster proto fields 18 and 19,
TOML cluster keys, and --affinity-header / --affinity-cookie on
`sozu cluster add`, shown in the cluster table. At most one, each an RFC
9110 token; Host and Cookie are refused as header names. The main state
refuses a cluster that names a key and serves a TCP frontend, in both
orders, and the TOML loader refuses the keys on a tcp cluster.
Hot-updatable, since the router reads the cluster per request.

Upgrade note: HTTP/TCP clusters already configured HRW or MAGLEV ran
round-robin and now pin by source IP; clusters behind a NAT or an L4
balancer without the PROXY protocol concentrate on few backends.
Documented in CHANGELOG and doc/configure.md.

Tests: e2e/src/tests/affinity_key_tests.rs predicts every key's backend
with the library's Rendezvous and asserts HTTP (source IP; two clients
behind one address split by header), HTTPS (source IP; cookie), HTTP/2
(header; cookie) and TCP (PROXY-v2 source) each stay on it, all failing
under the former round-robin fallback; and pins that two keys on one H1
keep-alive or one H2 client connection reach the same backend. Unit
tests pin the hash, the derivation rules, the sticky-cookie capture,
zero allocations for the derivation, keyed selections, sticky
precedence, and the name and TCP refusals.

Docs: doc/configure.md "Client affinity", configure_cli.md,
architecture.md, lifetime_of_a_session.md, mux LIFECYCLE.md,
bin/config.toml, CHANGELOG.

Refs #524

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the feat/lb-affinity-key-l7-tcp branch from 11aca8a to c70f65a Compare September 30, 2026 06:59
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 1ca4b05 into main Sep 30, 2026
51 of 52 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/lb-affinity-key-l7-tcp branch September 30, 2026 08:17
FlorentinDUBOIS added a commit that referenced this pull request Sep 30, 2026
…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 added a commit that referenced this pull request Sep 30, 2026
…y key (#1712)

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*](https://aws.amazon.com/builders-library/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](https://doi.org/10.1109/90.663936).

## Decisions implemented (maintainer comment on #524)

- **Key:** the affinity key from #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 #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`.



Signed-off-by: Florentin Dubois <[email protected]>
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