Repository navigation
perf(h1): 24.6 → 15.6 heap operations per keep-alive request - #1628
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 27, 2026 19:56
Two allocation cuts in `HttpContext::on_request_headers` and `on_response_headers` (`lib/src/protocol/kawa_h1/editor.rs`), the header editor shared by the H1 and H2 frontends. Measured on one H1 keep-alive connection of 20 requests, release, without jemalloc so the counter can interpose: 24.60 -> 15.55 heap operations per request in cleartext, 40.65 -> 31.65 over TLS. Syscalls and forwarded bytes are unchanged. Forwarding headers through one scratch. Each synthesised forwarding header took the scratch `Vec` itself with `Store::from_vec(std::mem::take(..))`, which spent two heap operations per header on the hand-over alone: `into_boxed_slice` reallocates to shrink the spare capacity away, and the next header starts again from an empty `Vec` and regrows it, 8 -> 16 -> 32 -> 64 bytes for a synthesised `Forwarded`. Each header now takes an exact-size copy of the scratch (`Store::from_slice`) and the scratch is cleared for the next one, so its 128-byte capacity is paid once per request: `X-Forwarded-For` and `Forwarded` cost three heap operations instead of seven. A request's id rendered once. The generated `X-Request-Id`, its copy kept for the access log and the `Sozu-Id` value of the request and of the response were four renderings of the same ULID, each through `Ulid`'s `Display`, which allocates a `String`; the `Sozu-Id` name was copied onto both as well. The id is now rendered on the stack (`render_ulid`) and copied once into an `Rc<str>` that the forwarded `X-Request-Id`, `HttpContext::x_request_id` and both correlation headers share through `kawa::Store::Shared`. A client-supplied `X-Request-Id` is kept verbatim and the correlation header then renders Sōzu's id into a copy of its own. The default `Sozu-Id` name is a `'static` literal; a renamed header is still copied. `Store::Shared` is behind kawa's `rc-alloc` feature, part of kawa's default set, which `sozu-lib` now enables on the already-pinned kawa 0.7.1: no dependency is added and `Cargo.lock` does not change. `HttpContext::x_request_id` becomes an `Option<Rc<str>>`. The rendering is not cached across the requests of a connection: that needs a new `HttpContext` field, which also reaches the exhaustive `HttpContext` literal in the H2 test fixtures of `lib/src/protocol/mux/h2.rs`, and is left to a change of its own. Tests, each seen red first: - `a_bare_request_costs_one_scratch_and_one_copy_per_forwarding_header` pins a bare request's header editing at 7 heap operations, plus the one copy of the `traceparent` the editor synthesises under the `opentelemetry` feature (`SYNTHESISED_TRACEPARENT`: `build_traceparent` on the stack, one `Store::from_slice`). Red at `left: 11, right: 7` with the `from_vec` hand-over restored, and at `left: 10, right: 7` with the per-header id renderings restored. - `a_response_shares_the_request_id_rendering` pins the response at 1 heap operation (the captured `reason`) and its bytes, on both the generated and the client-chosen `X-Request-Id` path. Red at `left: 3, right: 1`. - `header_editing_output_is_byte_exact_across_keep_alive_requests` pins the forwarded bytes: synthesised headers on three keep-alive requests, including the `traceparent` recorded on `ctx.otel` under the feature, and client-supplied `X-Forwarded-For`, `Forwarded` and `X-Request-Id` extended or kept verbatim. - `render_ulid_matches_the_display_rendering` checks `render_ulid` against `Display` at `0`, `u128::MAX`, `1 << 127` and generated ids. Two `editor.rs` line citations moved with the new code and are renumbered in `doc/h2_mux_internals.md` and `lib/src/protocol/kawa_h1/LIFECYCLE.md`. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
perf/h1-hot-path-next
branch
from
September 27, 2026 21:29
826a59a to
1892bac
Compare
This was referenced Sep 27, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
## Problem
On an HTTP/1.1 keep-alive connection every request carried the first request's ULID. The generated `X-Request-Id`, `Sozu-Id` on the request and on the response, `%REQUEST_ID` in default answers and the access log's `request_id` stayed constant for the whole connection. `doc/configure.md` and `lib/src/protocol/kawa_h1/LIFECYCLE.md` both say the id rotates per request.
## Cause
`HttpContext::reset` is the per-request reset of an H1 connection's slot, called from the keep-alive branch of `ConnectionH1::writable`. It cleared the request-scoped fields but left `HttpContext::id` untouched, and its postcondition asserted that behaviour: `debug_assert_eq!(self.id, id_before, "reset() must preserve the request id")`. The unit test `test_reset_preserves_connection_state` pinned it too, with `assert_eq!(ctx.id, original_id)`. Both assertions encoded the bug, because the id is request-scoped. Only `session_id` is connection-scoped. They are now inverted.
H2 was not affected: `ConnectionH2::create_stream` already mints one id per stream through `Context::next_request_id`.
## Fix
- `HttpContext::reset(&mut self, request_id: Ulid)` installs the next request's id. It asserts that the new id differs from the previous one and that it is the one it was given.
- The keep-alive branch mints that id with `Context::next_request_id`, the source that already numbers H2 streams. It builds a ULID from the pass's wall-clock snapshot (`Context::now_wall_ms`) and the per-session seeded `StdRng`. `HttpContext` owns no clock and no RNG, and the mux keeps its one-clock-sample-per-pass discipline.
- A client-supplied `X-Request-Id` is still forwarded verbatim, and `Sozu-Id` still carries Sōzu's own id. This is unchanged and matches `doc/configure.md`. A retried request is never reset, so it keeps its id.
**Visible change:** `X-Request-Id` (when Sōzu generates it) and `Sozu-Id` now change on every request of a keep-alive connection.
## Red → green
| Test | Before fix | After fix |
|---|---|---|
| `editor.rs` `test_reset_preserves_connection_state` (now `assert_ne!` on the id) | FAILED: `assertion left != right failed`, same `Ulid` on both sides | ok |
| `editor.rs` `header_editing_output_is_byte_exact_across_keep_alive_requests` (it pinned one id across 3 keep-alive requests; it now requires them distinct) | FAILED: `request 1 of the connection reuses the id of an earlier one: 01M3JB2VCVQPFGT815KEV120AE` | ok |
| e2e `test_keep_alive_rotates_request_id` (3 requests on one H1 connection, the third with a client `X-Request-Id`) | FAILED: `request 1: Sozu-Id 01M3JB4R8FM1YQG3NNDZPX813E was already used on this connection` | ok |
| e2e `test_h2_streams_carry_distinct_request_ids` (2 streams on one H2 connection) | ok (H2 was not affected) | ok |
The H2 test was seen red through sabotage: with `Context::next_request_id` returning `self.session_ulid`, it prints `Sozu-Id per stream: [Some("01M3JC2EGD43T1RQ0VP929RTJE"), Some("01M3JC2EGD43T1RQ0VP929RTJE")]` and fails. This also shows that its two streams share one connection.
## Measurements
Release binaries built on a tree carrying #1628 (then unmerged, based on `826a59ae`), before and after the fix. The fix's diff is unchanged by the later rebase onto `main` (`c974237c`, #1628 merged). The setup is 1 worker, an HTTP listener, and a Python HTTP/1.1 keep-alive backend. A warm-up connection comes first. Then `intentrace -c -p <worker>` traces one `curl` invocation that sends 20 GETs on one connection. Two runs each:
| | before-1 | before-2 | after-1 | after-2 |
|---|---|---|---|---|
| distinct response `Sozu-Id` | 1/20 | 1/20 | **20/20** | **20/20** |
| distinct backend `Sozu-Id` | 1/20 | 1/20 | **20/20** | **20/20** |
| distinct access-log request id | 1/20 | 1/20 | **20/20** | **20/20** |
| backend `X-Request-Id == Sozu-Id` | 20/20 | 20/20 | 20/20 | 20/20 |
| `epoll_wait` / `writev` / `recvfrom` / `getsockopt` | 66/60/60/40 | 66/60/60/40 | 66/59/59/40 | 67/60/60/40 |
| `getrandom` / `clock_gettime` | 0 / 0 | 0 / 0 | 0 / 0 | 0 / 0 |
The OpenTelemetry `traceparent` is not derived from the request id: `random_id()` draws it per request. It is unaffected, and `cargo test -p sozu-lib --lib --features opentelemetry -- kawa_h1::editor` passes (39 tests).
The syscall set is identical. The ±1 differences are event-loop wakeup noise. No `getrandom` appears, because the RNG is seeded once per session in `Context::new`. No `clock_gettime` appears either: the wall-clock snapshot is the one `Mux` already takes per pass, through the vDSO. Minting the id allocates nothing, because `Ulid` is `Copy` and `StdRng` draws in place. The allocation-count tests of the header editor (`a_response_shares_the_request_id_rendering` and the keep-alive byte-exact test) stay green.
## Commands run
- `cargo build --locked`, `cargo build --all-features --locked`
- `cargo clippy --all-targets --locked -- -D warnings`
- `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings`
- `cargo +nightly fmt --all -- --check`
- `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8`
- `check_doc_citations.py`: `--self-test`, the broken fixture tree (exit 1 with a failure report), a plain run, and `--base origin/main`
## Docs
- `CHANGELOG.md` (Fixed)
- `lib/src/protocol/kawa_h1/LIFECYCLE.md` point 4
- `lib/src/protocol/mux/LIFECYCLE.md` §2.5
- `doc/configure.md`: the `sozu_id_header` section, plus the request-ID propagation section, which now states the priority of a client `X-Request-Id`
- Line citations shifted by the added lines are renumbered.
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
## Problem The access log's `client_rtt` and `server_rtt` each cost one `getsockopt(TCP_INFO)` per request. The H1 log sites (`H1::Complete`, `H1::Upgrade`, `H1::EarlyHint`) and `Endpoint::peer_rtt` read their socket at every line, and `Mux::expire_client_rtt` forgot the H2 frontend sample at every pass (#1598 made the read lazy, not rarer). On an H1 keep-alive connection that was 2.00 of the worker's 11.55 syscalls per request. ## Change Operator decision: accept one sample per connection. - `memoized_rtt` (`lib/src/protocol/mux/mod.rs`) keeps a connection's first sample in a `Cell<Option<Option<Duration>>>` on the connection (`ConnectionH1::rtt`, new field; `H2Shell::local_rtt`, existing field) and answers every later request from it. `Connection::rtt` dispatches H1/H2. - Every mux RTT read goes through it: the three H1 log sites, `EndpointServer::peer_rtt`, `EndpointClient::peer_rtt`, `ShellEndpoint::local_rtt` and `Mux::close`. A backend connection keeps its sample across keep-alive pool reuse, since the `Connection` carries it. - `Mux::expire_client_rtt` and `H2Shell::expire_local_rtt` are removed. - Pipe (TCP/WebSocket) and the TCP frontend already log once per session and are unchanged. After a WebSocket upgrade, `Pipe::log_request` still reads `socket_rtt` once, at the end of the session. That is one read per session, left out of scope. No syscall added anywhere, no allocation added (one `Cell` of 16 bytes per `ConnectionH1`), no I/O path touched. ## Sampling point, and why Hypothesis tested: "`tcpi_rtt` is 0 before the first data ACK". **Refuted** on Linux 7.2.7, loopback. A Python probe reading `TCP_INFO` (`tcpi_rtt`, `tcpi_rttvar`): - straight out of `accept`: 34 / 27 / 29 µs over three trials. This is the SYN/SYN-ACK measurement. - straight out of a blocking `connect`: 80 / 30 / 33 µs. - after 1st/2nd/3rd request on the same connection: 34 → 33 → 1301 µs. The SRTT keeps drifting. So a sample at `accept` would be valid. The chosen point is still **the connection's first access log**: - frontend: the first request completed on the connection; - backend: the first response logged through it. The lazy read is free on a connection that never logs. A backend dial is still in flight when its non-blocking `connect(2)` returns. Semantics, now documented: **"RTT sampled at the connection's first request"**, repeated on every line of that connection. The value is frozen and no longer follows the kernel's SRTT. The two cells of one line come from two different instants. ## Measurement `intentrace -p` on the worker. Release build `--no-default-features --features jemallocator,crypto-aws-lc-rs`, one worker, python `http.server` backend on loopback, `curl`, 20 requests on one client connection (plus warmup). Base `58550dd4`, runs interleaved base/after, two runs per cell, 1-minute load average 21–48 (shared host): | scenario | syscalls/req before | after | `getsockopt`/req before | after | |---|---|---|---|---| | H1 keep-alive, plaintext | 11.55, 11.55 | 9.65, 9.65 | 2.00 | 0.10 | | H1 keep-alive, TLS | 11.85, 11.85 | 9.95, 9.95 | 2.00 | 0.10 | | H2, 20 streams multiplexed on 1 connection | 12.35, 12.20 | 11.35, 11.30 | 2.00 | 1.05 | - **H1: −1.90 syscalls/req.** The remaining 0.10 is the two per-connection reads, one per side. - **H2 multiplexed: −1.00.** Sozu dials one backend H1 connection per concurrent stream (20 `connect`s in the window), so the 20 backend reads remain, one per connection. Only the 19 repeated frontend reads disappear. - **Access logs, after:** every one of the 27 lines per run carries both `client_rtt` and `server_rtt`, with no `-` cell. There are 4 distinct (client, server) pairs, one per client connection (readiness probe, two warmups, the measured one). Before: 27 distinct pairs. ## Tests Seen red on `58550dd4` before the fix, green after: - `keep_alive_requests_read_tcp_info_once_per_connection` (`h1.rs`, new). It drives 20 keep-alive requests through the real `H1::Complete` site of `ConnectionH1::writable`, with the backend recycled by `end_stream`/`start_stream` as a `Mux` does. It asserts two things: - 2 `TCP_INFO` reads in total. Red: `left: 40, right: 2`. - Both RTT cells are present on all 20 access lines, with identical values. - `a_mux_pass_keeps_the_connection_sample_and_reads_none_without_a_log` (`mod.rs`). This rewrites `a_mux_pass_forgets_the_previous_sample_and_reads_none_without_a_log`. Red: `left: None, right: Some(Some(4321s))`. Also rewritten: `snapshot_rtts_samples_the_frontend_once_per_pass` became `snapshot_rtts_samples_the_frontend_once_per_connection` (`h2.rs`). Its documented red (the memo hit removed from `memoized_rtt`) was checked: `left: 2, right: 1`. The old names are forwarded in `check_doc_citations.py` `RENAMED_TESTS`, because the CHANGELOG cites them. ## Docs - `doc/configure.md` "When each cell is measured": **Changed** RTT semantics in access logs. - `doc/observability.md`. - `doc/h2_mux_internals.md`: new "One sample per connection" section, with the measurements. - `lib/src/protocol/mux/LIFECYCLE.md`. - `CHANGELOG.md` (Changed). My line shifts in `h1.rs`, `h2.rs` and `mod.rs` moved 27 `file.rs:NNN` citations and three pinned blocks. They are re-anchored mechanically from a line diff, in both `LIFECYCLE.md`, `doc/testing.md` and `doc/h2_mux_internals.md`, and `--base origin/main` confirms every cited line's text is unchanged. ## Conflicts with open PRs - `git merge-tree` against #1628 and #1629: clean. The new test uses `"test-cluster".into()`, so it compiles with #1629's `ClusterId` too. - Against #1630: three pinned `h2.rs:NNNN` fence numbers in `doc/h2_mux_internals.md` / `LIFECYCLE.md` conflict, numbers only. Whichever PR merges second re-anchors them. - `kawa_h1/editor.rs` and `HttpContext` are untouched. ## Commands run - `cargo build --locked` - `cargo build --all-features --locked` - `cargo clippy --all-targets --locked -- -D warnings` - `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` - `cargo +nightly fmt --all -- --check` - `check_doc_citations.py` (tree, `--base origin/main`, `--self-test`, broken-fixture `--root` exit 1 with its failure report) - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8`: 2160 passed, 0 failed. Results: - The full battery passed on the pre-amend tree. - The final amend changed only a test literal (`to_owned()` → `into()`). After it I re-ran fmt, both clippy cells, the citation runs and the new test. - A first battery run had one failure: `tests::tests::test_async` (client1 99/100 responses) under `--test-threads=8` at load average 40+. I ran it 3 times in isolation on this branch and 3 times on `58550dd4`: 6/6 green. The second full battery run was green. Protocol/security impact: none. No framing, parsing, readiness or I/O change. The only change is when an access-log value is read. 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.
What
Two allocation cuts in
HttpContext::on_request_headers/on_response_headers(
lib/src/protocol/kawa_h1/editor.rs), the header editor shared by the H1 and H2 frontends.No syscall changes, and the bytes forwarded stay the same (pinned by a byte-exact test).
perf(h1): render the forwarding headers of a request through one scratch. Each synthesisedheader took the scratch
Vecitself (Store::from_vec(std::mem::take(..))). That hand-over cost two heapoperations per header:
into_boxed_sliceshrinks the spare capacity with arealloc, and the next headerregrows an empty
Vec(8 → 16 → 32 → 64 bytes forForwarded). Each header now takes an exact-size copy ofone reused scratch. A bare request goes from 14 to 10 heap operations.
perf(h1): render a request's id once and share it across its headers. The generatedX-Request-Id,its copy for the access log, and the
Sozu-Idvalue on the request and on the response were four renderingsof the same ULID, each through
Ulid's allocatingDisplay. TheSozu-Idname was also copied onto both.The id is now rendered on the stack and copied once into an
Rc<str>, and all four share it throughkawa::Store::Shared. The defaultSozu-Idname is a'staticliteral; a renamed header is still copied.A client-supplied
X-Request-Idis still forwarded verbatim, andSozu-Idstill carries Sōzu's own id.The request goes from 10 to 7 heap operations, and the response from 3 to 1.
Dependency note:
Store::Sharedneeds kawa'src-allocfeature. That feature is in kawa's default set,and
sozu-libnow enables it on the kawa 0.7.1 it already pins. No crate is added andCargo.lockdoes notchange.
HttpContext::x_request_idbecomesOption<Rc<str>>.Measurements
Worker only, release build, 1 worker,
file://access log. The load is onecurl --http1.1process sendingN = 20 requests over one keep-alive connection, after a warm-up. The backend is a Python
http.serverwith
protocol_version = "HTTP/1.1". The same run is repeated twice (rep 1, rep 2), interleaving before andafter. Before is
0155d40b(origin/mainwhen measured) and after is this branch on top of it. Syscalls arecounted with
intentrace -p <worker>on the production feature set(
--no-default-features --features jemallocator,crypto-aws-lc-rs). Allocations are counted with anLD_PRELOADmalloc counter on the same code built without jemalloc (--features crypto-aws-lc-rs), becausethe counter cannot interpose jemalloc. LOAD1 was 8–25 on a 20-core host; every deterministic count below
matched to the integer across both reps.
The unit tests predict the −9 exactly: −4 from the scratch and −5 from the id (−3 on the request, −2 on the
response). After rebasing onto
58550dd4(#1625), the branch head was measured again and gave the same numbers:15.55 and 31.65 heap operations, 11.55 and 11.85 syscalls.
The syscall shape per keep-alive request is 3 ×
epoll_wait, 3 ×recvfrom, 3 ×writevand2 ×
getsockopt(TCP_INFO). The third read/write pair comes from the test backend, not from Sōzu: Python'shttp.serversends the headers and the body as two segments. There is no per-requestepoll_ctl, no readthat ends in
EAGAIN, and noclock_gettimetrap.Tests (each seen red first)
a_bare_request_costs_one_scratch_and_one_copy_per_forwarding_headerpins 7. It went red atleft: 14, right: 10on the commit-1 recipe, then at
left: 11with thefrom_vechand-over restored and atleft: 10with theper-header id renderings restored.
a_response_shares_the_request_id_renderingpins 1 allocation and the response bytes, on both the generatedand the client-chosen
X-Request-Idpath. It went red atleft: 3, right: 1.header_editing_output_is_byte_exact_across_keep_alive_requests: three keep-alive requests with a renamedcorrelation header and
send_x_real_ip, plus client-suppliedX-Forwarded-For,ForwardedandX-Request-Id. This is a behaviour test and passed before and after.render_ulid_matches_the_display_rendering:0,u128::MAX(top digit7),1 << 127, and generated ids.Commands run
cargo build --locked,cargo build --all-features --locked,cargo clippy --all-targets --locked -- -D warnings,cargo +nightly fmt --all -- --check,cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8, and the fourcheck_doc_citations.pyruns (--self-test, the broken fixture tree exits 1,--base origin/main, plain).Everything passed on the rebased head except one run of
tests::tests::test_async, whereclient0got 99 ofits 100 responses. That was the full workspace run at LOAD1 ≈ 20:
try_asyncreads each response with a singlereceive(), which is the one-segment readdoc/testing.mdwarns about. The test then passed three times out of threewhen run alone (
cargo test -p sozu-e2e -- --exact tests::tests::test_async).The
writevshape, counted as regions and bytes per call, is identical before and after, and on the rebasedhead, for both the clear and TLS runs. The
Store::Sharedheaders therefore go throughh2_transmit::gatheronto the wire unchanged.
Two
editor.rsline citations drifted because of the new code and were renumbered(
doc/h2_mux_internals.md,lib/src/protocol/kawa_h1/LIFECYCLE.md).What is left on the H1 keep-alive path, measured, not in this PR
getsockopt(TCP_INFO)×2 per request (17 % of the H1 syscalls). These are the frontendsample_rttand the backend
peer_rttthat feed the access log. Removing them means sampling the RTT less than once perrequest, which changes what the log reports.
keep-alive request (7 → 2 in the unit test). It needs a new
HttpContextfield, and that field also has tobe added to the exhaustive
HttpContextliteral in the H2 test fixtures inh2.rs.consult_ip_gate×2,track_cluster_ip, andRouter::from_frontend. These are left to theClusterId→Rc<str>change.reserve(ConnectionH1::writable) costs 1 allocation (~request size) per request ona pooled upstream.
reasoncapture costs 1 allocation per response; a table of standard reason phrases would remove it.plaintext,
write_vectored).Pre-existing finding, not changed here: on an H1 keep-alive connection every request carries the same
HttpContext::id. The measured access log shows one request id across 20 requests.HttpContext::resetassertsthe id is preserved, while
lib/src/protocol/kawa_h1/LIFECYCLE.mdsays it "IS rotated per request" anddoc/configure.mdcalls%REQUEST_IDa per-request ULID.Signed-off-by: Florentin Dubois [email protected]