Skip to content

feat(metrics): add backend_header_time, the backend time-to-first-header-byte - #1546

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
feat/backend-header-time
Sep 26, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
feat/backend-header-time

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 26, 2026 •

Copy link
Copy Markdown
Collaborator

What

Adds backend_header_time, the backend time-to-first-header-byte — the third
and last of the three nginx upstream timings asked for in issue #426.

nginx sōzu status
$upstream_connect_time backend_connection_time already existed
$upstream_response_time backend_response_time already existed
$upstream_header_time backend_header_time this PR

The name, and why

backend_header_time, declared as names::backend::HEADER_TIME. It is the
parallel of the two constants it sits between in lib/src/metrics/names.rs —
same backend_ prefix where nginx says upstream_, same _time suffix — so
an 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-named
setter, one accessor (SessionMetrics::backend_header_time), and one more
value recorded by record_backend_metrics!.

It is passed to the macro as an Option and recorded under if let Some(t),
following backend_connection_time rather than response_time (which arrives
already 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:

  • HTTP/1.x — ConnectionH1::readable (lib/src/protocol/mux/h1.rs), inside
    if kawa.is_main_phase(), on !was_main_phase && self.position.is_client().
    was_main_phase is sampled immediately before kawa::h1::parse and is the
    existing 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.
  • HTTP/2 — ConnectionH2::handle_headers_frame
    (lib/src/protocol/mux/h2.rs), on was_initial && self.position.is_client(),
    the client twin of the is_server() branch that pushes
    MetricEvent::RequestStarted. was_initial — the read-side kawa being in
    its initial parsing phase before pkawa::handle_header — is load-bearing
    here: 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_read already relies on.

Raw TCP records nothing, and needs no edit to do so.
lib/src/tcp.rs calls SessionMetrics::register_end_of_session like the L7
paths, but it sets backend_start only and never backend_connected, so
backend_response_time is already None for it and the whole
record_backend_metrics! block is skipped. Even reached, the new value would
be None and the if let Some(t) arm would record nothing. The key is
absent for a TCP cluster, never present as a zero.

The None decision

SessionMetrics::backend_header_time deliberately does not carry the
elapsed-so-far fallback that backend_response_time has ((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 - connected anyway would put out a number that grows with the wait and
then 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. None is the honest
answer, 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_time pins it.

The 1xx decision

The setter overwrites unconditionally, exactly like backend_stop and for the
same 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 initial
parsing phase and re-enters the transition. Last write wins, which anchors the
timing on the final response: the same response backend_stop ends on, and
what 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-continue client, hiding the
upstream think time the metric exists to expose. It would also have silently
dropped upgrades: a 101 is inside the same (100..200) range, has no
successor 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_time for the same request, because
the 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 histogram
stores: 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_stop is still None. That second
assertion is what no placement at a response-end site can satisfy — and the
response-end sites are the ten backend_stop call sites (five in h1.rs, four
in h2.rs, one in mod.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.

  1. 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 of
    ConnectionH1::readable and put it immediately after the
    stream.metrics.backend_stop(); that precedes Some("H1::Complete") in
    ConnectionH1::writable.
    → the response headers must arm the backend header instant, and only the
    H1 test fails.
  2. the_h2_backend_header_instant_lands_on_the_headers_not_the_response_end —
    move stream.metrics.backend_headers_received(); out of the
    was_initial && self.position.is_client() branch of
    ConnectionH2::handle_headers_frame and put it immediately after the
    stream.metrics.backend_stop(); that opens
    ConnectionH2::complete_server_stream.
    → a backend response HEADERS frame must arm the backend header instant.
  3. a_session_that_received_no_response_headers_reports_no_header_time — add
    (Some(connected), None) => Some(Instant::now() - connected), to the match
    in SessionMetrics::backend_header_time. → left: Some(3.713µs) right: None.
    The assertion this test makes is the None itself. It is also where the
    ordering 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 asserted
    here.
  4. reset_clears_the_backend_headers_instant_with_its_siblings — drop
    self.backend_headers_received = None; from SessionMetrics::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:

  • Neither protocol test covers the other. Each drives one protocol's read
    path only; both carry a DO NOT READ ... AS COVERING banner saying so. What
    keeps them honest is that recipe 1 above reddens the H1 test alone and leaves
    the H2 test green, and vice versa.
  • The published key itself is not asserted end to end. The tests assert the
    SessionMetrics accessor, which is the value
    record_backend_metrics! records; no test reads the key back out of the local
    drain. At millisecond resolution such a test could not have pinned the
    ordering anyway, which is the property at stake.
  • The 1xx and 101 behaviour is reasoned and documented, not driven by a
    test.
    It follows from kawa.clear() re-entering the transition; no test
    stages a 100-Continue followed by a final response.
  • doc/lifetime_of_a_session.md lists requests, bytes_in, bytes_out, backend_response_time illustratively and already omits
    backend_connection_time; it is left alone rather than made arbitrarily
    half-complete. The authoritative inventories in doc/configure.md are both
    updated.
  • record_backend_metrics! is #[macro_export], so its arity change is
    technically visible to a downstream sozu-lib consumer 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 the Unreleased / Added
    section.
  • Fifteen file.rs:NNN citations renumbered 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:
    the two fifteen-line production insertions shifted them, and
    check_doc_citations.py --base is 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.

Gate Exit
cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd 0
cargo +nightly fmt --all -- --check 0
cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings 0
cargo test -p sozu-lib … 0 — 1152 passed, 0 failed
cargo test -p sozu … 0 — 113 passed
cargo test -p sozu-command-lib --locked 0 — 171 passed
cargo test -p sozu-e2e … -- --skip tests::fuzz_tests:: 0 — 449 passed, 0 failed
RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked 0 — 30 passed
RUSTFLAGS="--cfg tokio_unstable" cargo clippy -p sozu-sim --all-targets --locked -- -D warnings 0
check_doc_citations.py --self-test 0
check_doc_citations.py --root . 0
check_doc_citations.py --base 747bc3a817a690f00906c69103458e297bd19a2d 0
check_doc_citations.py --audit --root . 0
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked 0

The e2e run was gated on LOAD1 < 8 && CHILD == 0 && PARENT == 0, measured at
LOAD1=2.30 CHILD=0 PARENT=0. Clippy first refused the changeset
(clippy::type_complexity on a six-element test-fixture tuple); that was fixed
by introducing a BackendReadFixture struct on the LedgerFixture pattern
already used in h2.rs, not by an -A or a relaxed gate. No check was
weakened, 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 fn in lib/ or bin/, no socket or
readiness path touched, command/src/command.proto untouched.

Closes #426

Signed-off-by: Florentin Dubois [email protected]

…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
FlorentinDUBOIS merged commit f749155 into main Sep 26, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/backend-header-time branch September 26, 2026 08:20
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.

new request metrics

1 participant