Repository navigation
perf(metrics): make the local drain's per-request path allocation-free and index backends by id - #1561
Merged
Conversation
Add a Criterion bench that replays the metric sequence `SessionMetrics::register_end_of_session` hands the worker's `Aggregator` (two cluster-labelled and two proxy-wide times, the six `record_backend_metrics!` emissions and `access_logs.count`) against a drain already holding n = 1, 10, 100, 1000 and 10000 backends of one cluster, at both the default `cluster` and the `backend` cardinality level. A counting global allocator also reports heap allocations per replayed session, because the path's contract is zero allocation in steady state and a wall-clock figure cannot show a violation. Refs #1548 Signed-off-by: Florentin Dubois <[email protected]>
…ission `LocalDrain::receive_cluster_metric` and `receive_backend_metric` reached the cluster row through `cluster_metrics.entry(cluster_id.to_owned())`. `BTreeMap::entry` takes an owned key, so the copy of `cluster_id` was made on every cluster-labelled emission, not only on a cluster's first sighting: nine heap allocations per request at both the default `cluster` and the `backend` cardinality level, whatever the number of backends. Both sites now look the row up with `get_mut(&str)` first and build the owned key only on the insert branch, the shape `MetricsMap::receive_metric` already uses for the metric name. The per-request emission path is back to zero allocation in steady state. `steady_state_emission_does_not_allocate` replays five requests' worth of emissions a hundred times against a primed drain and asserts that the thread made no allocation, counted by a test-only global allocator. It fails before the fix with 4500 allocations (100 x 5 x 9). Refs #1548 Signed-off-by: Florentin Dubois <[email protected]>
…ning them `LocalClusterMetrics` kept its backends in a `Vec<LocalBackendMetrics>` and found the target of each backend-labelled emission with `iter_mut().find(|b| b.backend_id == backend_id)`, plus a second full scan through `contains_backend` whose result only fed a `debug_assert!`. Under `metrics.detail = "backend"` every request emits up to seven such metrics (the six of `record_backend_metrics!` and `access_logs.count`), so each request ended with fourteen linear scans over the cluster's backends. The backends are now a `BTreeMap<String, MetricsMap>` keyed by backend id, the container this file already uses for clusters and metric names. `get_mut(backend_id)` takes the id as `&str` through `Borrow<str>`: the lookup is O(log n) and allocates nothing, and the owned id is still built only on a backend's first sighting. `remove_backend` removes by key, and `LocalBackendMetrics`, whose only extra field was the key itself, gives way to a `backend_to_filtered_metrics` helper. Observable difference: `ClusterMetrics.backends` in a metrics query response is now sorted by backend id instead of listed in first-sighting order. The text output of `sozu metrics` is unaffected: it regroups the rows through a `HashMap` and so never printed them in a stable order. A memorised index held by the session was rejected: `remove_backend` can drop a backend under a live session, and any removal from a `Vec` shifts the index of every later backend, so a kept index would silently route metrics to the wrong backend. `backend_metrics_route_to_their_own_backend` replays an interleaved sequence over forty backends in two clusters, with removals and re-appearances, against a reference model keyed by the (cluster, backend) pair. It passes on the former `Vec` and on the map, and turns red when the lookup is sabotaged to return the first backend instead of the requested one. Refs #1548 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 26, 2026 12:06
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 26, 2026
`BackendRegistry::id_for` runs once per backend connection a mux session opens, and copied `Backend::backend_id` into a fresh `Rc<str>` each time even though `intern` had already reused the backend's slot. Each registry slot now keeps the `Rc<str>` id and the address it read when the session first interned the backend, and `id_for` clones them: a redial is a reference-count increment and no longer borrows the `RefCell`. The id is still copied once per session and backend, at interning. The cache cannot go stale: neither field is written after `Backend::new`, and a reload that replaces a backend builds a new `Rc`, which takes a new slot. Measured with a counting global allocator over 64 redials of each of two interned backends: 128 allocations before (one per dial), 0 after. Making `Backend::backend_id` itself an `Rc<str>` would also remove the per-session copy, but it changes a public field of `sozu_lib::backends::Backend` and breaks 14 sites in `lib/` alone before its tests and `e2e/` are compiled, so the change stays inside the registry. `sozu-lib`'s unit-test binary installs a thread-local counting allocator (`lib/src/lib.rs`, `test_allocations`), so a private hot-path call can carry an allocation budget; `a_redial_of_an_interned_backend_allocates_nothing` pins this one at zero. It is the binary's only global allocator: the local drain's `steady_state_emission_does_not_allocate` (#1561) moves onto it from its private `#[global_allocator]`, which cannot coexist with a second one in the same binary, and still asserts zero allocations. The new registry type shifts `mod.rs` by 39 and 87 lines, and the 24 `mod.rs:NNN` citations in `LIFECYCLE.md` and `doc/testing.md` are re-anchored to the same text. Closes #1564 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 26, 2026
`BackendRegistry::id_for` runs once per backend connection a mux session opens, and copied `Backend::backend_id` into a fresh `Rc<str>` each time even though `intern` had already reused the backend's slot. Each registry slot now keeps the `Rc<str>` id and the address it read when the session first interned the backend, and `id_for` clones them: a redial is a reference-count increment and no longer borrows the `RefCell`. The id is still copied once per session and backend, at interning. The cache cannot go stale: neither field is written after `Backend::new`, and a reload that replaces a backend builds a new `Rc`, which takes a new slot. Measured with a counting global allocator over 64 redials of each of two interned backends: 128 allocations before (one per dial), 0 after. Making `Backend::backend_id` itself an `Rc<str>` would also remove the per-session copy, but it changes a public field of `sozu_lib::backends::Backend` and breaks 14 sites in `lib/` alone before its tests and `e2e/` are compiled, so the change stays inside the registry. `sozu-lib`'s unit-test binary installs a thread-local counting allocator (`lib/src/lib.rs`, `test_allocations`), so a private hot-path call can carry an allocation budget; `a_redial_of_an_interned_backend_allocates_nothing` pins this one at zero. It is the binary's only global allocator: the local drain's `steady_state_emission_does_not_allocate` (#1561) moves onto it from its private `#[global_allocator]`, which cannot coexist with a second one in the same binary, and still asserts zero allocations. The new registry type shifts `mod.rs` by 39 and 87 lines, and the 24 `mod.rs:NNN` citations in `LIFECYCLE.md` and `doc/testing.md` are re-anchored to the same text. Closes #1564 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 26, 2026
Closes #1564 `BackendRegistry::id_for` (`lib/src/protocol/mux/mod.rs`) runs once per backend connection a mux session opens, and copied `Backend::backend_id` into a fresh `Rc<str>` each time even though `intern` had already reused the backend's slot. ## Change Each registry slot is now a private `RegistryEntry { handle, backend_id: Rc<str>, address }`. The `Rc<str>` and the address are read once, when the session first interns the backend, and `id_for` clones them: a redial is a reference-count increment and no longer borrows the `RefCell`. The cache cannot go stale: neither field is written after `Backend::new`, and a reload that replaces a backend builds a new `Rc`, which takes a new slot with its own entry (the slot semantics are unchanged). ## Measured Counting global allocator, 64 redials of each of two already-interned backends (`a_redial_of_an_interned_backend_allocates_nothing`): | | Allocations per dial (steady state) | |---|---| | Before | 1 (128 for 128 dials; the test fails with exactly that count) | | After | 0 | The first dial of a backend in a session still copies its id once (plus the table's own growth). ## Why not `Backend::backend_id: Rc<str>` That would also remove the once-per-session copy, but it changes a public field of `sozu_lib::backends::Backend`. Trying it breaks 14 sites in `lib/` alone (`backends.rs`, `health_check.rs`, `udp/health.rs`, `tcp.rs`, `load_balancing.rs`, `mux/mod.rs`) before the tests and `e2e/` are even compiled. The registry-local cache removes every per-dial allocation without touching that API. Prior art, both allocating the identity once on the control plane and reading it by reference on the hot path: - Pingora (`cloudflare/pingora@4487f7b2`, 2026-09-11): `pingora-load-balancing/src/lib.rs:172-190` defines `Backend` as address, weight and `Extensions`, with no string id; the membership is published as a shared `Arc<BTreeSet<Backend>>` (`lib.rs:581`) built when discovery updates, not per request. - HAProxy (`haproxy/haproxy@0ceb8c65`, 2026-09-25): `struct server` carries `char *id` (`include/haproxy/server-t.h:389`), `strdup`ed once at config parse (`src/server.c:3772`) and read in place when a log line renders `%s` (`src/log.c:4667`). ## Tests `sozu-lib`'s unit-test binary now installs a thread-local counting allocator (`lib/src/lib.rs`, `test_allocations`, same shape as `lib/tests/backend_selection.rs`), because `id_for` is private and unreachable from an integration test. It is that binary's only global allocator: the local drain's `steady_state_emission_does_not_allocate` (#1561, merged meanwhile) moves onto it from its own private `#[global_allocator]`, which cannot coexist with a second one (the merge with `e123d736` failed with `cannot define multiple global allocators` without a textual conflict). Its zero-allocation assertion is unchanged; seen red at 2400 allocations with the `entry(cluster_id.to_owned())` lookup restored, green without. Documented in `doc/testing.md` §2 and `LIFECYCLE.md` invariant 14. The new type shifts `mod.rs`, so 24 `mod.rs:NNN` citations in `LIFECYCLE.md` and `doc/testing.md` are re-anchored to the same text in the same function. Local runs, each command on its own with its exit code read directly: - `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd`: exit 0 - `cargo +nightly fmt --all -- --check`: exit 0 - `cargo clippy` (same features) `--all-targets -- -D warnings`: exit 0 - `cargo test` (same features) `-p sozu-lib` (1164 unit tests), `-p sozu`, `-p sozu-e2e -- --skip tests::fuzz_tests::` (449 passed): exit 0 on the `e123d736` rebase; not rerun after the rebase onto `57c92699` because LOAD1 was above 8 (27.8, then 30.4) - `cargo test --locked -p sozu-command-lib` (without those features, which the crate does not declare): exit 0 - `RUSTFLAGS="--cfg tokio_unstable"` `cargo test -p sozu-sim` and `cargo clippy -p sozu-sim --all-targets -- -D warnings`: exit 0 - `check_doc_citations.py` `--self-test`, `--root .`, `--base 57c9269`, `--audit --root .`: exit 0 (the audit's 7 advisory findings are all in files this PR does not touch) - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`: exit 0 Out of scope, noted for a follow-up: the dial path still allocates in `Mux::dial_backend` (`backend.backend_id.to_string()` for the gauge label, `cluster_id.to_owned()`) and in `Router::backend_from_request` (`(*dialed.backend.backend_id).to_owned()` into the stream context), and the reused-connection branch of `Router::decide_after_gate` allocates two `String`s of the backend id per request. 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]>
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.
Closes #1548
What the measurement found
LocalDrain::receive_cluster_metricandLocalDrain::receive_backend_metricreached the cluster row throughcluster_metrics.entry(cluster_id.to_owned()).BTreeMap::entrytakes an owned key, socluster_idwas copied on every cluster-labelled emission: up to 9 heap allocations per request, at the defaultclusterdetail level as well as atbackend, whatever the backend count.Vecis per cluster (LocalClusterMetrics::backends), not per worker. It is pruned byRemoveBackend(Server::remove_backendfans oneremove_backendout per removed id), byRemoveClusterand bysozu metrics clear, sonis bounded by the cluster's live backends. One gap:RemoveBackendsets no tombstone, so a session that is still open when its backend is removed re-creates the row when it ends. This is documented indoc/observability.md; this PR does not change it.metrics.detail = "backend".MetricDetailLevel::default()isCluster, which stripsbackend_idbefore the drain sees it.remove_backendremoved withVec::retain, and any removal shifts every later index, so an index kept by the session could silently route metrics to the wrong backend.Change
perf(bench):lib/benches/local_drain.rsreplays oneregister_end_of_sessionagainst a drain holding n = 1…10000 backends of one cluster. A counting global allocator reports allocations per request.perf(metrics): bothreceive_*sites now tryget_mut(&str)first and build the owned key only on a cluster's first sighting.perf(metrics):backendsbecomes aBTreeMap<String, MetricsMap>, looked up withget_mut(&str)throughBorrow<str>. The only observable effect is that a metrics query lists a cluster's backends sorted by id instead of in first-sighting order.No new dependency. In the production diff, every
to_owned/to_string/String::from/format!/clone/into_owned/collectsits either on an insert branch (first sighting) or on the query path. None is on the lookup path.Evidence
Deterministic:
Vec1 / 5.5 / 50.5 / 500.5 at n = 1 / 10 / 100 / 1000,BTreeMap1 / 5.5 / 10.0 / 15.6. A request does 7 lookups. The old code also ran a secondcontains_backendscan whose result only fed adebug_assert!. I did not check whether release builds elide it.perfandvalgrindare not installed on the machine, so there are no instruction counts.Timings: base, fix 1 and fix 1+2 were run interleaved, 3 s per case, over two rounds. Every figure below was launched with LOAD1 < 4, and LOAD1 was between 1.85 and 2.54 before and after every second-round run.
There is no crossover: the map is at least as fast as the
Vecfrom n = 1.Tests, each seen red then green:
steady_state_emission_does_not_allocatefails with 4500 allocations (100 × 5 × 9) when theget_mutfast path is removed.backend_metrics_route_to_their_own_backendchecks each backend against a reference model, with removals and re-appearances. It passes on the oldVecand fails when the lookup is sabotaged to return the first backend.Signed-off-by: Florentin Dubois [email protected]