WIP: http: free idle connection slots for waiting connections at the limit #37019

Draft
optout21 wants to merge 2 commits from 2611-http-close-if-full2 into master AGit
optout21 commented 2026-11-30 13:33:05 +00:00 (Migrated from github.com)

Fixes #36960

Problem

Since the libevent replacement (#35182), the HTTP server limits the number of connected clients to -rpcmaxconnections (default 16, #35730). At the limit, new connections are not accepted and wait in the kernel's accept queue.

A keep-alive connection keeps its slot after its request has been answered. The slot is only freed when the client closes the connection, or after -rpcservertimeout (default 30 s) of inactivity. So a client that holds the maximum number of keep-alive connections blocks every other RPC and REST client, including bitcoin-cli, for up to 30 s, without any error or log message.

This happens in practice with a client that keeps a pool of parallel keep-alive connections. The popular indexer electrs, for example, fetches blocks over REST with one connection per CPU thread. On a 32-core machine, every batch of blocks it fetches while catching up stalls for about 30 s. Measured on master with 100 clients that each make one request and then keep their connection open (-rpcmaxconnections=64): 62 were answered at once, and the remaining 38 only after 31.1 s, when the idle connections hit -rpcservertimeout. With -rpcservertimeout=10 the stall shrinks to 10–11 s. The libevent server had no connection limit, so this didn't happen before v32.

Solution

While the server is at the limit and connections are waiting to be accepted, free slots for them in two ways:

  1. Close connections after their reply. A reply that would keep the connection alive gets Connection: close instead, and the connection is closed once the reply has been sent. The client learns from the reply that the connection won't be reused, so there is no race with the client, and a slot is freed as soon as a request has been answered. The I/O thread checks the listening sockets for waiting connections without waiting, once per loop iteration and only while at the limit, and publishes the result in an atomic flag that replies read.

  2. Evict the keep-alive client that has been idle the longest. Connections that were already idle when the others started waiting won't get another reply, so they would keep their slots. Such a client is disconnected if it is fully idle: all its requests have been answered and sent, it has not started a new request, and it has been idle for at least HTTP_MIN_IDLE_FOR_EVICTION (500 ms). At most one client is evicted per I/O loop iteration. At the limit, the listening sockets are only polled if a client could be evicted, so that a waiting connection that can't be accepted doesn't make the I/O loop spin.

Closing after the reply is the main mechanism, and eviction is only the fallback. An eviction can race with the client: if the client reuses the connection at that moment, its request fails with a connection reset. HTTP allows servers to close idle connections and expects clients to retry (RFC 9112, section 9.3.1), but not all clients do. An earlier version of this change only evicted idle clients. Tested with electrs under constant connection pressure, it hit this race quickly: electrs's HTTP client (ureq) reuses the connection that has been idle the longest, the same one that was evicted, and doesn't retry, so electrs failed with "Connection reset by peer". With replies closing their connections, slots are freed without that race during sustained load, and eviction is rarely needed.

New connections that have not sent a request yet, and clients with a request in progress, are never closed. Behavior below the limit is unchanged. Both mechanisms are logged in the http debug category, and the help text of -rpcmaxconnections describes them.

Alternatives considered

  • Raise the default of -rpcmaxconnections: this only moves the threshold, and costs file descriptors, which is why the default was lowered from 128 to 16 in #35730.
  • Only evict idle clients: simpler, but races with clients that reuse their connections, as described above.
  • Only close connections after their reply: race-free, but connections that were idle before the others started waiting would still block their slots until -rpcservertimeout.
  • Reject waiting connections with 503: the client gets an error instead of a delay, while idle slots stay blocked.

Tests

  • The first commit adds a functional test for the current behavior: with all slots held by idle keep-alive clients and -rpcservertimeout=0, a new connection is never accepted. The second commit changes it to the new expectation: the client that has been idle the longest is evicted, and the new connection is served.
  • New functional test for closing after the reply: with all slots held by busy clients (which can't be evicted), a waiting connection is served once one of them gets its reply, which carries Connection: close and closes the connection.
  • Unit tests for HTTPRemoteClient::IsEvictable(), including the minimum idle time (with a mocked clock), and for closing the connection after the reply while connections are waiting.
  • check_connection_limit() filled all slots with idle keep-alive clients, which would now be evicted. Its clients now keep an unfinished request open, so they are busy, and the test still checks that a connection over the limit waits when no client can be evicted.
  • Manually tested with electrs catching up against a node with a low -rpcmaxconnections.

Related: #36204 addresses a different way of holding a slot: clients that never finish sending a request.

Fixes #36960 ### Problem Since the libevent replacement (#35182), the HTTP server limits the number of connected clients to `-rpcmaxconnections` (default 16, #35730). At the limit, new connections are not accepted and wait in the kernel's accept queue. A keep-alive connection keeps its slot after its request has been answered. The slot is only freed when the client closes the connection, or after `-rpcservertimeout` (default 30 s) of inactivity. So a client that holds the maximum number of keep-alive connections blocks every other RPC and REST client, including `bitcoin-cli`, for up to 30 s, without any error or log message. This happens in practice with a client that keeps a pool of parallel keep-alive connections. The popular indexer `electrs`, for example, fetches blocks over REST with one connection per CPU thread. On a 32-core machine, every batch of blocks it fetches while catching up stalls for about 30 s. Measured on master with 100 clients that each make one request and then keep their connection open (`-rpcmaxconnections=64`): 62 were answered at once, and the remaining 38 only after 31.1 s, when the idle connections hit `-rpcservertimeout`. With `-rpcservertimeout=10` the stall shrinks to 10–11 s. The libevent server had no connection limit, so this didn't happen before v32. ### Solution While the server is at the limit and connections are waiting to be accepted, free slots for them in two ways: 1. **Close connections after their reply.** A reply that would keep the connection alive gets `Connection: close` instead, and the connection is closed once the reply has been sent. The client learns from the reply that the connection won't be reused, so there is no race with the client, and a slot is freed as soon as a request has been answered. The I/O thread checks the listening sockets for waiting connections without waiting, once per loop iteration and only while at the limit, and publishes the result in an atomic flag that replies read. 2. **Evict the keep-alive client that has been idle the longest.** Connections that were already idle when the others started waiting won't get another reply, so they would keep their slots. Such a client is disconnected if it is fully idle: all its requests have been answered and sent, it has not started a new request, and it has been idle for at least `HTTP_MIN_IDLE_FOR_EVICTION` (500 ms). At most one client is evicted per I/O loop iteration. At the limit, the listening sockets are only polled if a client could be evicted, so that a waiting connection that can't be accepted doesn't make the I/O loop spin. Closing after the reply is the main mechanism, and eviction is only the fallback. An eviction can race with the client: if the client reuses the connection at that moment, its request fails with a connection reset. HTTP allows servers to close idle connections and expects clients to retry (RFC 9112, section 9.3.1), but not all clients do. An earlier version of this change only evicted idle clients. Tested with electrs under constant connection pressure, it hit this race quickly: electrs's HTTP client (ureq) reuses the connection that has been idle the longest, the same one that was evicted, and doesn't retry, so electrs failed with "Connection reset by peer". With replies closing their connections, slots are freed without that race during sustained load, and eviction is rarely needed. New connections that have not sent a request yet, and clients with a request in progress, are never closed. Behavior below the limit is unchanged. Both mechanisms are logged in the `http` debug category, and the help text of `-rpcmaxconnections` describes them. ### Alternatives considered - **Raise the default of `-rpcmaxconnections`:** this only moves the threshold, and costs file descriptors, which is why the default was lowered from 128 to 16 in #35730. - **Only evict idle clients:** simpler, but races with clients that reuse their connections, as described above. - **Only close connections after their reply:** race-free, but connections that were idle before the others started waiting would still block their slots until `-rpcservertimeout`. - **Reject waiting connections with `503`:** the client gets an error instead of a delay, while idle slots stay blocked. ### Tests - The first commit adds a functional test for the current behavior: with all slots held by idle keep-alive clients and `-rpcservertimeout=0`, a new connection is never accepted. The second commit changes it to the new expectation: the client that has been idle the longest is evicted, and the new connection is served. - New functional test for closing after the reply: with all slots held by busy clients (which can't be evicted), a waiting connection is served once one of them gets its reply, which carries `Connection: close` and closes the connection. - Unit tests for `HTTPRemoteClient::IsEvictable()`, including the minimum idle time (with a mocked clock), and for closing the connection after the reply while connections are waiting. - `check_connection_limit()` filled all slots with idle keep-alive clients, which would now be evicted. Its clients now keep an unfinished request open, so they are busy, and the test still checks that a connection over the limit waits when no client can be evicted. - Manually tested with electrs catching up against a node with a low `-rpcmaxconnections`. Related: #36204 addresses a different way of holding a slot: clients that never finish sending a request.
DrahtBot commented 2026-11-30 13:33:16 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.
A summary of reviews will appear here.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #37055 (refactor: drop format calls on strings without arguments by fanquake)
  • #36434 (http: support unix sockets by pinheadmz)
  • #36204 (http: disconnect clients that never finish a request by janb84)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/37019 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/37019.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/37019#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. A summary of reviews will appear here. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#37055](https://github.com/bitcoin/bitcoin/pull/37055) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/37055.svg"></sub> (refactor: drop format calls on strings without arguments by fanquake) * [#36434](https://github.com/bitcoin/bitcoin/pull/36434) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36434.svg"></sub> (http: support unix sockets by pinheadmz) * [#36204](https://github.com/bitcoin/bitcoin/pull/36204) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36204.svg"></sub> (http: disconnect clients that never finish a request by janb84) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
First-time contributor

2 additional verified findings in the Review report.

🟠 Minor · IsEvictable() overlooks a partially parsed pipelined request

IsEvictable() can discard a partially parsed pipelined request under connection pressure after 500 ms; no current client producing this input was identified, so production impact is unconfirmed.

Location: src/httpserver.cpp:1316 (head).

🟠 Minor · Peers excluded by -rpcallowip can trigger connection reclamation

With a reachable non-loopback -rpcbind and restrictive -rpcallowip, an excluded peer can trigger idle eviction or Connection: close replies before its address is checked; the default loopback-only bind is unaffected.

Location: src/httpserver.cpp:1026 (head).

🟠 Minor · Forced close still permits dispatch of a buffered pipelined request

Pressure-forced Connection: close exposes an existing dispatch gap: buffered pipelined RPCs can execute without a reply; no in-tree or identified external client pipelines JSON-RPC, so production impact is unconfirmed.

Location: src/httpserver.cpp:609 (head).

🟠 Minor · Silent newcomers are protected over established idle connections

At the connection limit, unauthenticated silent newcomers can displace established clients idle for at least 500 ms and retain their slots until -rpcservertimeout, which defaults to 30 seconds.

Location: src/httpserver.cpp:1036 (head).

🔵 Suggestion · Close-after-reply leaves idle-pool eviction compatibility unverified

Close-after-reply cannot protect an already-idle pool at the limit; the reported ureq failure involved eviction-only behavior, and recovery under this fallback remains unverified.

Location: src/httpserver.h:55 (head).

🔵 Suggestion · One waiting connection can close several persistent connections

The shared, non-consuming waiting flag can close several persistent connections to admit one newcomer; the amount of extra reconnect churn has not been measured.

Location: src/httpserver.cpp:601 (head).

Review coverage was incomplete.


Reviewed: 5675ffce6847 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:483ed3be8d13b50996bf0f81d4f55487b6b938dd --> <!-- ralph-head:5675ffce6847e242d5dfed09cde4e59734f84d26 --> <!-- ralph-case:bd18393e8ec3bd0025bea8bc937a6304f2b259d3033eb0b9a168635cde6a29d3 --> [2 additional verified findings in the Review report](<https://review.fish.foo/report/37019-5675ffce6847e242d5dfed09cde4e59734f84d26-3349-1.html>). **🟠 Minor · `IsEvictable()` overlooks a partially parsed pipelined request** `IsEvictable()` can discard a partially parsed pipelined request under connection pressure after 500 ms; no current client producing this input was identified, so production impact is unconfirmed. Location: [`src/httpserver.cpp:1316`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5675ffce6847e242d5dfed09cde4e59734f84d26/src/httpserver.cpp#L1316>) (head). **🟠 Minor · Peers excluded by `-rpcallowip` can trigger connection reclamation** With a reachable non-loopback `-rpcbind` and restrictive `-rpcallowip`, an excluded peer can trigger idle eviction or `Connection: close` replies before its address is checked; the default loopback-only bind is unaffected. Location: [`src/httpserver.cpp:1026`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5675ffce6847e242d5dfed09cde4e59734f84d26/src/httpserver.cpp#L1026>) (head). **🟠 Minor · Forced close still permits dispatch of a buffered pipelined request** Pressure-forced `Connection: close` exposes an existing dispatch gap: buffered pipelined RPCs can execute without a reply; no in-tree or identified external client pipelines JSON-RPC, so production impact is unconfirmed. Location: [`src/httpserver.cpp:609`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5675ffce6847e242d5dfed09cde4e59734f84d26/src/httpserver.cpp#L609>) (head). **🟠 Minor · Silent newcomers are protected over established idle connections** At the connection limit, unauthenticated silent newcomers can displace established clients idle for at least 500 ms and retain their slots until `-rpcservertimeout`, which defaults to 30 seconds. Location: [`src/httpserver.cpp:1036`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5675ffce6847e242d5dfed09cde4e59734f84d26/src/httpserver.cpp#L1036>) (head). **🔵 Suggestion · Close-after-reply leaves idle-pool eviction compatibility unverified** Close-after-reply cannot protect an already-idle pool at the limit; the reported `ureq` failure involved eviction-only behavior, and recovery under this fallback remains unverified. Location: [`src/httpserver.h:55`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5675ffce6847e242d5dfed09cde4e59734f84d26/src/httpserver.h#L55>) (head). **🔵 Suggestion · One waiting connection can close several persistent connections** The shared, non-consuming waiting flag can close several persistent connections to admit one newcomer; the amount of extra reconnect churn has not been measured. Location: [`src/httpserver.cpp:601`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/5675ffce6847e242d5dfed09cde4e59734f84d26/src/httpserver.cpp#L601>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`5675ffce6847`](<https://git.fish.foo/bitcoin/bitcoin/commit/5675ffce6847e242d5dfed09cde4e59734f84d26>) · [Review report](<https://review.fish.foo/report/37019-5675ffce6847e242d5dfed09cde4e59734f84d26-3349-1.html>) · [Previous reports](<https://review.fish.foo/traces/37019/>) [permalink](<https://review.fish.foo/report/37019-5675ffce6847e242d5dfed09cde4e59734f84d26-3349-1.html>)
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!37019
No description provided.