Skip to content

perf(tcp): drop the per-session getpeername and EPOLL_CTL_DEL - #1657

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
perf/tcp-backend-address
Sep 28, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
perf/tcp-backend-address

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator

A raw TCP session paid one getpeername(2) per session for the access log's backend address, although Sōzu chose that address itself, and two EPOLL_CTL_DEL on close, each right before the socket's last close(2), which removes it from the epoll set anyway. This PR removes all three: 36.10–36.25 → 33.05–33.10 syscalls per session.

Measured

Release worker (--no-default-features --features crypto-ring,opentelemetry,splice,simd), worker_count = 1, one TCP listener to a python3 -m http.server backend, N=20 sequential curl sessions (one connection each), two passes per instrument. Same config and scenario on both sides; only the binary differs (f5136d67 vs this branch). LOAD1 3.35–4.09 on every pass; 20/20 responses 200 on every pass.

per session before (f5136d67) after
total, intentrace -p (aligned window, first accept4 to last close) 36.25 / 36.10 33.10 / 33.05
total, LD_PRELOAD descriptor tracer 38.30 / 37.30 33.85 / 34.35
getpeername 1.00 0
epoll_ctl 4.00 (40 ADD + 40 DEL) 2.00 (40 ADD)
accept4 ×2, socket, connect, setsockopt, pipe2 ×2, fcntl ×4, shutdown ×2 (how=2), getsockopt ×2, close ×6 unchanged
splice, epoll_wait 6.10–8.20, 3.95–4.10 6.05–7.20, 3.95–4.10 (timing noise)

Per-session sequence before: accept4 ×2, epoll_ctl ADD, pipe2 ×2, fcntl ×4, epoll_wait, socket, connect, setsockopt, epoll_ctl ADD, epoll_wait, splice…, getpeername (backend fd, same inode as the connect), getsockopt ×2, shutdown(front), epoll_ctl DEL ×2, shutdown(back), close ×6. After: the same without the three bold calls.

Leak check: the worker holds 14 descriptors before and after 1000 further sessions, on both binaries, 1000/1000 answered 200. The access log's backend address reads 127.0.0.1:45080 on both.

Method: the descriptor tracer is the campaign's fdtrace.so, extended with getpeername/getsockname/getsockopt/setsockopt and self-tested on a C program issuing exactly 3 getpeername. The two instruments agree on every deterministic family.

getpeername

Pipe::get_backend_address was the only caller of peer_addr() on the backend socket, used only by Pipe::log_request (access log). It now returns a backend_address field recorded when the backend was chosen:

  • WebSocket upgrades (HttpSession::upgrade_mux, HttpsSession::upgrade_mux): Pipe::new takes it from the Backend those paths already pass.
  • Raw TCP: TcpSession::connect_to_backend records the dialed backend.address and hands it to the Pipe through Pipe::set_backend_address, directly when the state is already Pipe, or at each upgrade to Pipe (upgrade_send, upgrade_relay, upgrade_expect, build_pipe_from_preread). A retry after a failed connect dials again and overwrites the address, so the log reports the backend actually retried.

Value: for a connected backend, identical (getpeername returns the address connect was given). The one difference: a backend still connecting (SYN_SENT) or already reset (CLOSE) made getpeername fail with ENOTCONN, and the log showed no address. It now shows the dialed address, which is what the HTTP mux already logs (Router, context.backend_address = Some(dialed.backend.address)). No caller needs the kernel's view of a connected peer. TcpSession::backend stays None as before (populating it would change dec_connections accounting).

Close: EPOLL_CTL_DEL removed, shutdown(Shutdown::Both) kept

TcpSession::close (front) and TcpSession::close_backend (back) no longer deregister, as #1567 did for HTTP/HTTPS (#1568 deliberately left TCP untouched).

  • Peer-visible behaviour is identical. A deregister is local to the epoll instance. The shutdown(2) calls (both Shutdown::Both, both kept), their order, the close(2) calls and the socket options (no SO_LINGER is set) are unchanged, so FIN, RST on unread data and bytes in flight are unchanged. The trace confirms: same two shutdown how=2, same six close, same order.
  • Each socket's last close precedes the next epoll_wait. From close(): shut_down_sessions_by_frontend_tokens is the only caller and drops the session in the same pass. From the connect retry in TcpSession::ready_inner: connect_to_backend either succeeds and set_back_socket drops the old socket immediately (every state's set_back_socket is a plain assignment), or fails, and handle_connection_result maps every Err to SessionResult::Close, which kills the session in the same pass. So a freed slab token cannot receive a stale event.
  • No duplicate. No dup/try_clone of a session socket, no worker fork, SCM_RIGHTS carries listeners only; mio 1.x keeps no per-source state that a deregister would release (same argument as perf(mux): leave closing session sockets to close(2), not EPOLL_CTL_DEL #1568).

Tests (each seen red, then green)

  • protocol::pipe::tests::backend_address_is_reported_without_asking_the_socket: a Pipe whose backend socket was refused (nothing listens on its port; on loopback it is reset before the assertion) must still report the backend's address, then the address a later set_backend_address gives. Red with get_backend_address restored to peer_addr(): left: None, right: Some(127.0.0.1:43841).
  • tcp::…::a_dialed_pipe_reports_the_backend_address_it_was_given: an expect-proxy session, once its header is parsed and its backend dialed, reports the dialed address. Red without the set_backend_address call in connect_to_backend: left: None, right: Some(127.0.0.1:33845).
  • tcp::…::a_send_proxy_protocol_pipe_reports_the_dialed_backend_address, …::a_relay_proxy_protocol_pipe_reports_the_dialed_backend_address, …::an_sni_preread_pipe_reports_the_dialed_backend_address: the three paths that dial before the Pipe exists (send, relay, SNI preread), each upgraded through TcpSession::upgrade and checked on Pipe::get_backend_address (the access-log value). Added after the adversarial review found two surviving mutations, because the expect test dials from the Pipe and masks the upgrade hand-over:
    • A1, TcpSession::set_backend_address records nothing: all three red (and the expect test), left: None, right: Some(127.0.0.1:…).
    • A2, the upgrades copy None: all three red; applied per site, upgrade_send reds only the send test, upgrade_relay only the relay test, build_pipe_from_preread only the preread test.
    • Green once restored.
  • tcp::…::closed_tcp_sessions_leave_their_sockets_to_close: reads the kernel's epoll table from /proc/self/fdinfo; after close() both sockets are still watched (no DEL), after the session drops both are gone (the close removed them, no leak). Red with the front deregister put back ("TcpSession::close must not deregister a front socket…"), and separately with the backend one put back ("TcpSession::close_backend must not deregister a backend socket…").

Docs

  • doc/lifetime_of_a_session.md: §9 (TCP lifecycle) documents the backend address and adds the perf(tcp): drop the per-session getpeername and EPOLL_CTL_DEL #1657 columns to its per-connection table; §11 extends the no-deregister argument to TCP (including the retry path).
  • doc/hot_path_zero_copy.md: §3.10 entry and a note under the §2.3 closing table.
  • doc/rate-limit-design.md: five lib/src/tcp.rs:NNN citations shifted by this change are replaced with symbols.
  • CHANGELOG.md: entry under Changed.

Rebased on #1656 (b3f2c787), code unchanged (patch-id outside *.md/CHANGELOG.md identical to the first push a1da6095). The TCP table #1656 added to doc/lifetime_of_a_session.md §9 gains #1657 before/after columns next to the untouched closing-measurement column, §11 gains the TCP close paragraph, and doc/hot_path_zero_copy.md gains a §3.10 entry and a note under the §2.3 closing table (its figures unchanged). No conflict with the UDP udp_connect work.

Out of scope, recorded for the campaign: SplicePipe::new per session costs pipe2 ×2 + fcntl ×4 + close ×4 = 10 syscalls (≈30 % of what remains).

Commands run (all exit 0)

  • cargo +nightly fmt --all -- --check
  • 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 test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8: sozu-lib 1333 passed after the three path tests (1330 before), e2e 490 passed (215 TCP/proxy-protocol tests among them, 0 failed), no failure anywhere
  • python3 .github/scripts/check_doc_citations.py --self-test, --root ., --root . --base origin/main, --audit --root .
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked

No protocol, wire, config or metric change. The only log change is the backend address now present on a not-yet-connected or reset backend, and the removed error! for a failed deregister.

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

A raw TCP session paid one getpeername(2) per session for the access
log's backend address, although Sōzu chose that address itself, and
two EPOLL_CTL_DEL on close, one per socket, right before the last
close(2) that removes the socket from the epoll set anyway.

Pipe::get_backend_address now returns the address recorded when the
backend was chosen: Pipe::new takes it from the Backend a WebSocket
upgrade hands over, and TcpSession::connect_to_backend passes the
address it dials through Pipe::set_backend_address, directly or at
each upgrade to Pipe, so a retry onto another backend reports the new
one. For a connected backend the logged address is unchanged; a
backend still connecting or already reset, where getpeername(2)
failed with ENOTCONN and the log showed none, now logs the dialed
address, as the HTTP mux already does.

TcpSession::close and TcpSession::close_backend no longer deregister,
as #1567 did for HTTP and HTTPS. Each socket's last close still comes
before the next epoll_wait: the server drops the session right after
close(), and on a connect retry connect_to_backend either replaces the
old socket in the same pass or fails, and every failure closes the
session. No session socket is duplicated. Both shutdown(Shutdown::Both)
calls, their order and the socket options are unchanged, so the peer
sees the same FIN, RST and bytes in flight.

Measured on a release worker (crypto-ring,opentelemetry,splice,simd)
behind python3 -m http.server, 20 sequential curl sessions through a
TCP listener, two passes per instrument, same config on both sides:
intentrace -p 36.10-36.25 -> 33.05-33.10 syscalls per session, an
LD_PRELOAD descriptor tracer 37.30-38.30 -> 33.85-34.35; getpeername
1 -> 0, epoll_ctl 4 -> 2 (40 ADD + 40 DEL -> 40 ADD), every other
count unchanged. The worker holds 14 descriptors before and after 1000
further sessions.

Tests: backend_address_is_reported_without_asking_the_socket
(pipe.rs, a refused backend socket whose address must still be
reported); in tcp.rs, one test per path that hands the dialed address
to the Pipe: a_dialed_pipe_reports_the_backend_address_it_was_given
(expect, dialed from the Pipe),
a_send_proxy_protocol_pipe_reports_the_dialed_backend_address,
a_relay_proxy_protocol_pipe_reports_the_dialed_backend_address and
an_sni_preread_pipe_reports_the_dialed_backend_address (dialed before
the upgrade); and closed_tcp_sessions_leave_their_sockets_to_close,
reading the kernel's epoll table from /proc/self/fdinfo. Each was seen
red with its part of the change reverted.

doc/lifetime_of_a_session.md documents the address and the close in
the TCP lifecycle (with the per-connection table next to the closing
measurement) and in the close section; doc/hot_path_zero_copy.md adds
the change to its accept-and-close section with its own before/after
figures, leaving the closing measurement as measured;
doc/rate-limit-design.md trades five drifted tcp.rs line citations for
symbols.

Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 34d5e71 into main Sep 28, 2026
11 of 23 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/tcp-backend-address branch September 28, 2026 15:29
FlorentinDUBOIS added a commit that referenced this pull request Sep 28, 2026
…ed (#1661)

Closes #1658

## CAUSE

`TcpSession::connect_to_backend` (`lib/src/tcp.rs`) receives the selected `Rc<RefCell<Backend>>` from `BackendMap::backend_from_cluster_id`, copies its `backend_id` and drops it, so `TcpSession::backend` stays `None` → `TcpSession::fail_backend_connection` (HUP on a connecting socket in `TcpSession::ready_inner`, i.e. a non-blocking connect refused after `EINPROGRESS`), `TcpSession::set_back_connected` and `TcpSession::remove_backend` all skip their `if let Some(backend) = self.backend` body → SYMPTOM: a refusing TCP backend never has `failures` bumped nor its `retry_policy` armed, stays in round-robin selection, is never marked down, `backend.connections.error` / `backend.down` / `backend.up` / `backend.available` are never emitted for TCP, and `Backend::active_connections` (incremented by `Backend::try_connect`) is never decremented.

The mux keeps its handle in its `BackendRegistry` and charges the same failure in `Mux::ready`.

## Fix

One line in `TcpSession::connect_to_backend`: `self.backend = Some(Rc::clone(&backend));`. The existing accounting then runs as written.

Per-backend byte counters and `connections_per_backend` do not change value: they are keyed by `metrics.backend_id`, which was already set. What changes: `backend.connections.error` (and on down/up transitions `backend.down`, `backend.up`, `backend.available`, `BackendDown`/`BackendUp`) are now emitted for TCP backends; `Backend::active_connections` is released on close; the PeakEWMA connection time is fed; and, from reading `impl Drop for Backend`, a removed TCP backend's `RemovedBackendHasNoConnections` now waits for its last session (not covered by a test).

## Reproduction, red then green

`test_tcp_refused_backend_is_accounted_and_avoided` (`e2e/src/tests/tcp_tests.rs`): two backends, the first on a closed port, sixteen sequential sessions, all served in both cases.

The avoidance bound comes from the retry policy, not from timing. `ExponentialBackoffPolicy::fail` arms at least one second of back-off per recorded failure, and a backend in back-off fails `Backend::can_open` (no fail-open while the live backend is a candidate), so over the measured duration of the sessions the refused backend can be dialed at most `1 + floor(elapsed)` times. Without the accounting, round-robin over the constant pair makes every session but possibly the first dial the refused backend, at least `SESSIONS - 1 = 15` times. The test requires `errors <= 1 + floor(elapsed)` and that bound to be strictly below 15.

- Rebased tree with the fix line removed: `backend.connections.error = None, sessions took 21.5ms, back-off allows at most 1, round-robin without it makes at least 15`, `test result: FAILED. 0 passed; 1 failed`. With `RUST_LOG=debug`: the refused backend dialed 16 times for 16 sessions.
- With the fix: `Some(1)` in each iteration, `test result: ok. 1 passed`; 10 runs out of 10 green (7 idle, 3 with 40 busy `yes` loops on 20 cores, load average 37-48, sessions took 12-200 ms, count always 1).

## Validation (all exit 0, on the tree rebased onto `origin/main` 34d5e71, after #1657)

- `cargo +nightly fmt --all -- --check`
- `cargo build --locked`
- `cargo build --all-features --locked` with `CC=clang CXX=clang++ ASM=clang AR=llvm-ar RANLIB=llvm-ranlib` (aws-lc-fips-sys fails with gcc on this host; its stale CMake cache was cleared with `cargo clean -p aws-lc-fips-sys`)
- `cargo clippy --all-targets --locked -- -D warnings`
- `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings`
- `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8` (e2e: 491 passed; lib: 1334 passed)
- e2e suites by name: `tcp_tests` 10 passed, `tcp_sni_tests` 19 passed, `proxy_protocol_local_tests` 2 passed, `protocol_pair_matrix` 24 passed
- `python3 .github/scripts/check_doc_citations.py --self-test`, `--root .`, `--root . --base origin/main`, `--audit --root .`
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked`

Signed-off-by: Florentin Dubois <[email protected]>
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.

1 participant