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 / server-request-processing

Server request processing

The server request path turns bytes from a client connection into a request that an application can handle, then turns the handler result into an HTTP response. It protects the connection while it parses input, applies application policy, translates failures into status responses, and completes or closes the connection. See Web server for the wider server model, Server routing and responses for route selection and response types, and Server lifecycle and deployment for connection and shutdown context.

Request lifecycle

Request flow

The request flow has one owner at each stage. The connection protocol reads and parses wire data, bounds queued requests, and runs request work. The application adds request meaning, and the response layer sends the final status, headers, and body.

This diagram shows how an inbound request becomes a handler result and then a response on the same connection.

flowchart LR
    A[Client bytes] --> B[HTTP protocol parser]
    B --> C[Raw message and body stream]
    C --> D[Request object]
    D --> E[Route resolution]
    E --> F[Middleware chain]
    F --> G[Application handler]
    G --> H{Result or exception}
    H -->|response| I[Prepare response]
    H -->|HTTP exception| J[Status response]
    H -->|timeout or other error| K[Error response]
    J --> I
    K --> I
    I --> L[Write headers and body]
    L --> M[Access log and connection decision]

The protocol can process more than one request from a connection. It queues parsed messages up to a fixed bound and pauses transport reads when the queue is full. It resumes reads after the queue drains below a lower threshold. This limits memory use when a handler is slow or when a client sends pipelined requests faster than the server can handle them.

References: aiohttp/web_protocol.py• L473-507 aiohttp/web_protocol.py• L727-756 aiohttp/web_protocol.py• L854-869

Connection input

The HTTP parser checks the request line, target form, version, headers, and transfer rules before it gives the protocol a request message. It also creates a body stream for data that follows the headers. For HTTP/1.1, a missing Host header is a parse error.

Malformed wire data does not enter normal application dispatch. The protocol stores the parse failure with an empty or placeholder message so that it can send a 400 Bad Request response through the normal response path. This keeps protocol errors separate from errors raised by application code.

When a protocol upgrade stops HTTP parsing, bytes after the upgrade boundary remain buffered until the new protocol accepts the connection. If the upgrade is rejected, the protocol sends those bytes back through HTTP parsing so that pipelined requests are not lost. A parse error in that buffered data follows the same controlled 400 Bad Request path.

References: aiohttp/web_protocol.py• L490-542 aiohttp/web_protocol.py• L558-617

Request context

Request object

The request object is the application-facing view of the parsed message. It carries the method, URL, version, headers, connection details, body stream, application state, and the eventual route match.

The server creates this object from the raw message and its body stream before it calls the application. A request may hold a pre-handler error when parsing failed. In that case, the application still receives a request-shaped context, but dispatch selects an error match instead of a normal route. The request keeps the raw target path separate from the full URL, so an absolute-form target does not add its authority to the path used by application code. For absolute-form and authority-form targets, the target authority supplies the request host, including a non-default port, instead of allowing the Host header to replace it.

The request exposes conditional request metadata as typed values. In particular, If-Range can represent either an HTTP date or an entity tag. File-serving response logic uses that value to decide whether a byte range remains valid for the selected representation.

References: aiohttp/web_request.py• L167-226 aiohttp/web_request.py• L445-543 aiohttp/web_request.py• L628-643 aiohttp/web_protocol.py• L762-782

Request body

The body is a stream because its size and arrival time are controlled by the client. Handlers choose when to read it. The request API can expose raw bytes, decoded text, JSON, form data, or multipart data while applying the configured client size and form-field limits.

Body errors become HTTP errors when the handler reads the body. Multipart forms expose uploaded files as file values, and the request closes their temporary resources when request processing finishes. A handler that does not consume the full body does not leave it available for the next request: after the response, the protocol drains the remaining data for a short period or closes the connection when the body does not finish. If this drain completes a deferred protocol upgrade, the protocol then replays the buffered bytes as HTTP input when the upgrade was not accepted.

References: aiohttp/web_request.py• L674-757 aiohttp/web_request.py• L759-893 aiohttp/web_request.py• L921-929 aiohttp/web_protocol.py• L819-851

Application dispatch

Route resolution

The application resolves the request URL and method before it calls a handler. The resulting match records the selected handler, route parameters, and the application context that owns the match. A missing route or unsupported method therefore becomes a controlled HTTP result rather than an unhandled lookup failure.

An Expect request header adds an early decision point. The matched route can answer before the main handler runs. If it returns no response, normal middleware and handler processing continues.

References: aiohttp/web_protocol.py• L683-708

Middleware chain

Middleware is the policy layer around a handler. It can inspect or change the request, stop the flow with its own response, or call the next layer and inspect the result on return. The application builds the chain from the matched route and all parent applications when sub-applications are used.

The built-in application context layer sets the current application while a handler runs and restores the prior value afterward. This lets nested applications share one request flow while keeping request configuration tied to the active application.

Path normalization is an example of an early policy. When a path does not resolve, it can try a normalized path and raise a redirect if that path does resolve. See Server routing and responses for the route behavior behind this decision.

References: aiohttp/web_protocol.py• L683-708 aiohttp/web_request.py• L985-990

Handler dispatch

The final handler receives the request and returns a stream response. The handler may return a complete response for a small body or a response that writes data over time. The request task remains tied to the connection so cancellation and client disconnects can reach the active work.

The server does not treat a handler return value as a wire response until the response stage validates and prepares it. A missing or invalid response is converted to an internal server error before any response bytes are sent.

References: aiohttp/web_protocol.py• L683-725 aiohttp/web_protocol.py• L784-805 aiohttp/web_protocol.py• L884-913

Error translation

HTTP exception handling

An HTTP exception is a deliberate response decision. It carries a status, reason, headers, optional text, and cookies. When a handler or middleware raises one, the protocol converts it into a response with those values and sends it through the same preparation path as a returned response.

Parse failures use the same status-response path after the protocol marks them as pre-handler errors. This gives clients a normal HTTP error while the server can retain the original parse cause for logging.

References: aiohttp/web_protocol.py• L696-708 aiohttp/web_protocol.py• L773-779

Server error handling

Timeouts become 504 Gateway Timeout responses. Other uncaught exceptions become 500 Internal Server Error responses. The error response is forced to close the connection because the request may have left the application or response state unsafe for reuse.

If response bytes already went to the client, the server cannot replace them with a second error response. It raises a connection error instead and lets connection handling stop the exchange.

References: aiohttp/web_protocol.py• L709-719 aiohttp/web_protocol.py• L921-972

Response emission

Response preparation

Response preparation changes an application response into an HTTP message. It binds the response to the request writer, runs response-prepare signals, selects body framing, and adds the headers needed for the selected HTTP version and connection mode.

The response layer also applies content compression when enabled and the request accepts a supported encoding. A response with no known length uses chunked framing on HTTP/1.1 when a body is allowed. Statuses and methods that cannot carry a body suppress body framing instead.

References: aiohttp/web_protocol.py• L884-913 aiohttp/web_request.py• L985-990

Body emission

After preparation, the handler can write body chunks through the response writer. The final end-of-body write marks the response complete and records the number of bytes sent. The response rejects writes before preparation and after completion so the wire message has one clear lifetime.

The protocol completes this step even when the handler returned a response without writing a body. It then records access information and reports whether the client disconnected during emission.

References: aiohttp/web_protocol.py• L884-919

Connection reuse

The response keep-alive decision combines the request's HTTP rules with the response framing and any explicit close decision. A reusable connection waits for the next request until its idle timeout. A non-reusable connection closes after the current exchange.

The protocol also protects the next request from unread bytes. It drains a still-arriving body during a limited lingering period. If the body remains incomplete, it marks the connection for close instead of allowing the bytes to affect a later request. Buffered bytes behind a deferred upgrade are replayed through HTTP parsing when the upgrade does not take effect.

References: aiohttp/web_protocol.py• L816-876 aiohttp/web_protocol.py• L558-617 aiohttp/web_request.py• L620-623

Change checklist

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

  • If parser output or parse-error handling changes, keep the request factory and application error-match path aligned with the raw message and pre-handler error contract.
  • If request body limits or body decoding rules change, check both direct body reads and multipart reads. They must agree on the status raised for an oversized body or form and on cleanup of uploaded file resources.
  • If request target parsing changes, keep the relationship between absolute-form and authority-form targets, target authority, Host, raw_path, and route matching consistent. A target port must remain part of the request host when the protocol requires it.
  • If request conditional-header parsing changes, keep the typed If-Range value aligned with file range selection. Dates and entity tags must not be treated as the same validator.
  • If middleware order or sub-application handling changes, verify that current-application state and route match data still describe the handler that runs.
  • If response framing or compression changes, check the relation between content length, chunked transfer, empty-body statuses, and keep-alive decisions.
  • If response preparation changes, keep response-prepare signals before header emission so listeners can still change the outgoing response.
  • If error translation changes, preserve the distinction between an HTTP exception, a timeout, an uncaught exception, and an error after response bytes were sent.
  • If upgrade handling changes, preserve the boundary between upgraded-protocol bytes and HTTP bytes. Rejected upgrades must return buffered tail data to the HTTP parser.

Important failure modes

TriggerConsequenceGuard
Invalid request line, headers, or transfer rulesThe request skips normal dispatch and receives a 400 Bad Request; the connection may close.Strict request parsing and the pre-handler error path.
More pipelined messages arrive than the queue limit allowsThe transport stops reading until the queue drains below its resume threshold.Bounded message queue with pause and resume flow control.
Handler reads more than the client size limitBody access raises 413 Request Entity Too Large.Size checks in raw, form, and multipart body reads.
A request exceeds the form-field limitForm parsing raises 413 Request Entity Too Large.Field-count checks for URL-encoded and multipart forms.
An absolute-form or authority-form target includes a port that is ignored during request constructionHost-based application behavior can use the wrong authority or port.Preserve the target authority as the request host and keep its non-default port.
Handler raises an HTTP exceptionThe exception becomes its declared status response.Exception translation in the request protocol.
Handler times out or raises an unexpected exceptionThe client receives a 504 or 500 response and the connection is closed.Timeout and general exception branches in request handling.
Handler returns no response or the client disconnects during outputThe server emits a 500 response when possible or stops the exchange.Response validation and connection-error handling during finalization.
Response leaves a body unread after the handler returnsThe connection is drained briefly or closed before reuse.Lingering body read and incomplete-payload close decision.
A protocol upgrade is rejected after later bytes were bufferedThe later HTTP requests could be lost or treated as upgraded-protocol data.Replay the buffered tail through the HTTP parser after the upgrade request is complete.
Multipart request processing creates temporary uploaded-file resourcesResources remain open if request finalization does not run.Request finalization closes file values before response preparation.
A client sends an invalid If-Range valueFile range logic does not apply the Range header and returns the full representation.Request parsing exposes only a valid HTTP date or entity tag.

Key files

FileWhy to read it
aiohttp/web_protocol.pyFollow the per-connection loop from queued messages through handler execution, error translation, response finalization, upgrade-tail replay, and keep-alive.
aiohttp/web_request.pyLearn what application code receives and how it accesses body data, request targets, conditional metadata, and request state.
aiohttp/http_parser.pyUnderstand the boundary between HTTP wire validation, raw request messages, and body streams.
aiohttp/web_server.pySee how a server supplies the request factory and application handler to each connection protocol.
aiohttp/web_app.pyFollow route resolution, expectation handling, middleware composition, and handler dispatch.
aiohttp/web_middlewares.pySee the shared policy behavior that can redirect or wrap a handler before it runs.
aiohttp/web_response.pyUnderstand response preparation, HTTP framing, body writes, and end-of-body completion.
aiohttp/web_exceptions.pySee the HTTP exception values that handlers use to request status responses.
aiohttp/web_fileresponse.pySee how date and entity-tag validators control whether a file response uses a requested byte range.
docs/server-routing-and-responses.mdFollow route selection and response behavior that sit next to request dispatch.
docs/server-lifecycle-and-deployment.mdFollow the server-level connection, shutdown, and deployment context around this request path.