Skip to content

perf(mux): stop allocating per request on a reused backend connection - #1584

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
perf/mux-per-request-allocs
Sep 26, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
perf/mux-per-request-allocs

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

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 (perf(mux): stop copying the backend id into a String per request #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 perf(mux): stop copying the backend id into a String per request #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 39dcc9c3b9d5d17ec1199e756d56b08a97e4b43f, --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]

A request that reuses a backend connection still allocated three times
past routing, and a dial copied the cluster id twice (#1583):

- remove_backend_stream dropped the emptied reverse-index Vec, which
  Context::link_stream rebuilt on the next attach. The entry now keeps
  its capacity; the key leaves with its connection in the dead-backend
  sweep of Mux::ready_inner, and Mux::close clears the index, so it
  stays bounded by the session's live backend connections. The debug
  consistency check counts non-empty entries and asserts every emptied
  one names a connection still in router.backends.
- both ledger drains emptied Context::backend_deltas with mem::take, so
  the charge Connection::start_stream records reallocated it. They now
  go through one BackendRegistry::apply_all that drains in place.
- Router::plan_connect copied the routed cluster id into
  HttpContext::cluster_id. It now moves it there, and decide_after_gate
  and consult_ip_gate borrow it; ConnectResume stops carrying a copy.
- ConnectPlan::Dial carries the one copy a dial needs and
  Mux::dial_backend moves it into Position::Client instead of copying
  it again.

No public type changes. Context::backend_streams may now hold an empty
entry for a live connection.

Measured with crate::test_allocations, steady state on a reused H1
keep-alive backend, gated and ungated: the reuse branch goes from 9 to
6 allocations per request in the debug test build (3 are the debug-only
history push) and makes 3 in release, all inside route_from_request.
consult_ip_gate still makes 3 in SessionManager bookkeeping. Both are
out of scope and measured separately by the new tests.

#1581's test now asserts zero outright for the decision and its mux
bookkeeping. New tests measure the whole branch on both paths against a
control of the out-of-scope costs, and drive a real Mux::dial_backend
to check the connection owns the allocation the plan carried. Each fix
was reverted on its own and its test seen red.

Closes #1583

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit e49d78a into main Sep 26, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/mux-per-request-allocs branch September 26, 2026 19:31
FlorentinDUBOIS added a commit that referenced this pull request Sep 26, 2026
…#1594)

Closes #1589

## What

#1584 left three heap allocations per routed request inside `Router::route_from_request`. This removes the two that need no public type change. The third, the cluster id cloned out of the route table, needs `ClusterId = String` changed in sozu-command-lib and is out of scope, as is `SessionManager::track_cluster_connection`.

**`original_authority`.** `route_from_request` copied the authority (`host.to_owned()`) into `HttpContext::original_authority` on every request. Its only reader is the `X-Forwarded-Host` injection in `apply_request_rewrites_and_headers`, which runs only when the frontend rewrites the host. Routing never mutates `HttpContext::authority`: the rewrite changes only the kawa status line and headers. So the helper now copies `context.authority` itself, only on a host rewrite, and moves that copy into `original_authority`. On the rewrite path this is one copy fewer than before, two instead of three.

**`trie_path`.** `Router::lookup` gave the trie a `Vec::with_capacity(16)` to record the wildcard and regex segments it matched. It allocated this even for a literal host, which records nothing. `lookup_recursive` was already generic over its `SubMatchSink`, so a crate-private `InlineTrieMatches` implements that trait. It keeps the first 16 segments in a fixed array on the stack and spills to a `Vec` only past them. `RouteResult::new_with_trie` borrows the segments from it, so `$HOST[n]` templates see every segment in the same walk order. `TrieMatches` and `TrieNode::lookup_with_path` are unchanged. No new dependency and no `unsafe`.

## Observable difference

The field type is unchanged, but the value of one `pub` field changes. `HttpContext::original_authority` is now `None` on a request without a host rewrite, where it used to be `Some(authority)`. Its own documentation already said "`None` when no host rewrite happened". Nothing else in the tree reads it: no access log, audit record or redirect reads it. On a host rewrite it is still set, and `X-Forwarded-Host` still carries the authority the client sent.

## Prior art: HAProxy (at `0ceb8c65`)

- `src/pattern.c:151`: `static THREAD_LOCAL struct pattern static_pattern;` A map or ACL match returns its result through a per-thread buffer that is reused, never allocated (filled at `src/pattern.c:516-520`).
- `src/pattern.c:507`: `ebst_lookup(&expr->pattern_tree, smp->data.u.str.area)` walks the ebtree on the sample's own bytes, in place. `src/pattern.c:683` and `src/pattern.c:991` (`ebmb_lookup_longest`) do the same.
- `src/sample.c:3487` and `src/regex.c:24` use `regmatch_t pmatch[MAX_MATCH]`, a fixed array for regex captures. `src/regex.c:155-156` clamps the match count at `MAX_MATCH`. `InlineTrieMatches` uses the same fixed array but spills instead of clamping, so no segment is dropped and routing semantics stay the same.

## Measurements

The counts come from the crate's counting allocator (`crate::test_allocations`); this change adds no `#[global_allocator]`.

| `route_from_request`, per request, reused keep-alive backend | before | after |
|---|---|---|
| debug test build, compared with the control | +2 (128 over 64 requests, both ungated and gated) | **0** |
| release build | 3 (as measured in #1583) | **1**, the cluster id clone |

- `a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id`: its control used to run all of `route_from_request`. It now counts only the cluster id `to_owned()` and the debug-only `DebugEvent::Str` push, so the rest of routing is measured. It is red before the fix (`left: 128, right: 0`). It turns red again, at 64, if either site is reintroduced on its own.
- `a_tree_lookup_allocates_nothing_past_its_route_result`: `Router::lookup` on a literal, a wildcard and a regex host allocates exactly what `RouteResult::forward` of the cluster id allocates. It is red with the old `Vec::with_capacity(16)` (`left: 4, right: 3`).
- `a_host_capture_past_sixteen_trie_segments_keeps_every_segment`: a 20-segment regex host, rewritten through `$HOST[1]`…`$HOST[20]`. It pins today's tree order. It is red if the spilled entries are dropped.
- `inline_trie_matches_rewinds_across_the_spill_like_a_vec`: pushes and rewinds across the inline/spill boundary give the same record as a `Vec`.
- `only_a_host_rewrite_records_the_original_authority`: with a host rewrite, `original_authority` and `X-Forwarded-Host` carry the client's authority. Without one, both are absent. It is red with the old unconditional copy.

A pre-existing quirk, unchanged here: a tree rule numbers its regex-segment captures right to left, in trie walk order, while a pre/post rule reads the whole-host regex left to right. The 20-segment test pins the current tree order, and this PR does not change it.

## Verification

- `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd`, then `cargo +nightly fmt --all -- --check`, then clippy with the same features and `--all-targets -- -D warnings`
- `cargo test -p sozu-lib` / `-p sozu` / `-p sozu-command-lib`, and `cargo test -p sozu-e2e -- --skip tests::fuzz_tests::` (449 passed)
- the sim test and sim clippy under `RUSTFLAGS="--cfg tokio_unstable"`
- `check_doc_citations.py` `--self-test`, `--root .`, `--base e49d78a…` and `--audit --root .`. One citation in `doc/testing.md` moved with `route_from_request`; it is re-anchored to the same `sni: sni.to_owned(),` line in the same function.
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`

`CHANGELOG.md` and `doc/testing.md` are updated in the same commit.

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): a reused backend connection still allocates per request in the reverse index, the delta ledger and the cluster id

1 participant