Skip to content

http3: expire_datagram_queues scans all pending requests on every packet #4373

Open

Description

@larseggert

Related: #4003, #4091
Code has moved since f53c12bc; still present at e09257ab neqo-http3/src/connection.rs:1734.
See also: #4371, #4374

Since v0.33.0, an Http3Client spends CPU time on every received packet in proportion to the number of its requests still waiting for a response, even when WebTransport and connect-udp are disabled. With 20,000 unanswered requests on one connection, a small packet costs the client about 235 µs in process_input() plus process_output() (release build). About 170 µs of that comes from this bug. The remaining ~65 µs is the transport's own per-stream work, which also shows up once GOAWAY has emptied the HTTP/3 stream table. At the usual tens or hundreds of concurrent requests the extra cost is under a microsecond per packet. It becomes visible with thousands of pending requests and lasts only until they are answered, cancelled or the connection closes, with no crash, hang or memory growth.

The cause is that Http3Connection::expire_datagram_queues() (neqo-http3/src/connection.rs:1748) finds extended CONNECT sessions by walking the whole recv_streams table, making one dynamic extended_connect_session() call per entry. For an ordinary request that call just returns None. Http3Client::process_http3() (connection_client.rs:757) calls it unconditionally, once per process_input() and twice per process_output(), so each packet costs about 8.5 ns extra per pending request. Both the function and the calls were added in 9d7e35ba607f ("WebTransport datagram queue initial version (#4003)"); v0.32.0 is not affected. Http3ServerHandler::process_http3() makes the same call, but there the table is bounded by the server's own max_streams. The attached reproducer times a default client against a server that grants 100,000 streams and never answers. It compares 20,000 pending requests with the same QUIC streams after a GOAWAY and finds the pending case about 3.7x slower. The attached patch keeps a separate session map in Http3Connection so that this walk and its two sibling walks are O(sessions), which brings that ratio back to 1.0x.

Related upstream, but it does not cover this: pull request #4091 (merged, 2026-10-17), "WebTransport: report the fate of outgoing datagrams via aggregate stats"
#4091
PR 4091 rewrote the body of expire_datagram_queues() and says the per-tick sweep is limited to sessions
with work, but its diff still iterates self.recv_streams.values() and calls extended_connect_session()
on every receive stream. That code is already present at f53c12b, so the per-pending-request cost the
finding measures is left open.

This is an ordinary performance bug, not a security issue: the pending requests it depends on can
only be created by the application, not by the server, and the result is a bounded, linear
slowdown that ends when those requests go away, with no crash, hang or memory growth.

Details

Http3Connection::expire_datagram_queues() looks for extended CONNECT sessions by iterating over the
whole recv_streams table, and Http3Client calls it once in every process_input() and twice in
every process_output(). The CPU time a client spends on one received packet therefore grows
linearly with the number of requests that are waiting for a response, also on a client that has
WebTransport and connect-udp switched off and can never have a session.

neqo-http3/src/connection.rs:1748:

pub(crate) fn expire_datagram_queues(&self, conn: &mut Connection, now: Instant) -> u64 {
    self.recv_streams
        .values()
        .filter_map(|s| s.extended_connect_session())   // one dynamic call per receive stream
        .filter(|s| s.borrow().is_active())
        .map(|s| { … })
        .sum()
}

Measured at commit f53c12bcebff22c899adfa75a5ff73ca5c1d64ba, release profile: a default
Http3Client has N GET requests outstanding (sent in full, not answered), and the server then
sends 2000 packets of 32 to 43 bytes, each with one byte of stream data. The time is
what process_input() plus process_output() take per packet, in a typical run; the two 20,000
rows vary by up to 40 µs between runs, their difference by much less.

requests pending client time per packet with the attached patch
0 3.5 µs 3.5 µs
2,000 23 µs 6.4 µs
20,000 235 µs 63–66 µs
20,000, all rejected by a GOAWAY 65 µs 67 µs

In the last row the QUIC layer still has the 20,000 streams and only the HTTP/3 table has lost
its entries for them (explained below), so the 170 µs between it and the row above (170 to 183
in three runs) are spent in HTTP/3: 8.5 ns per pending request and packet, 72 % of the total.

recv_streams fills through Http3Client::fetch(). Http3Connection::create_bidi_transport_stream()
(neqo-http3/src/connection.rs:925) has no limit of its own; it fails only when
conn.stream_create(StreamType::BiDi) does, that is, at the limit the server set with
initial_max_streams_bidi and MAX_STREAMS. request_with_stream() then registers a RecvMessage
(:974, add_streams() at :1865), which stays in recv_streams until the response has been
read to the end or the request is reset or cancelled. A server that grants 100,000 streams and
answers nothing keeps every request the application makes in the table.

The call is in process_http3(), neqo-http3/src/connection_client.rs:757:

fn process_http3(&mut self, now: Instant) {
    match self.base_handler.state() {
        Http3State::ZeroRtt | Http3State::Connected | Http3State::GoingAway(..) => {
            self.base_handler
                .expire_datagram_queues(&mut self.conn, now);

process_http3() runs at the end of process_multiple_input() (:749) and before and after the
transport's turn in process_multiple_output() (:822, :827). Nothing on the way asks whether a
session exists or whether an extended CONNECT feature is enabled. For a request, s is a
RecvMessage, which uses the trait's default extended_connect_session() that returns None
(neqo-http3/src/lib.rs:453); only a Session returns Some
(neqo-http3/src/features/extended_connect/session.rs:701). With 20,000 requests pending and no
session, one small packet thus costs a walk over three times 20,000 hash-table entries, with a
dynamic call for each that returns None. Both the calls in process_http3() and the walk in
expire_datagram_queues() were introduced in 9d7e35ba607f ("WebTransport datagram queue initial
version (#4003)", 2026-09-29), first released in v0.33.0; v0.32.0 is not affected.

The GOAWAY row separates this from the per-stream work of neqo-transport. On GOAWAY with stream
ID 0, Http3Client::handle_goaway() (connection_client.rs:1015) removes the handlers of all
requests from send_streams and recv_streams but does not touch the QUIC streams: the client
sends neither RESET_STREAM nor STOP_SENDING (the reproducer asserts both counters are 0). The
65 µs that remain are per-packet work over all streams in the transport, which is not part of
this report.

Http3ServerHandler::process_http3() makes the same call once per round
(neqo-http3/src/connection_server.rs:199). There the table holds the client's requests, whose
number the server limits itself (max_streams, 100 by default).

Impact

An application only meets this when it keeps a large number of requests open on one HTTP/3
connection and the server leaves them unanswered: each received packet, with its
process_input() and process_output() calls, then costs about 8.5 ns more per pending request.
At the tens or hundreds of concurrent requests that are usual this is under a microsecond per
packet and goes unnoticed; it becomes
visible only with thousands. The requests are always the application's own: the server decides
how many may be open (MAX_STREAMS) and how long they stay open, but cannot create them, and
streams the server opens itself are limited by the client's own max_streams (100
bidirectional, 100 unidirectional by default). Neqo has no cap on concurrent requests of its
own; an embedder that has one bounds the effect accordingly.

With 20,000 requests pending, a small packet costs the client about 235 µs. About 170 µs of that
is this function; the remaining 63–66 µs (against 3.5 µs on an idle connection) is the
transport's own per-stream work over the same 20,000 streams, which is not part of this report
and which the attached patch does not change. The cost is per call, so it shows most when packets
arrive one at a time. The effect is a slower thread driving neqo, in proportion to the number of
pending requests, until they are answered, cancelled or the connection closes; there is no crash,
no hang and no memory growth. This happens whether or not WebTransport or connect-udp is enabled.

Suggested fix

The attached patch keeps the sessions where they can be found without a search. It adds a
sessions: HashMap<StreamId, Rc<RefCell<extended_connect::session::Session>>> field to
Http3Connection in neqo-http3/src/connection.rs, next to recv_streams, and keeps it in step
with the stream tables:

  • filled at the only two places a session is registered, extended_connect_create_session() and
    do_accept_extended_connect();
  • emptied in remove_extended_connect(), the single teardown point that remove_recv_stream() and
    remove_send_stream() (connection.rs:1974, :1991) reach when they find both halves of a
    session, and cleared next to recv_streams in close() and handle_zero_rtt_rejected().

expire_datagram_queues() then iterates sessions instead of filtering all of recv_streams.
The two sibling walks with the same filter, drain_webtransport_sessions() (connection.rs:1361,
first GOAWAY) and webtransport_set_anticipated_incoming_streams() (:1461, API call), use the
table too, so per-session work is O(sessions) everywhere. No behaviour change is intended;
Http3Connection is crate-private, so no public interface changes.

Applied to this commit and rebuilt, the reproducer prints OK (third column of the table),
cargo test --locked -p neqo-http3 passes, and cargo +nightly fmt --check and
cargo clippy --locked --all-targets -- -D warnings are clean. remove_recv_stream() and
remove_send_stream() can return early through ? before reaching remove_extended_connect() if
the other half of a session is missing; no way into that state is known, but removing the
sessions entry at the point the session leaves the stream table would make a stale entry
impossible.

Proposed patches

patches/1.patch
# neqo-http3/src/connection.rs
# fix(http3): track extended CONNECT sessions in their own table so expire_datagram_queues() stops walking
#   every receive stream on each packet
#
# Http3Connection had no way to find its extended CONNECT sessions other than walking all of recv_streams and
#   asking each handler, and expire_datagram_queues() did that three times per received packet, so per-packet
#   client CPU grew with the number of unanswered requests even when no session can exist. The patch adds a
#   `sessions` map next to `recv_streams` in Http3Connection, the struct that owns the stream tables: filled
#   at the only two places a Session is registered (extended_connect_create_session,
#   do_accept_extended_connect), emptied in remove_extended_connect() (the single teardown point reached from
#   both remove_recv_stream and remove_send_stream) and at the two clear() sites (close, 0-RTT rejection).
#   expire_datagram_queues() now iterates that map; the two sibling walks with the same filter,
#   drain_webtransport_sessions() (first GOAWAY) and webtransport_set_anticipated_incoming_streams() (API
#   call), use it too, so per-session work is O(sessions) everywhere. No behaviour change is intended: with a
#   temporary assertion comparing `sessions` against the sessions found in recv_streams (same Rc, same id,
#   send half present) on every expire_datagram_queues() call, the whole `cargo test --locked --workspace
#   --exclude mtu` suite passed, and the assertion fired in 44 tests when the removal was taken out. `cargo
#   +nightly fmt --check` and `cargo clippy --locked --all-targets -- -D warnings` are clean; no test is added
#   because the only observable effect is timing (reproducer: 233 us -> 66 us per packet with 20000 pending
#   requests, equal to the GOAWAY control).
# reviewer: good — Fixes the cause (a separate table of sessions, kept in step at the only two places sessions
#   are added and the one place they are torn down, plus both clear() sites); neqo-http3 tests (479) pass,
#   clippy and nightly fmt are clean, and per-packet time drops from 232 to 66 µs.
# our check: FIXED · confidence high
#
diff --git a/neqo-http3/src/connection.rs b/neqo-http3/src/connection.rs
index 004a116a..b73b9dc3 100644
--- a/neqo-http3/src/connection.rs
+++ b/neqo-http3/src/connection.rs
@@ -311,6 +311,9 @@ pub struct Http3Connection {
     streams_with_pending_data: HashSet<StreamId>,
     send_streams: HashMap<StreamId, Box<dyn SendStream>>,
     recv_streams: HashMap<StreamId, Box<dyn RecvStream>>,
+    /// The extended CONNECT sessions that are in `recv_streams`, so that per-session work does
+    /// not have to walk every stream.
+    sessions: HashMap<StreamId, Rc<RefCell<extended_connect::session::Session>>>,
     webtransport: ExtendedConnectFeature,
     connect_udp: ExtendedConnectFeature,
     send_group_generator: SendGroupGenerator,
@@ -350,6 +353,7 @@ impl Http3Connection {
             streams_with_pending_data: HashSet::default(),
             send_streams: HashMap::default(),
             recv_streams: HashMap::default(),
+            sessions: HashMap::default(),
             send_group_generator: SendGroupGenerator::default(),
             role,
         }
@@ -676,6 +680,7 @@ impl Http3Connection {
             // them), and creating a session fails with `Unavailable` until one is.
             self.send_streams.clear();
             self.recv_streams.clear();
+            self.sessions.clear();
             Ok(())
         } else {
             debug_assert!(false, "Zero rtt rejected in the wrong state");
@@ -801,6 +806,7 @@ impl Http3Connection {
         }
         self.send_streams.clear();
         self.recv_streams.clear();
+        self.sessions.clear();
     }
 
     /// This function will not handle the output of the function completely, but only
@@ -1232,6 +1238,7 @@ impl Http3Connection {
             Rc::clone(&self.qpack_decoder),
             connect_type,
         )));
+        self.sessions.insert(id, Rc::clone(&extended_conn));
         self.add_streams(
             id,
             Box::new(Rc::clone(&extended_conn)),
@@ -1342,6 +1349,7 @@ impl Http3Connection {
                     connect_type,
                 )?,
             ));
+            self.sessions.insert(stream_id, Rc::clone(&extended_conn));
             self.add_streams(
                 stream_id,
                 Box::new(Rc::clone(&extended_conn)),
@@ -1359,9 +1367,8 @@ impl Http3Connection {
     /// sessions as draining and returns any sessions that were newly
     /// marked as draining
     pub(crate) fn drain_webtransport_sessions(&self) -> impl Iterator<Item = StreamId> + use<'_> {
-        self.recv_streams.iter().filter_map(|(id, s)| {
-            let sess = s.extended_connect_session()?;
-            let mut s = sess.borrow_mut();
+        self.sessions.iter().filter_map(|(id, s)| {
+            let mut s = s.borrow_mut();
             (s.connect_type() == ExtendedConnectType::WebTransport && s.set_draining())
                 .then_some(*id)
         })
@@ -1453,7 +1460,7 @@ impl Http3Connection {
     /// Recompute the connection's incoming limit for `stream_type` as the sum over open
     /// `WebTransport` sessions; see
     /// [`crate::webtransport::ClientSession::webtransport_set_anticipated_incoming_uni_streams`].
-    /// Walks every receive stream: call per session, not per stream.
+    /// Walks every session: call per session, not per stream.
     ///
     /// # Errors
     /// Returns `InvalidStreamId` if the session does not exist, is not a `WebTransport`
@@ -1474,10 +1481,9 @@ impl Http3Connection {
             .set_anticipated_incoming(stream_type, value);
 
         let total: u64 = self
-            .recv_streams
+            .sessions
             .values()
-            .filter_map(|s| {
-                let session = s.extended_connect_session()?;
+            .filter_map(|session| {
                 let session = session.borrow();
                 (!session.is_closing()
                     && session.connect_type() == ExtendedConnectType::WebTransport)
@@ -1746,9 +1752,8 @@ impl Http3Connection {
     /// Record expired, sent and too-big datagram counts for each active
     /// extended-CONNECT session.  Returns the number expired.
     pub(crate) fn expire_datagram_queues(&self, conn: &mut Connection, now: Instant) -> u64 {
-        self.recv_streams
+        self.sessions
             .values()
-            .filter_map(|s| s.extended_connect_session())
             .filter(|s| s.borrow().is_active())
             .map(|s| {
                 let mut s = s.borrow_mut();
@@ -1941,6 +1946,7 @@ impl Http3Connection {
         wt: &Rc<RefCell<extended_connect::session::Session>>,
         conn: &mut Connection,
     ) {
+        self.sessions.remove(&wt.borrow().id());
         wt.borrow_mut().drop_queued_datagrams(conn);
 
         let (recv, send) = wt.borrow_mut().take_sub_streams();

When fixing this, please carry this line into the commit message:

Discovered by Anthropic's OSS Scanner, as bug ANT-2026-XGCSFVTF.

Activity

  1. added
    server-side
    client-side
    http3
    on Nov 12, 2026
  2. added
    extended-connect
    on Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

client-sideextended-connecthttp3p3server-side

Type

No type

Fields

Priority

None yet

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions