Skip to content

Add support for HTTP/2 - #13039

Open
Moist-Cat wants to merge 86 commits into
aio-libs:masterfrom
Moist-Cat:master
Open

Moist-Cat wants to merge 86 commits into
aio-libs:masterfrom
Moist-Cat:master

Conversation

@Moist-Cat

@Moist-Cat Moist-Cat commented Jul 2, 2026 •

Copy link
Copy Markdown

What do these changes do?

Add HTTP/2 client support.

Why

Faster I/O bound operations (e.g., many requests to the same host) via multiplexing (handling several streams/requests inside a single connection).

How

  1. Use the environment variable AIOHTTP_ENABLE_EXPERIMENTAL_PROTOCOLS=1 to allow h2 negotiation via ALPN during the TLS handshake. Via the http2_enabled flag inside ClientSession.
  2. ResponseHandler was substituted by a wrapper that conditionally switches protocols depending on the negotiated protocol.
  3. I forced unconditional connection reuse for HTTP/2 connections since pooling is now unnecessary. This doesn't affect HTTP/1.1 connections. To make this possible, however, I had to use a Semaphore to avoid race conditions.

This means opening many HTTP/1.1 connections in parallel is now slower because it's done sequentially. That said, to know if connections can be pooled or not it's only necessary to wait until the first connection is done. Once it's known whether the host supports HTTP/2 or not, the rest of the requests can be done in parallel so it's possible to mitigate this performance hit substantially. Solved!

Backward compatibility

Opt-in via http2_enabled.

Testing

%95 coverage, benchmarks (%50 latency reduction for 99 requests, see below), and integration tests against real servers (~100).

Dependencies

hpack

Is it a substantial burden for the maintainers to support this?

Yes.

Related issue number

refs #5999

The implementation is self-contained, the changes to the current codebase are minimal and backwards compatible.

Missing features (to the date):

  • Proxies
  • Web socket upgrade
  • Response streaming
  • CONTINUATION frames for very large headers
  • h2c (cleartext) not supported (optional)
  • Ensure all the high-level configuration/parameters work (or make sense for) with HTTP/2 as well (obsolete)
  • expect100
  • Request streaming
  • Request payload compression
  • Send PING frames (if we connect to many servers in parallel and read the payloads sequentially, the server might close the idle connections).
  • Implement a (good) algorithm/strategy to send WINDOW_UPDATE frames.

Things that should be implemented/changed:

  • Support reusable connections
    This means changing the way we handle all connections so the implementation should be done in a separate PR to avoid regressions.

  • Make HTTP/1.1 a particular case of HTTP/2
    HTTP/1.1 connections can be seen as HTTP/2 connections that only allow a single stream. When we try to fit HTTP/2 connections inside routines that were built for HTTP/1.1 like we did here, the implementation ends up looking a bit awkward. (with "awkward" I mean that we have to add 1-2 additional if statements per class to pass the stream_id to the HTTP/2 connector).

Moist-Cat and others added 2 commits July 2, 2026 19:38
    This implementation is backwards compatible, functional, but still
incomplete.
Comment thread aiohttp/http2/connection.py Fixed
Comment thread aiohttp/http2/connection.py Fixed
Comment thread aiohttp/http2/connection.py Fixed
Comment thread aiohttp/http2/response.py Fixed
Comment thread aiohttp/http_protocol.py
self._handler: Optional[asyncio.Protocol] = None

# ---- Transport callbacks forwarded to the real handler ----
def connection_made(self, transport: asyncio.BaseTransport) -> None:
Comment thread tests/http2/test_http2.py Fixed
Comment thread tests/http2/test_http2.py Fixed
Comment thread tests/http2/test_http2.py Fixed
Comment thread tests/http2/test_http2.py Fixed
Comment thread tests/http2/test_http2.py Fixed
@codecov

codecov Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.20988% with 165 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.88%. Comparing base (b5acd43) to head (8418f19).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
aiohttp/http2/connection.py 84.46% 49 Missing and 29 partials ⚠️
aiohttp/http2/synchro.py 61.01% 19 Missing and 4 partials ⚠️
aiohttp/connector.py 85.95% 13 Missing and 4 partials ⚠️
aiohttp/http2/adapter.py 84.82% 14 Missing and 3 partials ⚠️
aiohttp/http2/stream.py 90.90% 7 Missing and 5 partials ⚠️
aiohttp/http_protocol.py 83.33% 3 Missing and 2 partials ⚠️
tests/http2/test_http2.py 99.48% 3 Missing and 2 partials ⚠️
aiohttp/client.py 80.00% 2 Missing and 2 partials ⚠️
tests/conftest.py 92.30% 2 Missing ⚠️
tests/http2/utils.py 95.91% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #13039      +/-   ##
==========================================
- Coverage   99.13%   98.88%   -0.26%     
==========================================
  Files         135      148      +13     
  Lines       54630    57014    +2384     
  Branches     2808     2985     +177     
==========================================
+ Hits        54158    56378    +2220     
- Misses        357      469     +112     
- Partials      115      167      +52     
Flag Coverage Δ
Autobahn 21.69% <25.67%> (+0.15%) ⬆️
CI-GHA 98.81% <93.20%> (-0.26%) ⬇️
OS-Linux 98.51% <93.20%> (-0.24%) ⬇️
OS-Windows 97.34% <93.16%> (-0.19%) ⬇️
OS-macOS 98.16% <93.20%> (-0.21%) ⬇️
Py-3.11 98.09% <93.20%> (-0.23%) ⬇️
Py-3.12 98.18% <93.20%> (-0.22%) ⬇️
Py-3.13 98.17% <93.20%> (-0.22%) ⬇️
Py-3.14 98.22% <93.20%> (-0.23%) ⬇️
Py-3.15 98.22% <93.20%> (-0.23%) ⬇️
Py-3.15t 98.08% <93.20%> (-0.22%) ⬇️
Py-pypy-3.12 96.82% <93.00%> (-0.18%) ⬇️
VM-macos-latest 98.16% <93.20%> (-0.21%) ⬇️
VM-ubuntu-latest 98.51% <93.20%> (-0.24%) ⬇️
VM-windows-latest 97.34% <93.16%> (-0.19%) ⬇️
cython-coverage 81.93% <31.93%> (-2.11%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@codspeed

codspeed Bot commented Jul 3, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 8.14%

2 warnings

⚠️ 49 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚠️ 1 benchmark with a significant change ran in a different software environment

Its base and head results were measured with a different OS or toolchain, such as compiler, runtime or library versions, so the change might come from this difference rather than from the code. Open the benchmark to see what changed.

See affected benchmarks

❌ 1 regressed benchmark
✅ 101 untouched benchmarks
⏩ 83 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_client_request_update_cookies 329.9 µs 359.1 µs -8.14%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing Moist-Cat:master (8418f19) with master (b5acd43)

Open in CodSpeed

Footnotes

  1. 83 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

Comment thread tests/http2/test_http2.py Fixed
Comment thread docs/conf.py

try:
import sphinxcontrib.spelling # noqa
import sphinxcontrib.spelling
Moist-Cat and others added 2 commits July 4, 2026 21:52
    It was necessary to add a semaphore to ensure the requests connect
sequentially to the hosts and reuse connections when necessary. HTTP/2
uses a single connection per host.
@Moist-Cat

Moist-Cat commented Jul 5, 2026 •

Copy link
Copy Markdown
Author

I ran tests against remote servers (httpbin.org) to verify HTTP/2 indeed reduces latency.

HTTP/2 Performance Test Results

System Specs:

  • CPU: Intel(R) Core(TM) i5-8350U CPU @ 1.70GHz (8 cores)
  • Memory: 7892016 KB
  • Python: 3.14.2
  • aiohttp: 4.0.0a2.dev0

Test Configuration:

  • Concurrency per batch: 99
  • Number of batches: 30
  • Total requests per version: 2970

Batch Mean Latency (seconds)

Version Mean Std Dev P50 P95 P99
HTTP/1.1 1.3928 0.9116 1.2004 2.9433 4.5932
HTTP/2 0.4821 0.1588 0.4502 0.6966 1.0516

Individual Request Latency Distribution

Version Mean P50 P95 P99
HTTP/1.1 1.3928 0.9819 3.8822 7.1815
HTTP/2 0.4821 0.4517 0.7857 1.3151

Statistical Analysis

  • Welch’s t‑test on batch means:
    t = 5.390, p = 0.000007
  • Cohen’s d: 1.392
  • Assumption: Measurement errors (batch means) are approximately normally distributed (reasonable with 30 batches by the Central Limit Theorem).

A simple bar chart with the means (results vary because they are from a second test):
bar_chart

We lose efficiency in CPU bound tasks (see #13039 (comment)) but I/O bound tasks are significantly faster. This is specially true for batch requests that require multiple TCP connections to the same host.

@Moist-Cat

Copy link
Copy Markdown
Author

I would like to know if the trade-offs (I/O vs CPU) are acceptable before writing the docs.

@Moist-Cat
Moist-Cat marked this pull request as ready for review July 6, 2026 00:29
@aiolibsbot

Copy link
Copy Markdown
Contributor

@Moist-Cat: I ran tests against remote servers (httpbin.org) to verify HTTP/2 indeed reduces latency.

HTTP/1.1 regression not inherent to h2. Caused by global Semaphore(1) wrapping every connector.connect() in _connect_and_send_request. Serializes all connection setup, h1 included — hence the ~8% CodSpeed hit on non-h2 benchmarks. Scope the semaphore to first-connect-per-unknown-host under the flag; h1 parallelism returns.

@aiolibsbot

Copy link
Copy Markdown
Contributor

@Moist-Cat: I would like to know if the trade-offs (I/O vs CPU) are acceptable before writing the docs.

Bigger blocker than the CPU/IO trade-off. h2 path returns Http2Response, not ClientResponse. Breaks .json(), .text(), cookies, raise_for_status, redirects, middleware. Hold the docs. Resolve response integration, the connector-slot leak, and the semaphore serialization first. The default-path CPU cost is the semaphore — removable, not intrinsic.

@aiolibsbot

aiolibsbot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@Moist-Cat

Moist-Cat commented Jul 6, 2026 •

Copy link
Copy Markdown
Author

Either inheriting from or using ClientResponse directly appears to be the most architecturally sound approach (even though inheritance in this case constitutes a violation of the Liskov substitution principle), however this class is deeply coupled with HTTP/1.1. For example, the _start method calls protocol.read() from connection. This is incompatible with h2 because the protocol handles many streams, not just the one associated to the response and raise_for_status depends on reason which doesn't exist in h2. A better solution is to create a "doppelganger" class that mimics the public interface, which is precisely what Http2Response is. The public interface is the same so the high-level functionalities that rely on these (e.g., session cookies, redirects) keep work regardless of the underlying protocol. In other words, the API is backwards compatible as far as I tested.

Regarding the Semaphore, I believe simply allowing parallel connections when the flag is not set would be the best approach here since the general solution (i.e., verifying if the host supports h2) requires tracking the hosts in TCPConnector which doesn't seem trivial at glance. Improving performance can be done in another PR after the protocol is integrated and working.

To deal with limit for h2, it's important to decide whether to count streams (current behaviour) or TCP connections (calling _release after every successful connection while keeping the same protocol in the _acquired set).

@Dreamsorcerer Dreamsorcerer added this to the 4.0 milestone Jul 12, 2026
Comment thread aiohttp/http2/adapter.py Fixed
Comment thread aiohttp/http2/connection.py Fixed
Comment thread aiohttp/http2/stream.py Fixed
Comment thread aiohttp/http_writer.py Fixed
Comment thread fuzzers/fuzz_connector.py Fixed
Comment thread fuzzers/fuzz_connector.py
host_id, req, task = pending.pop(cid)
try:
connection = task.result()
except BaseException as e:
Comment thread fuzzers/fuzz_connector.py
try:
connection = task.result()
live[cid] = LiveConn(cid, host_id, connection, req)
except BaseException:
Comment thread fuzzers/fuzz_connector.py
try:
connection = task.result()
live[cid] = LiveConn(cid, host_id, connection, req)
except BaseException:
Comment thread tests/http2/test_http2.py Fixed
Comment thread tests/http2/test_http2_adapter.py Fixed
@Moist-Cat

Copy link
Copy Markdown
Author

test_websocket_connection_cancellation seems to break when we add an additional reference to the response object because it relies on the GC to call the __del__ method, which is undefined behaviour in Python as far as I'm aware.

ref #14386

@Moist-Cat

Copy link
Copy Markdown
Author

I isolated all the remaining protocol-specific logic inside Connection we now have Connection (h11) and H2Connection (h2). This is similar to the Stream approach but it doesn't generate visible breaking changes and still gives us an unified interface for all protocols.

I'm going to fix a few bugs and verify that there are no major issues left.

@Moist-Cat Moist-Cat mentioned this pull request Nov 17, 2026
5 tasks done
Comment thread aiohttp/http2/adapter.py Fixed
@Moist-Cat

Copy link
Copy Markdown
Author

@aiolibsbot review

@aiolibsbot

Copy link
Copy Markdown
Contributor

❌ Permission denied. Only users with write access can trigger bot commands.

@Moist-Cat
Moist-Cat marked this pull request as ready for review December 2, 2026 19:43
self,
flags: int,
stream_id: int,
payload: bytes,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Server can exhaust client memory

A malicious HTTP/2 server can exhaust the client's memory with never-ending CONTINUATION frames.

_handle_continuation_frame extends _pending_headers with every incoming CONTINUATION payload and only decodes (and checks) the block after END_HEADERS arrives. There is no limit on how many bytes can accumulate, and HEADERS/CONTINUATION frames are exempt from HTTP/2 flow control, so nothing else caps them either. While the block is pending, every other frame is rejected as a protocol error, so the whole connection stalls too.

Example: the client (with http2_enabled=True) sends a request; the server replies with a HEADERS frame without END_HEADERS, then streams CONTINUATION frames of ~16 KB each forever. The client keeps appending to _pending_headers and is OOM-killed long before the default 5-minute total timeout fires. At localhost speed that is many GB.

The HPACK safety net is also a no-op: DEFAULT_SETTINGS sets MAX_HEADER_LIST_SIZE to 2**32 - 1 (settings.py:68) and that value is passed to Decoder(max_header_list_size=...), despite the comment saying the limit is there to prevent bombs. So even after END_HEADERS, the decoded header list has no size cap. Cap the accumulated block size (e.g. at a few times MAX_FRAME_SIZE) and advertise a real MAX_HEADER_LIST_SIZE, and treat exceeding either as a connection error.

Comment thread aiohttp/http2/stream.py
self.inbound_window -= max(len(data), payload_len)
# --- stream-level flow control refill ---
self.maybe_reset_window()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Server can buffer endless response data

HTTP/2 flow control no longer bounds how much response data the client buffers, so a malicious server can OOM the client with one response.

Stream.receive_data calls maybe_reset_window the moment data arrives, sending a full WINDOW_UPDATE before the app has consumed anything, and Http2Protocol.pause_reading is a no-op, so there is no transport-level backpressure either. The only remaining cap is the 64 KB connection window, which is refilled every time the app drains any stream's StreamReader below its low-water mark (resume_reading -> maybe_reset_window).

Example: the app reads response B chunk by chunk while response A on the same connection sits unread. Every read of B refills the connection window, and A's stream window refills on arrival, so the server can push an arbitrarily large body into A's body_reader, which buffers all of it in memory until the app gets to it. Reading a single stream slower than the server sends grows the buffer without bound too. HTTP/1.1 is safe here because the transport is paused while the buffer is full; this change removes that protection.

The window should only be refilled as the app consumes data - that is the entire point of HTTP/2 flow control.


self._read_timeout = read_timeout
self._auto_decompress = auto_decompress

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 security HTTP/2 response reads lose timeouts

Per-request timeout settings are silently dropped or shared connection-wide for HTTP/2 responses, so reads can hang forever.

Http2Protocol.set_response_params accepts timer but never stores it, and Stream creates its body StreamReader without a timer. On the HTTP/1.1 path the timer is passed into the reader, which is what enforces ClientTimeout.total while the app consumes the body. So once headers arrive, a malicious or stuck server can leave resp.read() hanging indefinitely even though the app set total=300.

On top of that, this method writes read_timeout and auto_decompress onto the shared protocol, once per request (H2Connection.send_request calls it for every request). The last request wins for the whole connection: one request with sock_read=None erases the read timeout of every other in-flight stream (the check fails open), and when _on_read_timeout does fire it calls _cancel_streams(0, ...), killing all streams on the connection instead of just the one that timed out.

Example: request A sets sock_read=10, request B on the same connection sets sock_read=None; the server stalls both. B's params overwrite A's, so A never times out and its task hangs until the app gives up.

@greptile-apps

greptile-apps Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

security Security Review

This PR does not appear safe to merge because a malicious server can exhaust the client's memory through unbounded CONTINUATION-frame buffering and unbounded response-body buffering on the new HTTP/2 path.

What was checked
  • Traced every HTTP/2 frame handler in the new parser; found no cumulative size limit on fragmented header blocks (CONTINUATION) and no effective HPACK header-list cap.
  • Traced HTTP/2 flow control and found the receive window is refilled when data arrives rather than when the app consumes it, so response bodies buffer without bound.
  • Compared HTTP/2 response timeout handling with the HTTP/1.1 path; the total-timeout timer is dropped and per-request read settings are applied to the shared connection instead of each stream.
  • Checked the connection-pool rework; found a race that can hand one pooled HTTP/1.1 connection to two requests when a trace callback yields control.
  • Checked request-header filtering, ALPN/TLS context selection, hpack version pinning, and the existing redirect/cookie stripping; found no new issues there.

Findings

  • P1 Server can exhaust client memory ▶
  • P1 Server can buffer endless response data ▶
  • P2 HTTP/2 response reads lose timeouts ▶
  • P2 Two requests can share one connection

@greptile-apps

greptile-apps Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Comments Outside Diff

  • P2 security Two requests can share one connection — aiohttp/connector.py:918

    A pooled HTTP/1.1 connection can be handed to two requests at once when trace callbacks yield.

    _get now works on conns = target[key].copy() and only persists the leftovers back into self._conns[key] at the end. Between the copy and the persist it awaits trace.send_connection_reuseconn(), so the popped protocol is still sitting in the real pool while the task is suspended. Before this change, conns was the live deque, so popleft() removed the connection from the pool before any await - the old code did not have this race.

    Example: the app has a TraceConfig whose on_connection_reuseconn callback awaits something (logging, metrics). Two concurrent requests hit _get for the same host; the first pops the connection and suspends in the trace callback, the second copies the original deque and pops the same connection. Both now write requests on one HTTP/1.1 connection and each reads whichever response arrives first, so one request can receive the other request's response - a cross-request data leak inside the app. The persist step can also overwrite the pool deque and silently drop a connection that a third task released into it meanwhile.

    Reorder so the protocol is removed from self._conns[key] before any await, as the old code did.

@asvetlov asvetlov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking the problem up.
Please address my initial review.

Comment thread aiohttp/base_protocol.py
self.transport: asyncio.Transport | None = None
# proto version
# we can't set the default due to a circular import
self.version: Any = None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it for HttpVersion? Move the class to some helper file if needed, but please avoid Any.

Comment thread aiohttp/client_reqrep.py
protocol = self._protocol
message, payload = await protocol.read() # type: ignore[union-attr]
assert protocol is not None
if hasattr(protocol, "version") and protocol.version.major == 2:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better ensure that all protocols have version attribute.

Comment thread aiohttp/client_reqrep.py
self.loop,
def _create_writer(
self, connection: "Connection"
) -> StreamWriter | Http2StreamWriter:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Return type looks cumbersome. Could you declare that an abstract writer is returned without using a union type?

Comment thread aiohttp/http_protocol.py
from .http2.connection import Http2Protocol


class HttpDispatcherProtocol(asyncio.Protocol):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like such a hackish solution.

If you need a protocol that redirects everything to its _handler (a bad name BTW) please write it explicitly without redirecting attrs setters/getters. The used approach makes debugging very complex.

Comment thread aiohttp/http_protocol.py
# all incoming data and callbacks.
self._handler.connection_made(transport)

def __getattribute__(self, name: str) -> Any:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Breaks uvloop even with HTTP/2 off: uvloop caches protocol.data_received before connection_made(), when _handler is still None, so all response data is dropped and requests hang (plain http://, UnixConnector). At least call transport.set_protocol(self._handler) in connection_made().

Comment thread aiohttp/connector.py
else:
return None

conns = target[key].copy()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Race: the live deque still holds proto during await trace.send_connection_reuseconn(), so a concurrent _get() can take the same HTTP/1.1 connection, and the write-back of conns drops connections released meanwhile. Please mutate the live deque before any await, as before.

self.hpack_encoder = Encoder()
# set limits to prevent zip bombs
self.hpack_decoder = Decoder(
max_header_list_size=self.local_settings[Setting.MAX_HEADER_LIST_SIZE],

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a zip-bomb limit: MAX_HEADER_LIST_SIZE is 2**32 - 1, overriding hpack's 64 KiB default, and CONTINUATION accumulation is unbounded. A hostile server can OOM the client. Please bound both from the session header limits; THREAT_MODEL.md needs an update too.

@Moist-Cat

Copy link
Copy Markdown
Author

Thank you for taking the time to review this, @asvetlov .

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants