Skip to content

perf(server): reuse the accept(2) peer address and set TCP_NODELAY on the listener - #1593

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
perf/accept-path-syscalls
Sep 26, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
perf/accept-path-syscalls

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Closes #1586

What

Every accepted frontend connection paid three syscalls that carried no new information.

  1. getpeername(2) ×2. accept4(2) returns the peer address, but the three listeners dropped it (.map(|(sock, _)| sock)), then Server::accept and the session constructor each read it back. ProxyConfiguration::accept now returns (TcpStream, SocketAddr), the address rides the accept queue (whose fifth tuple slot was already there and unused), and create_session, HttpSession::new, HttpsSession::new, TcpSession::new and TcpSession::new_sni_preread take it as a parameter.
  2. setsockopt(TCP_NODELAY) ×1. Set on each accepted socket. It is now set once in each listener's activate, 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 pub items in sozu-lib. The repository-wide sweep (git grep -n -E 'create_session\(|ProxyConfiguration|HttpsSession::new\(|HttpSession::new\(|TcpSession::new|accept_queue') found no consumer outside lib/src/{http,https,tcp,server}.rs; bin/, e2e/ and sim/ 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):

$ python3 (listener, connect c1, setsockopt(listener, TCP_NODELAY), connect c2, accept both)
listener 1
queued-before 0 after 1

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_bind socket for connections queued between listen(2) and activate. Each listener therefore carries nodelay_backlog: armed by activate, it makes accept set the flag per connection until the first WouldBlock, 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 = None on an expect-proxy listener until upgrade_expect adopts the header's source; HTTP's upgrade_expect never reads the accept address; TCP's effective_session_address still folds .or(self.frontend_address) over the parsed addresses, with the same value as before. Covered by https::tests::front_rustls_peer_snapshot_is_the_session_peer_not_the_accepted_socket and the 16 proxy_protocol e2e tests, all green.

  • SCM_RIGHTS. Only listeners cross receive_listeners at an upgrade; no accepted TcpStream is ever handed over, and create_session has one caller fed only by the accept queue. server::scm_listener_handoff_tests::inherited_listener_sockets_are_adopted_by_the_initial_activation now also asserts that the connection queued on each inherited HTTP/HTTPS/TCP socket carries TCP_NODELAY and 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 copies TF_NODELAY from the listener into the accepted socket.

    • FreeBSD sys/netinet/tcp_syncache.c:936-937 @ b98d169d1f910e0b28c7ea2f26fcc09f83614ec9
    • XNU (macOS) bsd/netinet/tcp_input.c:2501 @ f6217f891ac0bb64f3d375211650a4c1ff8ca1ea
    • OpenBSD sys/netinet/tcp_input.c:3619 @ 58ef3138855e39db066749e3b8e95b21b7471144
    • NetBSD sys/netinet/tcp_syncache.c:697 @ 60f9ecc654fc8f9e8c857946c295d3ed57b2f8d9

    These copy at handshake completion as Linux does, so the backlog drain covers them too.

Observable values

Unchanged: accept(2) and getpeername(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 with ENOTCONN, the per-source counter skipped the connection and the session started with no peer. Now both get the address accept(2) reported.

Measurement

Release builds of b5169d44 and of this branch, one worker, intentrace -p on the worker, ANSI stripped, counted by syscall name over the window from the first accept4 to the last close, 20 requests with one connection each. LOAD1 was between 6.10 and 7.16 during the passes.

per connection H1 before H1 after H2/TLS before H2/TLS after
getpeername 2.00 0.00 2.00 0.00
setsockopt 2.00 1.00 2.00 1.00
all syscalls 26.95 23.75 62.00 59.05

The remaining setsockopt follows socket/connect: it is the backend socket's, which inherits nothing.

Prior art

HAProxy stores the accept4 address as the connection source (src/sock.c:95, :125 in sock_accept_conn, @ 0ceb8c65fc28b8db060a6a3f96cfc127a3a4b2f6) and sets its listener-scoped options on the listener in tcp_bind_listener (src/proto_tcp.c:662, e.g. :694, :709, :806). It still sets TCP_NODELAY per accepted connection (src/session.c:296), under a FIXME/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 has TCP_NODELAY from the listener alone and is returned with the client's address. It goes red when the listener set_tcp_nodelay is removed.
  • The SCM adoption test above goes red when activate no longer arms nodelay_backlog.
  • The address assertions are equalities, which reverting the patch cannot turn red because the value is the same. They were seen red by injecting a wrong address into the listeners' 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 to doc/configure_admin_ops.md and lib/src/protocol/kawa_h1/LIFECYCLE.md re-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-1161 still says HttpsSession::new seeds peer_address from sock.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]

@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the perf/accept-path-syscalls branch 2 times, most recently from 97881ad to d867b15 Compare September 26, 2026 21:15
… 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
FlorentinDUBOIS force-pushed the perf/accept-path-syscalls branch from d867b15 to 16017bf Compare September 26, 2026 22:08
@FlorentinDUBOIS
FlorentinDUBOIS merged commit 761fab2 into main Sep 26, 2026
23 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/accept-path-syscalls branch September 26, 2026 22:10
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]>
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.

perf(server): drop the redundant getpeername and TCP_NODELAY syscalls on the accept path

1 participant