Streams and flow control
Streams are the byte and message paths that connect the HTTP parser to client responses and server requests. They let application code consume data at its own pace while the protocol and transport limit buffered data, pause input when needed, and report completion or failure. This page complements HTTP transport and streaming and HTTP parsing and message writing.
Stream data model
Stream readers
home/…/streams.py provides StreamReader, the byte stream exposed as ClientResponse.content and BaseRequest.content. A reader stores incoming body bytes until an application read consumes them, and it supports reads by size, delimiter, exact length, arrival order, or HTTP chunk boundary.
The reader has one pending asynchronous read at a time. A protocol feed wakes that read when data, an HTTP chunk boundary, or EOF arrives. Delimiter reads continue across input blocks, so a separator split between two received blocks is still recognized. Application code normally gets readers from a request or response rather than creating them directly.
| Read form | Result |
|---|---|
read(n) | Up to n available bytes. With n < 0, reads until EOF. |
readany() | The next available block. |
readexactly(n) | Exactly n bytes or IncompleteReadError if EOF comes first. |
readline() / readuntil(separator) | Data through a line ending or separator. Partial data is returned at EOF, and the separator can span received blocks. |
readchunk() | Data plus a flag for the end of an HTTP transfer chunk. |
Async iteration maps these forms to common consumption patterns. The default iterator reads lines. iter_chunked() limits each result, iter_any() follows arrival blocks, and iter_chunks() retains HTTP chunk-end signals.
References: aiohttp/streams.py• L71-186 aiohttp/streams.py• L378-532 aiohttp/client_reqrep.py• L543-560 aiohttp/web_request.py• L664-677
Data queues
DataQueue is the message-level counterpart to StreamReader. It holds parsed objects such as response headers paired with their body reader, or other protocol messages, and gives them to one asynchronous reader in order. The queue wakes its reader when a message arrives and raises EofStream only after all queued messages have been consumed.
This separation is important: a response or request can be queued as a message while its body remains a separate stream. The client uses this boundary in ResponseHandler; the server keeps parsed requests in its request queue before dispatch.
References: aiohttp/streams.py• L695-756 aiohttp/client_proto.py• L32-44 aiohttp/web_protocol.py• L129-135
Input buffering and backpressure
Read-side flow control
Read-side backpressure keeps a fast peer from filling memory while application code reads slowly. Each body reader has a low-water mark and a high-water mark. A size-limited read can raise these marks to match the consumer's requested size. The protocol pauses transport input when buffered body data rises above the high mark, then resumes it after consumption lowers the buffer below the low mark.
The transport can also pause for a protocol-owned buffer, such as a server message queue or an upgrade tail that is not ready for the next stage. The protocol keeps this hold separate from the body-reader hold and resumes transport input only when both conditions allow it. This prevents one consumer from releasing input while another buffer is still full.
HTTP chunk boundaries add a second guard. Many small boundaries can make each read expensive even when the byte count is modest, so the protocol can also pause until the application consumes enough chunk markers. A transport that does not support pause and resume is allowed to continue without this protection.
The flow from socket input to application consumption is coordinated across the transport, parser, and reader as shown here.
flowchart LR
T[Transport receives bytes] --> P[HTTP protocol and parser]
P --> R[StreamReader buffer]
R --> A[Application reads body]
R -- above high water --> X[Pause transport and parser]
A -- below low water --> Y[Resume parser and transport]
X --> Y
Q[Protocol-owned buffer is full] --> X
Q -- buffer drains --> Y
References: aiohttp/streams.py• L109-143 aiohttp/streams.py• L285-347 aiohttp/streams.py• L555-584 aiohttp/base_protocol.py• L68-120
Parser buffering
The HTTP parser may receive more bytes than the current body or message needs. It retains the unused tail for the next message, and it retains partial lines or partial chunk syntax until more input arrives. When a body reader is full, the payload parser stops processing and marks pending input so the protocol can continue from the same point after the reader drains.
Compression does not remove this control boundary. The decompression layer feeds output to the same reader and limits the amount of output produced per pass, which prevents a compressed input block from expanding into an unbounded single operation.
References: aiohttp/http_parser.py• L329-363 aiohttp/http_parser.py• L518-579 aiohttp/http_parser.py• L938-968 aiohttp/http_parser.py• L1113-1128
Message queue flow control
The server applies backpressure to parsed but not yet handled pipelined requests. It pauses transport input when the request queue reaches its limit, then releases one parser slot as the handler takes a request. Input resumes only after the queue falls below a lower threshold, which lets a small batch drain before reading starts again. The parser also stops emitting new messages at the limit, so the queue and parser do not create two separate unbounded buffers.
The same protocol buffer hold covers data that sits between HTTP and an upgraded protocol. The server limits this message tail while it waits for the next protocol stage. If the upgrade is not accepted, the server returns the tail to HTTP parsing so those bytes remain part of the normal request flow.
References: aiohttp/web_protocol.py• L43-47 aiohttp/web_protocol.py• L223-239 aiohttp/web_protocol.py• L465-604 aiohttp/web_protocol.py• L718-756 aiohttp/base_protocol.py• L76-120
Output flow control
Write-side backpressure
The same protocol object coordinates data sent to the peer. When the transport signals that its output buffer is full, the protocol marks writing as paused. StreamWriter writes bytes to the transport and periodically waits for the protocol to become writable through drain().
This makes await writer.write(data) the normal pacing point for streamed responses and other HTTP output. write_eof() sends the final body marker when needed and also waits for pending output before it reports completion. Server response writes use this writer through StreamResponse; client request bodies use the same transport contract.
References: aiohttp/base_protocol.py• L49-64 aiohttp/base_protocol.py• L111-156 aiohttp/http_writer.py• L168-221 aiohttp/http_writer.py• L276-365 aiohttp/web_response.py• L449-487
Completion and failure states
EOF behavior
EOF means that the protocol has no more body bytes to feed. It does not discard bytes already buffered. Reads return those bytes first, then return b""; readexactly() instead raises IncompleteReadError when the buffered bytes do not satisfy its requested size.
is_eof() reports that EOF has been signaled. at_eof() reports the stronger state in which EOF has been signaled and the buffer is empty. wait_eof() waits for the signal without consuming the body. For readchunk(), (b"", False) is the final stream result; an empty result with the end flag set marks an HTTP chunk boundary rather than stream EOF.
The parser signals EOF from the HTTP framing rules. A known content length completes after the declared bytes, chunked transfer completes after its final chunk and trailers, and responses read until connection close complete when the connection is lost cleanly. Missing bytes in a fixed-length or chunked body are errors rather than normal EOF.
References: aiohttp/streams.py• L217-258 aiohttp/streams.py• L241-247 aiohttp/streams.py• L479-517 aiohttp/http_parser.py• L907-936 aiohttp/http_parser.py• L1100-1128
Exceptions and connection loss
A stream exception is terminal for that data path. It wakes a pending reader and causes later reads to raise the same failure. Connection loss applies this rule to both the message queue and the active body so callers do not wait forever for data that cannot arrive.
The client turns an incomplete response into a payload or connection error and closes or releases the connection instead of returning it to the pool as reusable. The server can spend a short lingering period consuming an unread request body after the handler finishes; if the body still does not complete, it closes the connection. These actions protect the next request from receiving bytes that belong to the previous one.
References: aiohttp/streams.py• L190-206 aiohttp/streams.py• L717-753 aiohttp/client_proto.py• L115-188 aiohttp/client_reqrep.py• L568-605 aiohttp/web_protocol.py• L423-453 aiohttp/web_protocol.py• L810-846
Client and server transport coordination
Client response path
The client protocol turns transport bytes into a response message and a body reader. It places the response message in a data queue, then feeds later bytes to the body parser. As the caller reads ClientResponse.content, the reader controls input flow; when the body reaches EOF, the response can release the connection for reuse.
The response path also supports a response read limit and optional decompression. These settings shape reader buffering and parser work without changing the application-facing reader contract. A caller that releases a response before reading it marks the content closed so an unfinished body cannot silently remain attached to a pooled connection.
References: aiohttp/client.py• L234-254 aiohttp/client_proto.py• L229-261 aiohttp/client_proto.py• L301-373 aiohttp/client_reqrep.py• L543-580 aiohttp/client_reqrep.py• L663-705
Server request path
The server protocol turns transport bytes into queued request messages and body readers. Its handler removes one message at a time, dispatches the request, and then either confirms that the body reached EOF or consumes the unread body during the lingering period. This keeps request boundaries safe across persistent connections.
The response uses the write-side half of the same protocol. The handler writes through a StreamWriter, and the transport can slow that work by making drain() wait. A connection closes when keep-alive is not safe or when a body, parser, or transport error prevents reuse.
References: aiohttp/web_protocol.py• L465-604 aiohttp/web_protocol.py• L718-846 aiohttp/web_protocol.py• L879-914 aiohttp/web_request.py• L679-708
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the high-water and low-water rules aligned between
StreamReader, the payload parser, andBaseProtocol; a mismatch can leave input paused or allow input to grow without bound. - Keep body-reader pauses and protocol-buffer pauses independent, and resume transport input only after both holds are clear.
- Preserve the pending-input resume path in
HttpPayloadParserwhen changing body framing or decompression. It carries bytes that were received but could not yet be fed to the reader. - Preserve separator matching across buffer boundaries when changing
StreamReader.readuntil(); a delimiter can start in one received block and finish in the next. - Keep server message-queue limits aligned with parser message accounting and the queue-drain point in
RequestHandler.start(). - Keep the queue pause threshold and its lower resume threshold aligned so parser slots are released before transport input resumes.
- Preserve the upgrade-tail replay path when changing protocol transitions. Bytes behind a rejected upgrade must return to HTTP parsing.
- Preserve the distinction between stream EOF and an HTTP chunk boundary. Client response reuse and async iteration depend on it.
- Keep connection-loss exception propagation synchronized between
ResponseHandler, its body reader, and the response release path. - When changing writer buffering or
drain()behavior, check both streamed server responses and client request-body producers because they share the transport write contract.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Application reads a fixed number of bytes after the peer sends a shorter body | readexactly() raises IncompleteReadError instead of returning a short body | Use a size-limited read when short final bodies are valid. |
| A body reader stays above its high-water mark | Transport input pauses and the parser stops feeding the body | Continue consuming the reader so it can cross the low-water mark. |
| A protocol-owned buffer stays full while the body-reader pause clears | Transport input remains paused | Drain every buffer that owns a pause before expecting input to resume. |
| A server request queue reaches its limit and its lower resume point is not reached | The transport stays paused while queued requests wait for handlers | Ensure request handling removes messages and releases parser slots. |
| Bytes remain in an upgrade tail after the upgrade is rejected | Pipelined HTTP requests can remain hidden from the HTTP parser | Replay the tail through HTTP parsing before the connection continues. |
| A separator is split across received blocks and the reader checks only the current block | readuntil() can wait for more data or return data without the complete delimiter | Match the end of the prior block with the start of the current block. |
| A server handler leaves request data unread | The connection may close after lingering rather than safely serving another request | Read or release the request body before relying on keep-alive. |
| A response is released before its body is complete | The body becomes unusable and the connection is not treated as a clean reusable response | Consume the body when reuse is needed, or close the response deliberately. |
| A producer ignores write backpressure | Transport output can grow while the peer is slow | Await the writer's pacing and final write_eof() operation. |
| The peer disconnects during a body or while a reader waits | Pending and later reads receive a connection or payload error | Handle the error and do not treat the connection as reusable. |
Key files
| File | Why to read it |
|---|---|
| aiohttp/streams.py | Defines the byte reader, delimiter reads across received blocks, EOF states, chunk boundaries, and message queue contract. |
| aiohttp/base_protocol.py | Coordinates body and protocol-buffer read holds with transport pause and resume, and exposes the writer drain signal. |
| aiohttp/http_parser.py | Shows how HTTP framing, parser tails, payload limits, and EOF feed the streams. |
| aiohttp/client_proto.py | Shows how client response messages and body readers share one connection protocol. |
| aiohttp/web_protocol.py | Shows server request queues, pipelining limits, upgrade-tail handling, lingering body reads, and response coordination. |
| aiohttp/http_writer.py | Defines output buffering, write backpressure, and message completion. |
| aiohttp/client_reqrep.py | Connects the client-facing response lifecycle to body EOF, release, and connection reuse. |
| aiohttp/web_request.py | Connects the server-facing request lifecycle to body reads and release. |