Repository navigation
perf(mux): stop allocating per request on a reused backend connection - #1584
Merged
Merged
Conversation
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
requested review from
Wonshtrum and
llenotre
as code owners
September 26, 2026 18:32
This was referenced Sep 26, 2026
Closed
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]>
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.
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
remove_backend_streamdropped the emptiedVec,Context::link_streamrebuilt itMux::apply_backend_deltasand the pre-plan settle inMux::ready_inneremptied it withmem::takeHttpContext::cluster_id:Router::plan_connectstoredSome(cluster_id.to_owned())cluster_idinConnectPlan::Dialthen again inMux::dial_backendWhole reuse branch (
plan_connect, thenplan_connect_resumeon 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-onlyDebugEvent::Strhistory push), 3 in release (measured after the change).Changes
Vecstays in itsContext::backend_streamsentry. The key leaves with its connection in the dead-backend sweep ofMux::ready_inner(only when empty, so a still-linked entry keeps surfacing as drift), andMux::closeclears the index. Bound: the index holds at most one entry per live backend connection of the session. I chose this over a single spareVecbecause it needs no signature change at the fiveremove_backend_streamcall sites (one inh1.rs, three inh2.rs, all left untouched) and it keeps the per-connection capacity where the next link wants it.BackendRegistry::apply_all, which usesdrain(..). 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.plan_connectmoves the routedStringintoHttpContext::cluster_id;decide_after_gateandconsult_ip_gateborrow it from there, andConnectResumeloses itscluster_idfield. A missing id is refused withMaxSessionsMemoryrather than gated against an empty key.Mux::dial_backendtakes the plan'sStringby value and moves it intoPosition::Client; the two gauge labels read the stream's copy.No public type changes, so no breaking entry. One observable difference:
Context::backend_streams(apubfield) 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_innernow counts non-empty entries and additionally asserts that every emptied entry names a connection still inrouter.backends. That is stricter than before: an entry that empties for a token already removed from the router now fires. It held acrosssozu-lib(1151 tests),sozu-e2e(449) and thesozu-simsweeps, 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:
route_from_request:captured_authority = host.to_owned()(lib/src/protocol/mux/router.rs), thetrie_pathVec::with_capacity(16)ofRouter::lookup(lib/src/router/mod.rs:165), and the cluster id cloned out of the route table intoRouteResult(lib/src/router/mod.rs:2329/:2364). Removing the last one means carrying anRc<str>cluster id in the route table, i.e. changingClusterId = Stringinsozu-command-lib.consult_ip_gate, on the gated path (every production request has a source address): thecluster_id.to_owned()handed toSessionManager::track_cluster_connection(moved fromresume.cluster_id(), same count) and the clones inside it (lib/src/server.rs:809). That isSessionManager'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_idmeasures the whole branch on the ungated and the gated path against a control of exactly the out-of-scope costs (route_from_requestand the debug history push); the gate'sSessionManagerbookkeeping is excluded from both sides.a_dial_moves_the_planned_cluster_id_into_the_backend_connectiondrives a realMux::dial_backendagainst a loopback backend and checks that the connection'sPosition::Clientowns the very allocationConnectPlan::Dialcarried.Each fix reverted on its own, test seen red, then restored green:
mem::takeinapply_all→ same two fail (448 against 384);Some(routed.as_str().to_owned())→ the branch test fails (448 against 384);cluster_id.clone()intonew_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), theContext::backend_streamsfield doc andCHANGELOG.mdupdated in the same commit; 25mod.rs/router.rsline citations inLIFECYCLE.mdanddoc/testing.mdre-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-simandcargo clippy -p sozu-sim --all-targets -- -D warningscheck_doc_citations.py --self-test,--root .,--base 39dcc9c3b9d5d17ec1199e756d56b08a97e4b43f,--audit --root .(its findings are on untouchedh2.rs/expect.rscitations, pre-existing)RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedCloses #1583
Signed-off-by: Florentin Dubois [email protected]