Repository navigation
feat(metrics): add backend_header_time, the backend time-to-first-header-byte - #1546
Merged
Merged
Conversation
…der-byte The third and last of the three nginx upstream timings asked for in #426. `backend_connection_time` (nginx's `$upstream_connect_time`) and `backend_response_time` (`$upstream_response_time`) already existed; this adds `$upstream_header_time` — established backend connection to the moment the response headers finished parsing — as a `time` metric labelled `(cluster_id, backend_id)`, emitted by `record_backend_metrics!` beside the other two, so it reaches StatsD, Prometheus and `sozu metrics` with no new surface. Armed in both L7 protocols, on the edge each already discriminates for its own request-side accounting: `ConnectionH1::readable` on the `!was_main_phase && position.is_client()` transition, and `ConnectionH2::handle_headers_frame` on the `was_initial && position.is_client()` branch, where `was_initial` is what keeps an H2 trailer block from being read as a response header block. Raw TCP (`lib/src/tcp.rs`) has no headers and emits nothing under the key rather than a zero. `SessionMetrics::backend_header_time` deliberately omits the elapsed-so-far fallback its response-time sibling carries: a time to first header byte where no header byte arrived is not an in-flight value, and returning `now - connected` anyway would publish a number that grows with the wait and then freezes wherever the session ended, indistinguishable on a dashboard from a backend that answered slowly. The instant is taken unconditionally, like `backend_stop`, so a 1xx — which clears the back buffer and re-enters the transition — leaves the timing anchored on the FINAL response, the same one `backend_stop` ends on. A set-once instant would have floored the metric at ~0ms for every `Expect: 100-continue` client and hidden the upstream think time the metric exists to expose. A 101 has no successor and correctly keeps its own instant, so an upgraded session still reports the time to its `101`. Four tests, each seen red on its own named substitution. The two protocol tests pin `backend_header_time <= backend_response_time` on `Duration`s rather than on the millisecond values the histogram stores, because at millisecond resolution a fast test rounds both to 0 and the relation holds however wrong the placement is; each drives its own protocol's real read path and asserts the header instant exists while `backend_stop` is still `None`, which no placement at a response-end site can satisfy. Neither test covers the other protocol, and both say so. The two fifteen-line production insertions shifted fifteen `file.rs:NNN` citations in `doc/h2_mux_internals.md`, `doc/configure_admin_ops.md`, `doc/testing.md` and `lib/src/protocol/mux/LIFECYCLE.md`, five of them fenced-block annotations; they are renumbered here so `check_doc_citations.py --base` stays clean. Closes #426 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 26, 2026 07:29
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
Adds
backend_header_time, the backend time-to-first-header-byte — the thirdand last of the three nginx upstream timings asked for in issue #426.
$upstream_connect_timebackend_connection_time$upstream_response_timebackend_response_time$upstream_header_timebackend_header_timeThe name, and why
backend_header_time, declared asnames::backend::HEADER_TIME. It is theparallel of the two constants it sits between in
lib/src/metrics/names.rs—same
backend_prefix where nginx saysupstream_, same_timesuffix — soan operator who already charts the other two needs no translation table. The
supporting shape follows the two existing timings rather than inventing a
third: one
Option<Instant>field (SessionMetrics::backend_headers_received,beside
backend_start/backend_connected/backend_stop), one same-namedsetter, one accessor (
SessionMetrics::backend_header_time), and one morevalue recorded by
record_backend_metrics!.It is passed to the macro as an
Optionand recorded underif let Some(t),following
backend_connection_timerather thanresponse_time(which arrivesalready unwrapped), because it is legitimately absent — see the TCP path below.
Where the instant is posed, in each protocol
Both L7 protocols are covered. In each one the point already existed as a
named local, because each protocol already has to discriminate exactly this
edge for its own request-side accounting — so the new arming is the client twin
of a branch sitting right next to it, not a new discriminator:
ConnectionH1::readable(lib/src/protocol/mux/h1.rs), insideif kawa.is_main_phase(), on!was_main_phase && self.position.is_client().was_main_phaseis sampled immediately beforekawa::h1::parseand is theexisting witness of the header → body edge; the server-position twin
immediately below it is what counts a first-seen request. I found it by
looking for the request-side "headers just parsed" discriminator and taking
its client mirror, rather than searching the read path for a new condition.
ConnectionH2::handle_headers_frame(
lib/src/protocol/mux/h2.rs), onwas_initial && self.position.is_client(),the client twin of the
is_server()branch that pushesMetricEvent::RequestStarted.was_initial— the read-side kawa being inits initial parsing phase before
pkawa::handle_header— is load-bearinghere: it is what keeps a trailer block from being read as a response
header block, which is the same distinction RFC 9113 §8.1 makes and which
ConnectionH2::handle_readalready relies on.Raw TCP records nothing, and needs no edit to do so.
lib/src/tcp.rscallsSessionMetrics::register_end_of_sessionlike the L7paths, but it sets
backend_startonly and neverbackend_connected, sobackend_response_timeis alreadyNonefor it and the wholerecord_backend_metrics!block is skipped. Even reached, the new value wouldbe
Noneand theif let Some(t)arm would record nothing. The key isabsent for a TCP cluster, never present as a zero.
The
NonedecisionSessionMetrics::backend_header_timedeliberately does not carry theelapsed-so-far fallback that
backend_response_timehas ((Some(start), None) => Some(Instant::now() - start)).A time to first header byte where no header byte has arrived is not an
in-flight value, it is a value that does not exist. Publishing
now - connectedanyway would put out a number that grows with the wait andthen freezes wherever the session ended — on a dashboard that is
indistinguishable from a backend that answered slowly, which is precisely the
condition the metric is supposed to tell you about.
Noneis the honestanswer, and it is also what makes the TCP no-op fall out for free. The
reasoning is written at the accessor, and
a_session_that_received_no_response_headers_reports_no_header_timepins it.The 1xx decision
The setter overwrites unconditionally, exactly like
backend_stopand for thesame reason. After a 1xx informational response the back buffer is cleared —
ConnectionH1::writable's 100-Continue and 103-Early-Hints arms,ConnectionH2::handle_1xx_reset— so the final response returns to the initialparsing phase and re-enters the transition. Last write wins, which anchors the
timing on the final response: the same response
backend_stopends on, andwhat nginx reports.
A set-once guard would have anchored the pair on two different responses and
floored the metric at ~0 ms for every
Expect: 100-continueclient, hiding theupstream think time the metric exists to expose. It would also have silently
dropped upgrades: a
101is inside the same(100..200)range, has nosuccessor response, and under the unconditional setter correctly keeps its own
instant — so an upgraded session still reports the time to its
101.The ordering relation the tests pin
backend_header_time <= backend_response_timefor the same request, becausethe first response-header byte arrives before the last response byte. It is
false if the instant is posed in the wrong place and it cannot pass by
accident.
Asserted on
Durations, not on the millisecond values the HDR histogramstores: at millisecond resolution a fast test rounds both to 0 and the relation
would hold however wrong the placement is.
Each protocol test also asserts, after the headers alone, that the header
instant already exists while
backend_stopis stillNone. That secondassertion is what no placement at a response-end site can satisfy — and the
response-end sites are the ten
backend_stopcall sites (five inh1.rs, fourin
h2.rs, one inmod.rs).To SEE THIS RED
Each of the four tests carries its own recipe in its doc comment, and each was
run. All four literals below exist at
HEAD.the_h1_backend_header_instant_lands_on_the_headers_not_the_response_end—move
parts.metrics.backend_headers_received();out of the!was_main_phase && self.position.is_client()branch ofConnectionH1::readableand put it immediately after thestream.metrics.backend_stop();that precedesSome("H1::Complete")inConnectionH1::writable.→
the response headers must arm the backend header instant, and only theH1 test fails.
the_h2_backend_header_instant_lands_on_the_headers_not_the_response_end—move
stream.metrics.backend_headers_received();out of thewas_initial && self.position.is_client()branch ofConnectionH2::handle_headers_frameand put it immediately after thestream.metrics.backend_stop();that opensConnectionH2::complete_server_stream.→
a backend response HEADERS frame must arm the backend header instant.a_session_that_received_no_response_headers_reports_no_header_time— add(Some(connected), None) => Some(Instant::now() - connected),to the matchin
SessionMetrics::backend_header_time. →left: Some(3.713µs) right: None.The assertion this test makes is the
Noneitself. It is also where theordering inversion would come from: with the fallback in place and no
instant recorded, the reported header time becomes the elapsed wait, which
exceeds
backend_response_time— that consequence is reasoned, not assertedhere.
reset_clears_the_backend_headers_instant_with_its_siblings— dropself.backend_headers_received = None;fromSessionMetrics::reset.→
reset must clear the headers instant, or the next keep-alive request inherits the previous response's headers.Not covered
Named rather than left to be assumed:
path only; both carry a
DO NOT READ ... AS COVERINGbanner saying so. Whatkeeps them honest is that recipe 1 above reddens the H1 test alone and leaves
the H2 test green, and vice versa.
SessionMetricsaccessor, which is the valuerecord_backend_metrics!records; no test reads the key back out of the localdrain. At millisecond resolution such a test could not have pinned the
ordering anyway, which is the property at stake.
test. It follows from
kawa.clear()re-entering the transition; no teststages a 100-Continue followed by a final response.
doc/lifetime_of_a_session.mdlistsrequests, bytes_in, bytes_out, backend_response_timeillustratively and already omitsbackend_connection_time; it is left alone rather than made arbitrarilyhalf-complete. The authoritative inventories in
doc/configure.mdare bothupdated.
record_backend_metrics!is#[macro_export], so its arity change istechnically visible to a downstream
sozu-libconsumer calling it directly.The only in-tree caller is
SessionMetrics::register_end_of_session.Docs
doc/configure.md— the key added to both metric inventories (the"Timing / latency" table and the "Backend metrics (per cluster/backend)"
table), at the existing column widths, plus a short note on the nginx
correspondence, the L7-only emission, the final-response anchoring and the
ordering relation.
CHANGELOG.md— one entry at the end of theUnreleased/Addedsection.
file.rs:NNNcitations renumbered indoc/h2_mux_internals.md,doc/configure_admin_ops.md,doc/testing.mdandlib/src/protocol/mux/LIFECYCLE.md, five of them fenced-block annotations:the two fifteen-line production insertions shifted them, and
check_doc_citations.py --baseis clean at the base SHA and had to stay so.No other doc content changed.
Battery
Every line judged on its own exit code, output redirected to a file rather than
piped.
cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simdcargo +nightly fmt --all -- --checkcargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warningscargo test -p sozu-lib …cargo test -p sozu …cargo test -p sozu-command-lib --lockedcargo test -p sozu-e2e … -- --skip tests::fuzz_tests::RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --lockedRUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warningscheck_doc_citations.py --self-testcheck_doc_citations.py --root .check_doc_citations.py --base 747bc3a817a690f00906c69103458e297bd19a2dcheck_doc_citations.py --audit --root .RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedThe e2e run was gated on
LOAD1 < 8 && CHILD == 0 && PARENT == 0, measured atLOAD1=2.30 CHILD=0 PARENT=0. Clippy first refused the changeset(
clippy::type_complexityon a six-element test-fixture tuple); that was fixedby introducing a
BackendReadFixturestruct on theLedgerFixturepatternalready used in
h2.rs, not by an-Aor a relaxed gate. No check wasweakened, no test skipped or ignored, and no assertion loosened. A local run is
a pre-flight; CI is the verdict.
No production dependency added, no
async fninlib/orbin/, no socket orreadiness path touched,
command/src/command.protountouched.Closes #426
Signed-off-by: Florentin Dubois [email protected]