Introducing a new way to review your PRs.

Read the announcement

aio-libs / aiohttp

Asynchronous HTTP client/server framework for asyncio and Python

View on GitHub

19 documents · Updated Nov 23, 2026

docs / http-transport

HTTP transport and streaming

The HTTP transport layer connects asyncio network transports to aiohttp's client and server message flows. It turns incoming bytes into validated HTTP messages with streaming bodies and turns outgoing headers and body data into framed bytes. It also limits read and write work so that a slow application or peer does not cause unbounded buffering.

Transport boundary

The transport boundary is the shared point between a socket and HTTP behavior. aiohttp/base_protocol.py provides the common protocol that owns the asyncio transport, tracks connection state, and coordinates read and write pauses. Client and server protocols add their own message queues and request or response lifecycles around this boundary.

The boundary has separate holds for application-level reading and for data that the protocol has buffered but cannot yet hand to the next consumer. This separation lets a body reader, a pipelined message queue, or an upgraded protocol pause the transport without losing the reason for the pause. aiohttp/base_protocol.py aiohttp/base_protocol.py

The public HTTP layer supplies the parser, raw message, version, and stream-writer types used by both sides. HTTP parsing and message writing explains the HTTP message rules. Stream flow control explains body readers, queues, and buffer limits.

Incoming data path

Incoming bytes move from the asyncio transport to a client or server protocol. The protocol passes them to an HTTP parser, which validates message metadata and returns a message plus a body stream. The client places responses in a response queue. The server places requests in a queue for its request loop. A single read can contain a partial message, several messages, or bytes beyond a protocol upgrade.

The parser has a Python path and a compiled path with the same message-and-payload contract. The compiled path is used when available, while aiohttp/http_parser.py remains the reference path and fallback. Both paths apply the same content-encoding policy before a body reaches the stream, including support for a bounded chain of supported codings. aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx

This diagram shows the shared path and the two application-facing outcomes.

flowchart LR
    A[Network transport] --> B[Client or server protocol]
    B --> C[HTTP parser]
    C --> D[Message metadata]
    C --> E[Streaming body]
    D --> F[Client response queue]
    D --> G[Server request queue]
    E --> H[Application consumer]
    C --> I[Upgrade or connection tail]

The client protocol uses ResponseHandler to adapt transport callbacks to queued response messages. It retains bytes that cannot yet be parsed or that arrived after an upgrade. The server protocol performs the same boundary work while also keeping parsed requests until the request handler can process them. aiohttp/client_proto.py aiohttp/client_proto.py aiohttp/web_protocol.py

Message boundaries

The parser separates the request or response line and headers from the body. It validates the message metadata, selects the body boundary, and returns raw metadata with a stream for the body. This lets the client or server start request or response work before it has received the full body. Strict request parsing rejects invalid header and framing combinations. Response parsing can use a more tolerant mode for common peer behavior. aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx

The body may use a declared length, chunked transfer, or connection end as its boundary. A completed body returns any bytes that belong to the next message. This supports persistent connections without merging two exchanges. The parser can also hold back new messages when the consumer queue reaches its configured limit. Body decoding can remove one or two supported content codings while preserving the same stream and boundary contract. aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx

References: aiohttp/http_parser.py• L216-295 aiohttp/http_parser.py• L383-641 aiohttp/http_parser.py• L643-694 aiohttp/http_parser.py• L926-1212 aiohttp/http_parser.py• L126-165 aiohttp/http_parser.py• L1260-1339 aiohttp/_http_parser.pyx• L455-584 aiohttp/_http_parser.pyx• L563-605 aiohttp/_http_parser.pyx• L638-761 aiohttp/_http_parser.pyx• L966-977 aiohttp/_http_parser.pyx• L1007-1025

Protocol upgrades

An accepted upgrade changes the meaning of later bytes from HTTP messages to the upgraded protocol. The HTTP layer waits for the required HTTP body to finish, then gives the retained tail to the upgraded reader. The server can replay that tail through the HTTP parser if the application rejects the upgrade, so pipelined HTTP bytes do not disappear. aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx aiohttp/client_proto.py aiohttp/web_protocol.py

References: aiohttp/http_parser.py• L471-517 aiohttp/http_parser.py• L630-641 aiohttp/_http_parser.pyx• L525-539 aiohttp/_http_parser.pyx• L687-761 aiohttp/client_proto.py• L342-356 aiohttp/web_protocol.py• L541-596

Outgoing data path

The stream writer is the outbound counterpart to the parser. A client request or server response gives it headers and body chunks. It buffers headers until it can combine them with initial body data, then applies the selected HTTP framing and optional compression before sending the result through the asyncio transport. It can also notify request or response observers as headers and body chunks pass through. HTTP parsing and message writing covers the wire-level rules and writer behavior.

This diagram shows how application output becomes a complete HTTP message.

flowchart LR
    A[Headers and body chunks] --> B[HTTP stream writer]
    B --> C[Length or chunk framing]
    B --> D[Optional compression]
    C --> E[Asyncio transport]
    D --> E
    E --> F[Peer]

Message completion

The writer makes message completion explicit. write() sends body data as it becomes available, while write_eof() can send a final body part before it closes the message. Completion flushes pending compression data and emits any required final marker, including the end marker for chunked messages. After completion, the HTTP message is complete and its body stream is closed. aiohttp/http_writer.py aiohttp/http_writer.py

References: aiohttp/http_writer.py• L159-219 aiohttp/http_writer.py• L247-339

Asynchronous flow control

Flow control limits data that waits between the peer, the protocol, and the application. Read flow control pauses the transport when a body, message queue, or upgrade tail reaches its limit. Write flow control waits when the transport output buffer is full. The protocol resumes each side only after the relevant consumer or transport makes progress. aiohttp/base_protocol.py aiohttp/http_writer.py

Read backpressure

StreamReader buffers body bytes for an asynchronous consumer and resumes the transport after the buffer falls below its low-water limit. For chunked bodies, it also limits the number of saved chunk boundaries so many small chunks cannot make one read block the event loop. The reader resumes only when both the byte buffer and chunk-boundary count are below their lower limits. The HTTP parser also limits parsed messages that remain unconsumed. On the server, the request loop frees a queue slot when it removes a request and resumes reading after the queue reaches its lower threshold. This bounds body data, chunk metadata, and pipelined request metadata. Decoded content also feeds the same bounded body stream, so compressed input cannot bypass the reader's pause state. aiohttp/streams.py aiohttp/streams.py aiohttp/streams.py aiohttp/streams.py aiohttp/streams.py aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx aiohttp/web_protocol.py aiohttp/web_protocol.py

The client applies the same limit to bytes held behind a response or protocol upgrade. While that tail remains too large to drain, the transport stays paused. Resuming the parser or upgraded reader also checks the tail hold before it resumes the socket. aiohttp/client_proto.py aiohttp/client_proto.py aiohttp/base_protocol.py

References: aiohttp/streams.py• L109-124 aiohttp/streams.py• L178-185 aiohttp/streams.py• L285-303 aiohttp/streams.py• L313-347 aiohttp/streams.py• L555-584 aiohttp/http_parser.py• L347-364 aiohttp/http_parser.py• L1285-1315 aiohttp/_http_parser.pyx• L585-611 aiohttp/_http_parser.pyx• L1007-1025 aiohttp/web_protocol.py• L44-47 aiohttp/web_protocol.py• L736-748 aiohttp/client_proto.py• L210-221 aiohttp/client_proto.py• L342-356

Write backpressure

The writer tracks bytes handed to the transport and can await drain() when the output buffer crosses its threshold. Message completion also drains before it returns. BaseProtocol stores the pending drain waiter and wakes it when the transport resumes or the connection closes. This makes large uploads and downloads yield to the event loop instead of treating socket writes as unlimited. aiohttp/http_writer.py aiohttp/http_writer.py aiohttp/http_writer.py aiohttp/base_protocol.py aiohttp/base_protocol.py

References: aiohttp/http_writer.py• L88-114 aiohttp/http_writer.py• L204-219 aiohttp/http_writer.py• L336-352 aiohttp/base_protocol.py• L51-66 aiohttp/base_protocol.py• L127-156

Connection lifetime and errors

EOF is a shared state change for the parser, body stream, and protocol. The parser marks a body complete when its framing ends or when an EOF-delimited body reaches connection end. The protocol then wakes pending consumers and stops treating the connection as reusable when the exchange is incomplete or unsafe to continue. The accelerated parser also passes errors from final body decoding to the waiting body reader before it drops its internal body reference. aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx aiohttp/streams.py aiohttp/client_proto.py

The server keeps a connection alive only when the response and request body permit another exchange. It can briefly drain an unread request body before closing. Client and server connection-loss paths propagate errors to pending body or message consumers and release write drain waiters. aiohttp/web_protocol.py aiohttp/client_proto.py aiohttp/base_protocol.py

Protocol errors remain visible to the relevant consumer. Invalid framing, incomplete content, decoding errors, read timeouts, and lost connections can end the current exchange. They also mark the connection for closure when it cannot be safely reused. aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx aiohttp/client_proto.py aiohttp/client_proto.py aiohttp/web_protocol.py

  • HTTP parsing and message writing explains message syntax, header rules, transfer coding, content coding, and the parser and writer paths.
  • Stream flow control explains body readers, data queues, buffering thresholds, EOF behavior, and pause or resume coordination.

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the parser's message-and-payload contract aligned with both the server request queue and the client response queue.
  • Keep the Python and compiled parser paths aligned on message boundaries, framing errors, content-encoding chains, upgrade tails, and pause or resume behavior.
  • Keep body framing symmetric between the parser and stream writer, especially for content length, chunked transfer, compression output, and end-of-message markers.
  • Keep supported content codings, their order, their maximum chain length, and the decompression error contract aligned across both parser paths.
  • Recheck every pause and resume path when changing body limits, message queue limits, upgrade tails, parser replay, or decompression stages.
  • Preserve bytes that follow a completed body or protocol boundary. They may begin the next HTTP message or upgraded protocol frame.
  • Keep connection-loss handling consistent for body readers, queued messages, upgraded readers, and write drain waiters.
  • Keep server queue low-water behavior aligned with parser message consumption so a full queue can drain and refill without a deadlock.

Important failure modes

TriggerConsequenceGuard
A body ends before its declared content lengthThe body fails as incomplete and the connection cannot safely continue the exchange.The Python and compiled payload parsers check the received count at EOF. aiohttp/http_parser.py aiohttp/_http_parser.pyx
A chunk size or chunk trailer has invalid syntaxThe payload receives a transfer error and parsing stops.Chunk size, CRLF, trailer count, and trailer length checks reject invalid input. aiohttp/http_parser.py
A request or response contains conflicting or unsafe framing headersThe message is rejected before its body can be assigned an unsafe boundary.Header validation rejects forbidden values, duplicate singleton headers in strict mode, and Transfer-Encoding with Content-Length. aiohttp/http_parser.py aiohttp/http_parser.py aiohttp/_http_parser.pyx
A supported content-encoding chain exceeds the safe depthThe body is rejected instead of being passed to a decoder with unbounded expansion.Both parser paths cap supported chains and raise a content-encoding error when automatic decoding is enabled. aiohttp/http_parser.py aiohttp/_http_parser.pyx aiohttp/_http_parser.pyx
A compressed stream ends before every decoding stage reaches its boundaryThe body fails as a truncated encoded stream.Each decoding stage checks completion at EOF and reports the coding that failed. aiohttp/http_parser.py
A server request queue or client upgrade tail reaches its high-water limitThe protocol stops reading from the transport until the queued work or tail falls below its resume condition.Server queue thresholds and client tail checks use the shared buffer pause state. aiohttp/web_protocol.py aiohttp/web_protocol.py aiohttp/client_proto.py aiohttp/base_protocol.py
The connection closes while a writer waits for drainA pending write task must not wait forever and receives a connection error when appropriate.connection_lost() resolves or fails the stored drain waiter. aiohttp/base_protocol.py
A body write exceeds the declared content lengthBytes beyond the remaining length are discarded instead of being sent as part of the next message.The writer tracks the remaining length and clips each outgoing body chunk. aiohttp/http_writer.py
A protocol upgrade is rejected after bytes arrive behind its boundaryThose bytes could be lost or misread as upgraded-protocol data.The server replays the retained tail through the HTTP parser when no upgrade reader accepts it. aiohttp/web_protocol.py

Key files

FileWhy to read it
aiohttp/base_protocol.pyDefines the shared asyncio transport boundary and the separate read and write pause state.
aiohttp/http_parser.pyDefines the parser contract and the Python path that turns incoming bytes into validated message metadata, streaming payloads, and bounded content decoding.
aiohttp/_http_parser.pyxDefines the compiled parser path used for the same message, payload, content-encoding, upgrade, and queue behavior when extensions are available.
aiohttp/http_writer.pyShows how headers and body chunks become framed outbound HTTP bytes and how completion and write backpressure work.
aiohttp/streams.pyShows body buffering, asynchronous reads, chunk-boundary tracking, EOF signaling, and read backpressure.
aiohttp/web_protocol.pyShows the server path from parsed requests to handlers, response writers, keep-alive, and upgrade-tail replay.
aiohttp/client_proto.pyShows the client path from parsed responses to response consumers, timeouts, upgrades, and connection errors.
aiohttp/http.pyProvides the shared public names for parsers, writers, raw messages, and HTTP versions.