Repository navigation
perf(tcp): drop the per-session getpeername and EPOLL_CTL_DEL - #1657
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 28, 2026 13:25
FlorentinDUBOIS
force-pushed
the
perf/tcp-backend-address
branch
from
September 28, 2026 13:59
a1da609 to
546bf14
Compare
FlorentinDUBOIS
force-pushed
the
perf/tcp-backend-address
branch
from
September 28, 2026 14:22
546bf14 to
668a897
Compare
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
force-pushed
the
perf/tcp-backend-address
branch
from
September 28, 2026 15:23
668a897 to
bb793d2
Compare
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]>
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.
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 twoEPOLL_CTL_DELon close, each right before the socket's lastclose(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 apython3 -m http.serverbackend, N=20 sequentialcurlsessions (one connection each), two passes per instrument. Same config and scenario on both sides; only the binary differs (f5136d67vs this branch). LOAD1 3.35–4.09 on every pass; 20/20 responses 200 on every pass.f5136d67)intentrace -p(aligned window, firstaccept4to lastclose)LD_PRELOADdescriptor tracergetpeernameepoll_ctlaccept4×2,socket,connect,setsockopt,pipe2×2,fcntl×4,shutdown×2 (how=2),getsockopt×2,close×6splice,epoll_waitPer-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 theconnect),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:45080on both.Method: the descriptor tracer is the campaign's
fdtrace.so, extended withgetpeername/getsockname/getsockopt/setsockoptand self-tested on a C program issuing exactly 3getpeername. The two instruments agree on every deterministic family.getpeernamePipe::get_backend_addresswas the only caller ofpeer_addr()on the backend socket, used only byPipe::log_request(access log). It now returns abackend_addressfield recorded when the backend was chosen:HttpSession::upgrade_mux,HttpsSession::upgrade_mux):Pipe::newtakes it from theBackendthose paths already pass.TcpSession::connect_to_backendrecords the dialedbackend.addressand hands it to thePipethroughPipe::set_backend_address, directly when the state is alreadyPipe, or at each upgrade toPipe(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 (
getpeernamereturns the addressconnectwas given). The one difference: a backend still connecting (SYN_SENT) or already reset (CLOSE) madegetpeernamefail withENOTCONN, 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::backendstaysNoneas before (populating it would changedec_connectionsaccounting).Close:
EPOLL_CTL_DELremoved,shutdown(Shutdown::Both)keptTcpSession::close(front) andTcpSession::close_backend(back) no longer deregister, as #1567 did for HTTP/HTTPS (#1568 deliberately left TCP untouched).shutdown(2)calls (bothShutdown::Both, both kept), their order, theclose(2)calls and the socket options (noSO_LINGERis set) are unchanged, so FIN, RST on unread data and bytes in flight are unchanged. The trace confirms: same twoshutdown how=2, same sixclose, same order.epoll_wait. Fromclose():shut_down_sessions_by_frontend_tokensis the only caller and drops the session in the same pass. From the connect retry inTcpSession::ready_inner:connect_to_backendeither succeeds andset_back_socketdrops the old socket immediately (every state'sset_back_socketis a plain assignment), or fails, andhandle_connection_resultmaps everyErrtoSessionResult::Close, which kills the session in the same pass. So a freed slab token cannot receive a stale event.dup/try_cloneof 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: aPipewhose 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 laterset_backend_addressgives. Red withget_backend_addressrestored topeer_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 theset_backend_addresscall inconnect_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 thePipeexists (send, relay, SNI preread), each upgraded throughTcpSession::upgradeand checked onPipe::get_backend_address(the access-log value). Added after the adversarial review found two surviving mutations, because the expect test dials from thePipeand masks the upgrade hand-over:TcpSession::set_backend_addressrecords nothing: all three red (and the expect test),left: None, right: Some(127.0.0.1:…).None: all three red; applied per site,upgrade_sendreds only the send test,upgrade_relayonly the relay test,build_pipe_from_prereadonly the preread test.tcp::…::closed_tcp_sessions_leave_their_sockets_to_close: reads the kernel's epoll table from/proc/self/fdinfo; afterclose()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: fivelib/src/tcp.rs:NNNcitations shifted by this change are replaced with symbols.CHANGELOG.md: entry under Changed.Rebased on #1656 (
b3f2c787), code unchanged (patch-id outside*.md/CHANGELOG.mdidentical to the first pusha1da6095). The TCP table #1656 added todoc/lifetime_of_a_session.md§9 gains #1657 before/after columns next to the untouched closing-measurement column, §11 gains the TCP close paragraph, anddoc/hot_path_zero_copy.mdgains a §3.10 entry and a note under the §2.3 closing table (its figures unchanged). No conflict with the UDPudp_connectwork.Out of scope, recorded for the campaign:
SplicePipe::newper session costspipe2×2 +fcntl×4 +close×4 = 10 syscalls (≈30 % of what remains).Commands run (all exit 0)
cargo +nightly fmt --all -- --checkcargo build --lockedcargo build --all-features --lockedcargo clippy --all-targets --locked -- -D warningscargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warningscargo 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 anywherepython3 .github/scripts/check_doc_citations.py --self-test,--root .,--root . --base origin/main,--audit --root .RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedNo 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]