Skip to content

perf(mux): stop copying the backend id into a String per request - #1581

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

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

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1579

Since #1565 every BackendId carries its id as an Rc<str>, but the mux still turned it back into a heap String each time it stamped a request with its backend: twice per request on a reused backend connection, three times per dial.

Change

HttpContext::backend_id (lib/src/protocol/kawa_h1/editor.rs) and SessionMetrics::backend_id (lib/src/lib.rs) become Option<Rc<str>>, and every mux writer clones the BackendId's Rc:

Site Before After
Router::decide_after_gate, reuse branch (router.rs:740, :742) 2 to_string() per request 2 Rc::clone
Router::backend_from_request (router.rs:1185) 1 copy per dial Rc::clone
Mux::dial_backend, SessionMetrics copy (mod.rs:2032) 1 copy per dial Rc clone
Mux::dial_backend, gauge label (mod.rs:1986) 1 copy per dial Rc::clone
raw TCP, lib/src/tcp.rs:1747 1 String per session 1 Rc<str> per session (same count)

Measured

crate::test_allocations, 64 iterations after one warm-up. Both tests compare with as_deref(), so they compile against the old field type too; they were run red against the a3e72a3 production code with the tests in place.

Test (lib/src/protocol/mux/router.rs) Before After
a_request_on_a_reused_backend_connection_allocates_nothing: decide_after_gate on a reused keep-alive backend, minus a control doing only the mux bookkeeping it triggers (Connection::start_stream + Context::link_stream) 256 vs 128 (+2 per request) 128 vs 128 (+0)
stamping_a_dialled_backend_allocates_nothing: backend_from_request through a stub BackendDialer holding pre-connected sockets 64 (1 per dial) 0

Mux::dial_backend needs a live L7Proxy and ProxySession, for which the crate has no test double, so its two copies are counted from the source only.

The reused-connection test uses a control because the branch also triggers two allocations that do not come from the backend id. Asserting 0 on the whole branch would be false, and asserting 2 would break as soon as either is fixed:

  • remove_backend_stream (mod.rs:1123-1134) drops the emptied reverse-index Vec, which Context::link_stream rebuilds on every attach;
  • Mux::apply_backend_deltas (mod.rs:1252-1256) empties the delta ledger with std::mem::take, so the next record_backend_delta reallocates it.

These, the two per-dial cluster_id copies (ConnectPlan::Dial and Position::Client own a String) and the per-request HttpContext::cluster_id copy in Router::plan_connect stay out of this change. They are listed in #1579 and in the CHANGELOG.

Why the field type change is acceptable

Two public fields change type; no API is added. Every in-tree reader already goes through as_deref() / as_ref() (log context macros, access log, record_backend_metrics!, default answers), and Rc<str> derefs to str, so those readers compile unchanged. The breakage is 1 production writer (lib/src/tcp.rs:1747) plus 3 test fixtures (editor.rs:1537, h1.rs:1874, h2.rs:16469). bin/, e2e/, command/ and sim/ compile and pass without edits. #1565 declined the analogous change to Backend::backend_id because it broke 14 sites in lib/. Here it is the only way to remove the copy: a String field cannot hold the id without allocating.

Neither struct derives Serialize, so the change needs no serde rc feature and adds no dependency.

Docs

CHANGELOG.md (Changed), doc/testing.md §2 (users of the counting allocator, plus the control-difference pattern), the BackendId doc comment and the reuse-branch comment. mod.rs and editor.rs keep their line counts, so no LIFECYCLE.md / doc/ citation moves (check_doc_citations.py --base a3e72a34… reports 0 of 255 drifted).

Checks

Run locally at d53caea, each on its own, exit code read directly:

  • cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd → 0
  • cargo +nightly fmt --all -- --check → 0
  • cargo clippy --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd --all-targets -- -D warnings → 0
  • cargo test -p sozu-lib → 0 (1148 passed in the unit binary)
  • cargo test -p sozu → 0
  • cargo test -p sozu-command-lib → 0
  • cargo test -p sozu-e2e -- --skip tests::fuzz_tests:: → 0 (449 passed)
  • RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked → 0
  • RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --locked --all-targets -- -D warnings → 0
  • check_doc_citations.py --self-test, --root ., --base a3e72a34a8f6cfa0f54cab4cf2d4b532fa9bd657, --audit --root . → 0 each (the audit's 7 advisory findings are in files this change does not touch)
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked → 0

The e2e suite and both sim commands were rerun on d53caea itself, with a clean tree. The earlier runs had predated a comment-only edit to mod.rs and editor.rs.

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

Closes #1579

`HttpContext::backend_id` and `SessionMetrics::backend_id` become
`Option<Rc<str>>`, and the mux fills them with a clone of the `Rc<str>`
the connection's `BackendId` already carries since #1565.

- `Router::decide_after_gate`, reuse branch: two `to_string()` per
  request on a reused backend connection become two `Rc::clone`.
- `Router::backend_from_request`: one copy per dial becomes an
  `Rc::clone`.
- `Mux::dial_backend`: the second copy into `SessionMetrics` and the
  gauge label copy become `Rc` clones.
- `lib/src/tcp.rs` still builds the id once per raw TCP session, now as
  an `Rc<str>` instead of a `String`: same count as before.

Measured with `crate::test_allocations`, 64 requests or dials after a
warm-up:

- reused keep-alive backend, `Router::decide_after_gate` against a
  control performing only the mux bookkeeping it triggers
  (`Connection::start_stream` + `Context::link_stream`): 256 against
  128 before, 128 against 128 after;
- `Router::backend_from_request` through a stub dialer: 64 before,
  0 after.

The 128 left in both columns are the reverse-index `Vec` that
`remove_backend_stream` drops and `link_stream` rebuilds, and the delta
ledger `Mux::apply_backend_deltas` takes instead of draining; they are
outside this change and named in #1579 and the CHANGELOG, together with
the per-dial `cluster_id` copies and the per-request
`HttpContext::cluster_id` copy.

Both fields are public and change type. Every in-tree reader goes
through `as_deref()`/`as_ref()`, so the only production writer to
adjust is `lib/src/tcp.rs`, plus three test fixtures; `bin/`, `e2e/`,
`command/` and `sim/` compile unchanged.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 39dcc9c into main Sep 26, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/router-backend-id-no-alloc branch September 26, 2026 17:52
FlorentinDUBOIS added a commit that referenced this pull request Sep 26, 2026
…#1584)

## Summary

A request that reuses a backend connection still allocated three times past routing after #1581, and a dial copied the cluster id twice. This removes those four allocations with the smallest change to each site (#1583).

## Sites and allocations, before → after

| # | Site | Before | After |
|---|---|---|---|
| 1 | Reverse index: `remove_backend_stream` dropped the emptied `Vec`, `Context::link_stream` rebuilt it | 1 per request | 0 |
| 2 | Delta ledger: `Mux::apply_backend_deltas` and the pre-plan settle in `Mux::ready_inner` emptied it with `mem::take` | 1 per request | 0 |
| 3 | `HttpContext::cluster_id`: `Router::plan_connect` stored `Some(cluster_id.to_owned())` | 1 per request | 0 |
| 4 | `cluster_id` in `ConnectPlan::Dial` then again in `Mux::dial_backend` | 2 per dial | 1 per dial |

Whole reuse branch (`plan_connect`, then `plan_connect_resume` on the gated path, then the production release), steady state on a reused H1 keep-alive backend, gated and ungated: **9 → 6 per request in the debug test build** (3 of which are the debug-only `DebugEvent::Str` history push), **3 in release** (measured after the change).

## Changes

- (1) The emptied `Vec` stays in its `Context::backend_streams` entry. The key leaves with its connection in the dead-backend sweep of `Mux::ready_inner` (only when empty, so a still-linked entry keeps surfacing as drift), and `Mux::close` clears the index. Bound: the index holds at most one entry per live backend connection of the session. I chose this over a single spare `Vec` because it needs no signature change at the five `remove_backend_stream` call sites (one in `h1.rs`, three in `h2.rs`, all left untouched) and it keeps the per-connection capacity where the next link wants it.
- (2) Both drains go through one `BackendRegistry::apply_all`, which uses `drain(..)`. Its capacity is bounded by the most deltas a single pass pushes. The test now drains through the same function, so it exercises production code rather than a copy.
- (3) `plan_connect` moves the routed `String` into `HttpContext::cluster_id`; `decide_after_gate` and `consult_ip_gate` borrow it from there, and `ConnectResume` loses its `cluster_id` field. A missing id is refused with `MaxSessionsMemory` rather than gated against an empty key.
- (4) `Mux::dial_backend` takes the plan's `String` by value and moves it into `Position::Client`; the two gauge labels read the stream's copy.

No public type changes, so no breaking entry. One observable difference: `Context::backend_streams` (a `pub` field) may now hold an empty entry for a live connection, so key presence no longer means "has linked streams"; every reader in the tree already tested emptiness.

Debug-only hardening: the consistency check at the end of `Mux::ready_inner` now counts non-empty entries and additionally asserts that every emptied entry names a connection still in `router.backends`. That is stricter than before: an entry that empties for a token already removed from the router now fires. It held across `sozu-lib` (1151 tests), `sozu-e2e` (449) and the `sozu-sim` sweeps, all debug builds with the invariant live.

## What remains, and why it is out of scope

The goal was zero allocations per request on a reused connection for the whole branch. That is reached for everything the branch owns, but not end to end:

- 3 per request in `route_from_request`: `captured_authority = host.to_owned()` (`lib/src/protocol/mux/router.rs`), the `trie_path` `Vec::with_capacity(16)` of `Router::lookup` (`lib/src/router/mod.rs:165`), and the cluster id cloned out of the route table into `RouteResult` (`lib/src/router/mod.rs:2329` / `:2364`). Removing the last one means carrying an `Rc<str>` cluster id in the route table, i.e. changing `ClusterId = String` in `sozu-command-lib`.
- 3 per request in `consult_ip_gate`, on the gated path (every production request has a source address): the `cluster_id.to_owned()` handed to `SessionManager::track_cluster_connection` (moved from `resume.cluster_id()`, same count) and the clones inside it (`lib/src/server.rs:809`). That is `SessionManager`'s public API.

Both are measured separately by the new test, not estimated.

## Tests

Counting allocator `crate::test_allocations`, 64 requests after one warm-up; no new `#[global_allocator]`.

- `a_request_on_a_reused_backend_connection_allocates_nothing` (#1581) keeps its differential assertion and now also asserts zero outright for the decision and for the mux bookkeeping it triggers.
- `a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id` measures the whole branch on the ungated and the gated path against a control of exactly the out-of-scope costs (`route_from_request` and the debug history push); the gate's `SessionManager` bookkeeping is excluded from both sides.
- `a_dial_moves_the_planned_cluster_id_into_the_backend_connection` drives a real `Mux::dial_backend` against a loopback backend and checks that the connection's `Position::Client` owns the very allocation `ConnectPlan::Dial` carried.

Each fix reverted on its own, test seen red, then restored green:

- (1) drop the emptied entry again → the #1581 test and the branch test fail (448 against 384 over 64 requests);
- (2) `mem::take` in `apply_all` → same two fail (448 against 384);
- (3) `Some(routed.as_str().to_owned())` → the branch test fails (448 against 384);
- (4) `cluster_id.clone()` into `new_h1_client` → the dial test fails ("the connection must own the id the plan carried").

No production literal is shared with a test.

## Docs

`lib/src/protocol/mux/LIFECYCLE.md` (backend attach, the gate step, invariant 2, invariant 14's drain rule), the `Context::backend_streams` field doc and `CHANGELOG.md` updated in the same commit; 25 `mod.rs`/`router.rs` line citations in `LIFECYCLE.md` and `doc/testing.md` re-anchored to the same text in the same function, each checked against the base text.

## Validation

- `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd`, `cargo +nightly fmt --all -- --check`, `cargo clippy` (same features, `--all-targets -- -D warnings`)
- `cargo test -p sozu-lib`, `-p sozu`, `-p sozu-command-lib`, `-p sozu-e2e -- --skip tests::fuzz_tests::`
- `RUSTFLAGS="--cfg tokio_unstable"` `cargo test -p sozu-sim` and `cargo clippy -p sozu-sim --all-targets -- -D warnings`
- `check_doc_citations.py --self-test`, `--root .`, `--base 39dcc9c`, `--audit --root .` (its findings are on untouched `h2.rs` / `expect.rs` citations, pre-existing)
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`

Closes #1583

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

perf(mux): the backend id is copied into a String on every reused-connection request and on every dial

1 participant