Repository navigation
perf(server): reuse the accept(2) peer address and set TCP_NODELAY on the listener - #1593
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 26, 2026 20:09
FlorentinDUBOIS
force-pushed
the
perf/accept-path-syscalls
branch
2 times, most recently
from
September 26, 2026 21:15
97881ad to
d867b15
Compare
… the listener Every accepted frontend connection paid three syscalls that carried no new information. accept4(2) already returns the peer address, but the HTTP, HTTPS and TCP listeners dropped it and the worker read it back with getpeername(2) twice: in Server::accept for the per-source counter, and again in the session constructor. ProxyConfiguration::accept now returns the (TcpStream, SocketAddr) pair, the address rides the accept queue, and create_session, HttpSession::new, HttpsSession::new and both TcpSession constructors take it as a parameter. On an expect-proxy listener the session still takes the client address from the PROXY header. Only listeners cross SCM_RIGHTS at an upgrade, so every session is built from a socket this worker accepted. TCP_NODELAY is now set once in each listener's activate, on the freshly bound, SCM-inherited or parked socket, instead of on every accepted socket: Linux, FreeBSD, NetBSD, OpenBSD and macOS copy the flag from the listener when the handshake completes. Connections already queued when the flag is set do not inherit it, which is the backlog of a socket adopted from a binary that never set it, so each listener's accept sets it per connection until its first WouldBlock after an activation. Measured in release with intentrace on the worker, one connection per request: getpeername 2 -> 0 and setsockopt 2 -> 1 per connection, in H1 and in H2 over TLS. Closes #1586 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
perf/accept-path-syscalls
branch
from
September 26, 2026 22:08
d867b15 to
16017bf
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 27, 2026
…AGAIN (#1606) Closes #1602 ## What Every read path kept calling `recv(2)` until EAGAIN, even after a `recv` that returned fewer bytes than it was offered. On a stream socket that short read already proves the receive queue is empty, so the next `recv` could only answer EAGAIN. - `tcp_socket_read` now issues one read per call through a new private `plain_socket_read`, generic over `Read` (like `rustls_socket_read`) so tests count every `recv`. A short read answers `(n, WouldBlock)` — what the old loop answered one EAGAIN later. A read that fills the buffer is **not** a short read and answers `Continue`. The loop disappears, and so does its breaker counter `socket.read.infinite_loop.error` (removed from `names.rs` and `doc/configure.md`; operator-visible, noted in the CHANGELOG). - `rustls_socket_read` wraps the stream in a `ShortReadProbe` that records the length `read_tls` offered (rustls returns only the count, `rustls-0.23.45/src/msgs/deframer/buffers.rs:208,220`). After a short read the pass makes no second `recv`, but still processes and drains what arrived, and still reports a `close_notify` that arrived with it: that `read_tls` returns `Ok(0)` without touching the socket (`rustls-0.23.45/src/conn.rs:768-770`), so it stays allowed. - `update_readiness_after_read` (`lib/src/protocol/mux/mod.rs`) keeps READABLE after a short read once HUP was seen, so the next pass reads the EOF. ## Why it is safe - **A new edge comes for new data.** mio registers every socket with `EPOLLET` (`mio-1.2.3/src/sys/unix/selector/epoll.rs:130`, `EPOLLIN|EPOLLRDHUP` at `:133`). `man 7 epoll` (man-pages 6.13): edge-triggered mode "delivers events only when changes occur on the monitored file descriptor, that is, an event will be generated upon each receipt of a chunk of data", and in the EPOLLET Q&A: "For stream-oriented files (e.g., pipe, FIFO, stream socket) ... if you call read(2) by asking to read a certain amount of data and read(2) returns a lower number of bytes, you can be sure of having exhausted the read I/O space for the file descriptor." `after_a_short_read_new_bytes_raise_a_new_edge` checks this on a real loopback socket registered with mio: short read, no pending event, new bytes raise a new READABLE event, and so does the FIN. - **HUP already seen → read until EOF.** A FIN coalesced with the data raised its edge already; sozu folds it into `Ready::HUP` (`command/src/ready.rs`, `From<&mio::event::Event>`), merged with `|=` (`Mux::update_readiness`). No later event will announce the EOF, hence the exception in `update_readiness_after_read`. It cannot spin: the next read either returns bytes or `size == 0`, which drops READABLE (pinned by `a_short_read_after_hup_keeps_readable_to_read_the_eof`, `a_short_read_without_hup_drops_readable`, `an_empty_read_after_hup_still_drops_readable`). Same rule as HAProxy (`src/raw_sock.c`: `fd_cant_recv` when `ret < try`, then `goto read0` if `FD_POLL_HUP`) and tokio (`clear_readiness` when `0 < n < len`, `tokio-1.53.1/src/io/poll_evented.rs:211-213`, keeping closed states, `src/runtime/io/scheduled_io.rs:357-362`). A short read drains every byte before the FIN, so no data is ever left behind; only the EOF observation moves to the next pass. - **Other callers.** They already handled `(n > 0, WouldBlock)` (it is what read-then-EAGAIN produced). The pipe records HUP in `ConnectionStatus` independently of any EOF read (`Pipe::frontend_hup`, `Pipe::backend_hup`), and closes through `check_connections` once flushed; `ExpectProxyProtocol`, the TLS handshake and the TCP preread close on HUP. Two comments (`pipe.rs`, `tcp.rs`) that said the tail was read "to EOF" are adjusted. - **A full buffer is not a short read**: `a_full_plain_buffer_is_not_a_short_read`, `a_plain_body_ending_on_a_full_buffer_still_needs_its_eagain`. ## Honest limits - **TCP urgent data (OOB).** The "a short read empties the queue" guarantee does not hold while a TCP urgent mark is queued: `recv` stops before the mark with bytes behind it. Reproduced on a real socket: `AAAA`, `send(B, MSG_OOB)`, `CCCC` raise one edge; `tcp_socket_read` answers `(4, WouldBlock)` with `AAAA`, no event follows for 300 ms, and `CCCC` stays in the kernel. A stream carrying OOB data (telnet, rlogin, FTP `ABOR`) can stall until the peer's next send. HAProxy and tokio behave the same, and sozu never read OOB data before either. Documented in the `plain_socket_read` doc-comment, `doc/lifetime_of_a_session.md` §2.2 and the CHANGELOG. - The three e2e close-delimited tests (`test_h1_close_delimited_response_fully_delivered`, `test_h2_close_delimited_large_response`, `test_h2_large_h1_response_close_delimited`) pass **with and without** the HUP exception — I removed it and ran them: 3 passed. They do not discriminate it (the FIN most likely arrives in a separate event there). The exception is pinned instead by `data_and_fin_in_one_edge_keep_readable_until_the_eof_is_read`: on a real loopback socket registered with mio, data and FIN share ONE `(readable, read_closed)` edge, the short read answers `(4, WouldBlock)`, no event follows, READABLE survives `update_readiness_after_read`, and the next read answers `(0, Closed)`. It fails with the exception removed ("HUP was seen: READABLE must stay so the EOF is read") and passes with it. - A pass does not remember a short read made by an earlier call, on purpose: an edge may have arrived in between and already been folded into the READABLE the mux kept. So the EAGAIN after a call whose buffer filled from the last short read's plaintext remains (`a_large_body_over_tls_arrives_intact` pins exactly 1). That is where most of the remaining H2 EAGAINs come from. ## Tests Red then green: with the fix reverted (loop restored in `plain_socket_read`, probe ignored in rustls, HUP exception removed), 9 of the 27 targeted tests fail; with it, all pass. `close_notify_in_the_short_read_is_reported_in_the_same_call` fails on the naive variant that skips every `read_tls` after a short read. New plain-path tests: short read (1 recv, 0 EAGAIN), full buffer, FIN behind a short read, fragmented message, 1 MiB body (65 reads, 0 EAGAIN). New rustls tests: `close_notify` in the short read, FIN behind a short read, 64 KiB body. Two existing rustls tests encode the old count and are updated to the lower one (`a_large_buffer_drains_the_record_in_one_short_recv`: 2 → 1 reads; `a_fragmented_record_is_read_again_until_it_completes`: 2 → 1 and 3 → 2). ## Trade with #1603 (rebased on main `13269c5e`) #1603/#1605 closed an H1 backend in the same pass when its last bytes and EOF came back from one `recv`. With a short read that `recv` is no longer issued, so: - FIN in the kernel **before** `epoll_wait` returned: the edge carries HUP, the backend is still closed **in the same pass**; - FIN landing **after** `epoll_wait` returned (READABLE without HUP): the backend is closed **one `epoll_wait` round later**, on the `EPOLLRDHUP` edge the FIN queued — and no later: that edge is already pending when the pass ends. That is HAProxy's choice (`src/raw_sock.c:315-338`: stop on `ret < try`, let the poller report the EOF). The saved `recv` answers EAGAIN on every short read not followed by a FIN. Documented in the CHANGELOG, `doc/lifetime_of_a_session.md` §2.2 and the `ConnectionH1::readable` comment. **The #1605 tests were rewritten, not removed or weakened** (commit `206a47b1`, each referencing #1606 and HAProxy): - `an_h1_backend_eof_read_records_hup_and_a_frontend_one_does_not` keeps every assertion; the EOF is now met by the second `readable`, which records HUP on the backend and not on the frontend. Red when the HUP insertion in `h1.rs` is removed. - `a_backend_eof_read_with_its_last_bytes_closes_the_backend_in_the_same_pass` covers the coalesced edge (READABLE|HUP), closed in the same pass. Red when `is_hup()` is dropped from `dead`. - new `a_fin_after_epoll_wait_closes_the_backend_on_the_next_round_at_the_latest`, real loopback socket + mio: not closed in the first pass, RDHUP edge returned by a zero-timeout poll, closed on that round. Note: the two intermediate commits of this branch do not pass those two #1605 tests; the branch head does. Squash-merge keeps `main` bisectable. ## Measurement Release builds of main `13269c5e` (with #1605) and this branch, one worker, loopback, python backend that closes after each response (the #1605 scenario), 20 requests per scenario, LOAD1 < 2. Syscalls per request: | scenario | tool | total | `recv`/`recvfrom` | EAGAIN (run) | `epoll_wait` | |---|---|---|---|---|---| | H1 | fdtrace | 20.35 → 18.65 | 4.45 → 2.30 | 31 → 0 | 5.60 → 5.95 | | H1 | intentrace | 20.65 → 18.85 | 4.00 → 2.00 | n/a | 4.55 → 4.75 | | H2 | fdtrace | 35.25 → 34.35 | 10.70 → 9.45 | 88 → 68 | 8.45 → 8.65 | | H2 | intentrace | 42.10 → 41.05 | 6.00 → 5.00 | n/a | 4.95 → 4.90 | | H2 mux (1 conn) | fdtrace | 15.95 → 14.70 | 5.35 → 4.00 | 34 → 23 | 3.90 → 4.05 | | H2 mux (1 conn) | intentrace | 16.45 → 15.45 | 4.10 → 3.10 | n/a | 3.10 → 3.10 | The total drops in every scenario; `epoll_wait` rises slightly in H1 (the extra round above). `intentrace` does not decode `recvfrom` results, so the EAGAIN split comes from `fdtrace`. The first measurement against `f165a3dc` (before #1605): H1 recv 114 → 58, H2 236 → 171, multiplexed 136 → 84. ## Also - The `FrontRustls::peer_addr` comment still described `HttpsSession::new` seeding the peer with `sock.peer_addr().ok()`; since #1593 it uses the address `accept(2)` returned. Corrected. - `doc/lifetime_of_a_session.md` §2.2 and `doc/h2_mux_internals.md` describe the short-read stop; the mux `LIFECYCLE.md` and `doc/testing.md` citations shifted by the new lines in `mux/mod.rs` are re-anchored to the same text. 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.
Closes #1586
What
Every accepted frontend connection paid three syscalls that carried no new information.
getpeername(2)×2.accept4(2)returns the peer address, but the three listeners dropped it (.map(|(sock, _)| sock)), thenServer::acceptand the session constructor each read it back.ProxyConfiguration::acceptnow returns(TcpStream, SocketAddr), the address rides the accept queue (whose fifth tuple slot was already there and unused), andcreate_session,HttpSession::new,HttpsSession::new,TcpSession::newandTcpSession::new_sni_prereadtake it as a parameter.setsockopt(TCP_NODELAY)×1. Set on each accepted socket. It is now set once in each listener'sactivate, on whichever socket it activates (fresh bind, SCM_RIGHTS inheritance, parked after a failed registration), and the kernel copies it to accepted sockets.The signature changes are all
pubitems insozu-lib. The repository-wide sweep (git grep -n -E 'create_session\(|ProxyConfiguration|HttpsSession::new\(|HttpSession::new\(|TcpSession::new|accept_queue') found no consumer outsidelib/src/{http,https,tcp,server}.rs;bin/,e2e/andsim/only name them in comments.Why the per-connection flag survives for the backlog
The flag is copied when the handshake completes, not at
accept(2):So a worker that adopts the listener of a binary that never set the flag would accept its queued backlog without it, and so would a fresh
server_bindsocket for connections queued betweenlisten(2)andactivate. Each listener therefore carriesnodelay_backlog: armed byactivate, it makesacceptset the flag per connection until the firstWouldBlock, which is exactly the backlog present at activation. In steady state it costs nothing.server_bind(lib/src/socket.rs) is deliberately left unchanged.Cases that needed proof
PROXY protocol. HTTPS keeps
peer_address = Noneon an expect-proxy listener untilupgrade_expectadopts the header's source; HTTP'supgrade_expectnever reads the accept address; TCP'seffective_session_addressstill folds.or(self.frontend_address)over the parsed addresses, with the same value as before. Covered byhttps::tests::front_rustls_peer_snapshot_is_the_session_peer_not_the_accepted_socketand the 16proxy_protocole2e tests, all green.SCM_RIGHTS. Only listeners cross
receive_listenersat an upgrade; no acceptedTcpStreamis ever handed over, andcreate_sessionhas one caller fed only by the accept queue.server::scm_listener_handoff_tests::inherited_listener_sockets_are_adopted_by_the_initial_activationnow also asserts that the connection queued on each inherited HTTP/HTTPS/TCP socket carriesTCP_NODELAYand is queued with the client's address.systemd socket activation. None in the tree (
git grep -n -i -E 'LISTEN_FDS|sd_listen'is empty).Other platforms. No
cfg: each BSD kernel copiesTF_NODELAYfrom the listener into the accepted socket.sys/netinet/tcp_syncache.c:936-937@b98d169d1f910e0b28c7ea2f26fcc09f83614ec9bsd/netinet/tcp_input.c:2501@f6217f891ac0bb64f3d375211650a4c1ff8ca1easys/netinet/tcp_input.c:3619@58ef3138855e39db066749e3b8e95b21b7471144sys/netinet/tcp_syncache.c:697@60f9ecc654fc8f9e8c857946c295d3ed57b2f8d9These copy at handshake completion as Linux does, so the backlog drain covers them too.
Observable values
Unchanged:
accept(2)andgetpeername(2)return the same address for a socket. The one difference is a peer that resets between the accept and the lookup. Before,getpeername(2)failed withENOTCONN, the per-source counter skipped the connection and the session started with no peer. Now both get the addressaccept(2)reported.Measurement
Release builds of
b5169d44and of this branch, one worker,intentrace -pon the worker, ANSI stripped, counted by syscall name over the window from the firstaccept4to the lastclose, 20 requests with one connection each. LOAD1 was between 6.10 and 7.16 during the passes.getpeernamesetsockoptThe remaining
setsockoptfollowssocket/connect: it is the backend socket's, which inherits nothing.Prior art
HAProxy stores the
accept4address as the connection source (src/sock.c:95,:125insock_accept_conn, @0ceb8c65fc28b8db060a6a3f96cfc127a3a4b2f6) and sets its listener-scoped options on the listener intcp_bind_listener(src/proto_tcp.c:662, e.g.:694,:709,:806). It still setsTCP_NODELAYper accepted connection (src/session.c:296), under aFIXME/WTA(:288-290) that says these calls belong at the protocol level.Tests
http::tests::a_steady_state_accepted_socket_inherits_nodelay_and_its_peer_address: after the first drain, a new connection hasTCP_NODELAYfrom the listener alone and is returned with the client's address. It goes red when the listenerset_tcp_nodelayis removed.activateno longer armsnodelay_backlog.accept.Docs
doc/lifetime_of_a_session.md§3.1–3.2,doc/benchmark.md(strace walkthrough),doc/rate-limit-design.md,CHANGELOG.md. The one-line changes todoc/configure_admin_ops.mdandlib/src/protocol/kawa_h1/LIFECYCLE.mdre-anchor citations that moved: same line text, same functions (check_doc_citations.py --base b5169d44…is green).Out of scope: the doc comment at
lib/src/socket.rs:1159-1161still saysHttpsSession::newseedspeer_addressfromsock.peer_addr().ok(). It is left for a follow-up because another change is in flight in that file.Signed-off-by: Florentin Dubois [email protected]