Skip to content

perf(backends): select a backend without allocating or cloning candidates - #1557

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
perf/backend-selection-no-alloc
Sep 26, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
perf/backend-selection-no-alloc

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Every backend selection collected its candidates into a fresh Vec of cloned Rc<RefCell<Backend>> (BackendList::available_backends), once per tier it tried, because LoadBalancingAlgorithm::next_available_backend took &mut Vec<Rc<RefCell<Backend>>>. Random added two allocations of its own: its weight Vec and the cumulative weights inside WeightedIndex.

Measured

Counting global allocator (lib/tests/backend_selection.rs), 256 steady-state selections of a ten-backend cluster after 16 warm-up selections, per tier and policy:

Tier Before (allocations per selection) After
Primary (backups and unavailable backends interleaved) 2 (Vec, then its growth); Random: 4 0
Backup (every primary unavailable) 1; Random: 3 0
Fail-open (nothing passes can_open) 2; Random: 4 0

Rc traffic per selection: one increment and one decrement per healthy candidate before, one increment (the returned backend) after. 0 allocations holds under all six policies and all three load metrics (30 tier x policy cells).

Change

  • BackendList owns a Vec<usize> of candidate positions. add_backend reserves it for the whole list on the control plane; each selection clears and refills it with the unchanged predicates: primary (!backup && can_open()), then backup, then fail-open (Normal and retry policy OKAY).
  • Contract change on a public trait: LoadBalancingAlgorithm::next_available_backend takes a new Candidates<'_> view (the backend list plus those positions; Copy; len, is_empty, get, iter, Index) instead of &mut Vec. View position i is the i-th candidate in list order, so every policy computes the same index it computed over the collected Vec. Repository-wide grep (code, docs, e2e, sim): nothing outside lib/src/backends.rs and lib/src/load_balancing.rs implements or calls the trait.
  • Random replaces WeightedIndex with a scan that accepts exactly the weight sets WeightedIndex::new accepts (non-empty, no negative weight, no i32 overflow, positive total), samples the same UniformInt<i32> over [0, total), and returns the position WeightedIndex::sample's partition_point returns. A seeded Random replays the same sequence.
  • Maglev's cold-start table build reads the view directly; Maglev::rebuild keeps its slice signature.
  • BackendList::available_backends stays public and unchanged, off the selection path.

No protocol or security impact: no wire, config, metric or log change. Selection results are unchanged, as pinned below.

Tests

  • backend_selection_allocates_nothing_in_steady_state: red on origin/main (30 failing cells, 256 to 1024 allocations per 256 selections), green here.
  • backend_selection_pick_sequences_are_pinned: replays pick sequences recorded from origin/main for RoundRobin, Random, LeastLoaded and PowerOfTwo (connections, requests), Hrw and Maglev (keyed and unkeyed), on all three tiers. Unavailable and backup backends sit between the candidates, and excluded backends carry the lowest load, so an index computed over the wrong list picks differently. It passes on origin/main and here. connection_time is excluded because PeakEWMA decays with wall-clock time; it stays in the allocation test.
  • random_weighted_pick_matches_weighted_index: the new draw against WeightedIndex plus the choose fallback, over valid, zero, negative, overflowing, singleton and empty weight sets, 64 seeds by 32 draws. Changing the scan's > to >= makes it fail.
  • The existing load-balancing unit tests call the policies through a pick helper that builds a whole-list view.

Docs

CHANGELOG.md, doc/configure.md and doc/lifetime_of_a_session.md (the candidate walk no longer builds a fresh Vec), the PowerOfTwo cost section, and one re-anchored citation in lib/src/protocol/proxy_protocol/LIFECYCLE.md (same line of Backend::try_connect, moved by one line).

Commands run

  • cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd
  • cargo +nightly fmt --all -- --check
  • cargo clippy --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd --all-targets -- -D warnings
  • cargo test -p sozu-lib --locked, cargo test -p sozu --locked, cargo test -p sozu-command-lib --locked
  • cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::
  • RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked and the matching cargo clippy -p sozu-sim --all-targets -- -D warnings
  • .github/scripts/check_doc_citations.py with --self-test, --root ., --base e2fd5f0dde2938a2c8df1d51b7d7b367dd152e36, --audit --root .
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked

No Criterion bench was run: the host's one-minute load stayed above 4 for the whole session.

Out of scope: BackendRegistry::id_for's Rc::from(str) per dial, the adjacent item the issue lists.

Closes #1549

Signed-off-by: Florentin Dubois [email protected]

…ates

Every selection collected its candidates into a fresh Vec of cloned
Rc<RefCell<Backend>> through BackendList::available_backends, once per
tier it tried, because LoadBalancingAlgorithm::next_available_backend
took &mut Vec<Rc<RefCell<Backend>>>. Random added two more allocations:
its weight Vec and the cumulative weights inside WeightedIndex.

Measured with a counting global allocator over 256 steady-state
selections of a ten-backend cluster, before: 2 allocations per selection
on the primary and fail-open tiers, 1 on the backup tier, 2 more under
Random, and one Rc increment per healthy candidate. After: 0 under all
six policies and every load metric on all three tiers, and one Rc
increment, for the returned backend.

BackendList owns a Vec<usize> of candidate positions, sized by
add_backend on the control plane and refilled by each selection with the
unchanged primary, backup and fail-open predicates. The trait now takes a
Candidates<'_> view of the backend list through those positions; view
position i is the i-th candidate in list order, so every policy computes
the index it computed over the collected Vec. Random replaces
WeightedIndex with a scan that accepts the same weight sets, samples the
same UniformInt<i32> and returns the same position, so a seeded Random
replays the same sequence. Maglev's cold-start build reads the view;
Maglev::rebuild keeps its slice signature. available_backends stays
public, off the selection path.

lib/tests/backend_selection.rs pins zero allocations per selection (red
on the previous code) and replays pick sequences recorded from the
previous code for every policy on lists with interleaved unavailable and
backup backends. random_weighted_pick_matches_weighted_index compares the
new draw with WeightedIndex across valid, zero, negative, overflowing,
singleton and empty weight sets.

Closes #1549

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit d2d4bbd into main Sep 26, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/backend-selection-no-alloc branch September 26, 2026 12:27
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…h the request lifecycles (#1656)

## Summary

Writes up the hot-path zero-copy and system-call work merged between 2026-09-26 and 2026-09-28, and rewrites the request lifecycle documentation so it describes the code as it now stands. The work covers the access logs, the request id, `TCP_INFO`, `ClusterId`, the H1 header editor, the H2 output queue and HPACK codec, the read and write paths, accept and close, session setup, and the drain loop. The new document says what changed, how it works, why it was done, and what was measured before and after each change. The lifecycle documents now say, for UDP, TCP, H1, H2 and the mux, which system calls and allocations each step still pays on the nominal path.

Documentation and comments only: every changed `.rs` line is a comment (`git diff origin/main -- '*.rs' | grep '^[-+]' | grep -vE '^[-+]\s*(//|\*|$)|^(\+\+\+|---)'` prints nothing), and no production code, test or dependency changes.

## Files

| File | Why |
|---|---|
| `doc/hot_path_zero_copy.md` (new) | Campaign document. §1 goal and rules; §2 method (fixed scenario, instruments) and the closing measurement; §3 one section per theme, each with its mechanism, rationale, before/after figures and PRs; §4 correctness and safety fixes found along the way; §5 invariants and the tests that hold them; §6 the 66 PRs merged in the window. |
| `doc/lifetime_of_a_session.md` | Rewritten: event loop, accept, TLS, PROXY pre-flight, the H1, H2, TCP and UDP lifecycles, the mux session, close, soft stop and GOAWAY. Each protocol has a table of the system calls and allocations still paid on the nominal path. |
| `lib/src/protocol/udp/LIFECYCLE.md` | Removes the `SelectBackend` / `BackendResolved` round trip, which no longer exists, and adds a §13 per-datagram cost table. Citations converted to symbols. |
| `lib/src/protocol/mux/LIFECYCLE.md` | Adds §12, what a request costs on the nominal path. Converts the last five line citations outside pinned blocks, corrects the "cross-client" wording, and replaces `Router::connect` with `Router::plan_connect`. |
| `lib/src/protocol/kawa_h1/LIFECYCLE.md` | 23 line citations converted to symbols. The §2.1/§2.2 wording from #1655 is kept. |
| `doc/h2_mux_internals.md` | Corrects the "cross-client" wording in three places. The pinned blocks are unchanged. |
| `CHANGELOG.md` | Corrects the "cross-client" wording in the #1627, #1631 and #1632 entries, and adds a `docs` entry. |
| `doc/README.md` | Links the new document. |
| `doc/architecture.md`, `CLAUDE.md` | Both still described `file.rs:LINE` citations, and `CLAUDE.md` still pointed at the stale `lifetime_of_a_session.md`. |
| `doc/udp_simulation.md`, `doc/testing.md` | Describe the `ChangeBackendSet` action that replaced `BackendResolved` in the UDP simulator. |
| comments in `lib/src/{http,https}.rs`, `lib/src/protocol/mux/{mod,h2,stream}.rs`, `lib/src/udp.rs`, `lib/src/protocol/udp/{flow,manager}.rs` | Section references into the rewritten `lifetime_of_a_session.md` (the close path is now §11), the retired UDP `SelectBackend` / `BackendResolved` round trip, and the frontend-connection scope of a shared H2 backend connection. Line counts unchanged, so no pinned block moves. |

## Closing measurement

Measured on 2026-09-28. Two release binaries (`--no-default-features --features crypto-ring,opentelemetry,splice,simd`, glibc malloc), one built at `b5169d44` and one at `c086b456`, run interleaved pass by pass with two repetitions each. During the intentrace passes the one-minute load average was 10.7–24.9 in the first repetition and 2.7–8.5 in the second for the scenarios without keep-alive, and 1.5–2.9 for the keep-alive ones. Setup: one worker, a `file://` access log, a `python3 -m http.server` backend on loopback (an HTTP/1.1 variant for the keep-alive rows), `curl`, N = 20.

Instruments: system calls with `intentrace -p <worker>`, ANSI codes stripped and counted on the system-call name field, cross-checked by an `LD_PRELOAD` descriptor tracer; allocations with an `LD_PRELOAD` malloc counter.

Figures are per request; ranges are the two repetitions.

| Scenario | System calls (intentrace) | Heap operations | Bytes requested |
|---|---|---|---|
| H1, one request per connection | 26.25–26.70 → **18.45–18.85** | 83.65–83.85 → **39.95–40.35** | 84 327–84 445 → **15 793–16 069** |
| H1 keep-alive, 20 requests | 14.75 → **9.65** | 50.80 → **7.80** | 8 362 → **1 322** |
| H1 keep-alive over TLS | 15.75 → **10.70** | 63.30 → **20.25–20.30** | 10 644–10 680 → **3 638–3 640** |
| H2 over TLS, one request per connection | 61.25–61.60 → **40.15–40.75** | 412.15–413.90 → **240.60–241.75** | 137 094–137 857 → **47 559–47 963** |
| H2 over TLS, 20 streams on one connection | 25.05 → **13.55** | 83.40–83.90 → **41.15–42.00** | 11 021–11 029 → **4 792–4 825** |
| TCP relay (splice) | 39.00–39.10 → **36.05–36.15** | 31.45 → **14.45** | 4 068 → **3 778** |

**Baseline limit.** `b5169d44` was the first release-build baseline. It already included #1552, #1553, #1557, #1558, #1561, #1565, #1568, #1578 and #1581, so their gains are not in this table; each is given, with its own figures, in its section of the document. All other per-PR figures come from the PR descriptions. UDP was not traced: its costs are read from the code and labelled as such. The TLS rows include 15 `getrandom(2)` per handshake, which comes from `crypto-ring`. That is the default provider (`bin/Cargo.toml`, `lib/Cargo.toml`, the Dockerfile, the RPM and Arch packages), so default builds pay it; a `crypto-aws-lc-rs` build issues none on this path (§3.13).

Earlier reference points: the campaign's first map (2026-09-26, `LD_PRELOAD` interposer on a debug build, `stdout` access log) counted about 25.1 system calls per H1 request and 34.8 per H2 request, and undercounted because it did not interpose `fcntl` or `recv`. The 106.25 → 25.35 figure is the `tcp://` access-log pass of #1552, measured on its base `ca058989`.

## Doc/code contradictions corrected

- Reusing a keep-alive backend involves no liveness probe. What exists is a replay on a fresh connection (`ReplayOnFreshBackend`).
- `TcpSession::shutting_down` answers `true`: a TCP session is closed on the first soft-stop pass. It has done so since `be5dd44b` (2020-01-10).
- The UDP soft stop is `UdpProxy::notify`'s `SoftStop` arm, not `shutting_down`, and it is active: `Drain`, then `close_all_flows` on every listener session, then the listener sockets are deregistered.
- An H1 backend EOF is read by a later `readable` since #1606, not together with the last bytes.
- `backend.pool.size` is incremented in `Mux::dial_backend`.
- A new UDP flow also costs three `fcntl`, a `getsockname` and a `getpeername` in `udp_connect`, even in release builds.
- The UDP simulator's `BackendResolved` action is now `ChangeBackendSet`.
- The UDP LIFECYCLE described a `SelectBackend` / `BackendResolved` round trip that no longer exists; selection is done in the core.
- `Router::connect` (removed) was cited instead of `Router::plan_connect`. Two code comments in `lib/src/protocol/mux/h2.rs` still name it; they are left for a later change.
- An H2 backend connection belongs to one `Mux` session and carries only the streams of one frontend connection. The #1627, #1631 and #1632 entries called it shared by several clients. Another user is reachable only behind an intermediary that multiplexes users on one frontend connection.
- Drifted citations: `h2.rs:1439` now pointed at an empty `///` line, and `https.rs:1065` no longer pointed at the shutdown write-up.

## Open question

**TCP soft stop.** On soft stop, a TCP relay session is closed on the first pass, with whatever bytes it still has in flight and no drain of its own. The documentation states this without calling it a bug; whether it is the intended behaviour is for the maintainers to decide.

## Also reflected

- #1654 (#1647): a draining H2 session waits for a header block still arriving or for a request awaiting its backend link, and a forced close is preceded by a final `GOAWAY(NO_ERROR)`.
- #1655 (kawa 0.7.2): the #1651/#1653 guards are described as shipped and now defense in depth. Their `content_length_invalid` counters stay at zero unless kawa regresses.

## Validation

- `python3 .github/scripts/check_doc_citations.py --self-test` → exit 0
- `python3 .github/scripts/check_doc_citations.py --root .` → exit 0 (54 line citations, 794 test names, 15 pinned blocks)
- `python3 .github/scripts/check_doc_citations.py --root . --base origin/main` → exit 0 ("none of the 87 cited lines compared against f5136d6 changed their text")
- `python3 .github/scripts/check_doc_citations.py --audit --root .` → exit 0. It reports 3 advisory findings, all in files this PR does not touch (`doc/configure_admin_ops.md`, `lib/src/protocol/proxy_protocol/LIFECYCLE.md`).
- `cargo +nightly fmt --all -- --check` → exit 0
- `cargo build --locked` → exit 0
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` → exit 0
- Relative markdown links in the touched files were checked with a script: 0 broken. CI has no markdown link checker.

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.

Every backend selection allocates a Vec of candidates, and the load-balancing trait requires it

1 participant