Skip to content

perf(socket): stop reading on a short read instead of reading until EAGAIN #1602

Closed

Description

@FlorentinDUBOIS

Problem

Every read path keeps calling recv(2) until it answers EAGAIN, even when the previous recv already returned fewer bytes than it was offered:

  • tcp_socket_read (lib/src/socket.rs) loops until the buffer is full, EOF or EAGAIN;
  • rustls_socket_read calls read_tls again after a read_tls that returned less than the 4096 bytes rustls offered (rustls-0.23.45/src/msgs/deframer/buffers.rs:208,220).

On a stream socket, a short read already proves the receive queue is empty (man 7 epoll: "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"), so the extra recv can only return EAGAIN.

Measured on a release build (fdtrace interposer, 20 requests, one worker, loopback backend), recv results in the measurement window:

scenario recv total ret>0 EOF EAGAIN
H1 (20 connections) 107 55 10 42
H2 (20 connections) 397 129 11 257
H2 multiplexed (1 connection) 206 65 11 130

Prior art

  • HAProxy stops on a short read and clears the fd's receive readiness: src/raw_sock.c:315-338 (fd_cant_recv when ret < try), and reads read0 directly when FD_POLL_HUP was already seen; the H1 mux also sets CO_RFL_READ_ONCE (src/mux_h1.c:3986-3990).
  • tokio clears read readiness when 0 < n < len (tokio-1.53.1/src/io/poll_evented.rs:211-213), keeping the closed states sticky (src/runtime/io/scheduled_io.rs:357-362).

Proposal

  • Stop reading on a short read and report WouldBlock with the bytes read; a full buffer stays Continue.
  • In rustls, observe the length read_tls asked for and do not call read_tls again in the same pass after a short one.
  • Because mio is edge-triggered (mio-1.2.3/src/sys/unix/selector/epoll.rs:130), a peer FIN coalesced with the data raises no further edge; when HUP was already seen, keep READABLE so the next pass reads the EOF (the close-delimited H1 response path depends on it).

Activity

  1. added a commit that references this issue on Sep 27, 2026
    e73a12e
  2. added a commit that references this issue on Sep 27, 2026
    7c820e5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions