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 / client-request-lifecycle

Client request and response lifecycle

ClientSession manages an outbound HTTP exchange from request setup to response cleanup. It applies session and call policy, creates one request attempt, sends it through the connector, follows allowed redirects, and returns a ClientResponse whose body still controls connection reuse.

Lifecycle overview

The exchange has two ownership stages. The session owns request and connection setup until it returns a response. The caller then owns the response body and must consume or end it so the connection can be reused or closed.

The diagram shows the main path and the cleanup paths for one exchange.

flowchart TD
    A[ClientSession request] --> B[Resolve URL and request policy]
    B --> C[Create request attempt]
    C --> D[Acquire connection and send request]
    D --> E[Start response]
    E --> F{Allowed redirect?}
    F -- Yes --> G[Release intermediate response]
    G --> C
    F -- No --> H[Return final response]
    H --> I{Consume or end response}
    I -- Read to end --> J[Reuse connection when safe]
    I -- Release --> J
    I -- Close or failure --> K[Close connection]

Request construction

Session request boundary

The request boundary in aiohttp/client.py• L488-748 combines the URL, method, body, headers, cookies, timeout, and transport choices into one exchange. It rejects a closed session and invalid combinations before it asks the connector to connect.

The session keeps one total timeout for request setup, redirects, response reads, and body consumption. It also creates the trace context and response rules that apply to every attempt in the exchange.

References: aiohttp/client.py• L488-613 aiohttp/client.py• L630-748

ClientRequest object

ClientRequest represents one concrete wire attempt. It carries the final URL and method for that attempt, the headers and body to send, and the response settings needed to interpret the reply.

The session can create a new ClientRequest after a redirect or a retry. The request body remains a shared resource across those attempts when it must be replayed, so a consumed body can stop the next attempt instead of being sent as an empty body.

When a request body is replaced, ClientRequest.update_body() closes the old payload before it installs the new one. This keeps file, stream, and other payload resources tied to the request lifecycle rather than leaving them behind when middleware changes a body.

References: aiohttp/client.py• L751-785 aiohttp/client.py• L800-812 aiohttp/client_reqrep.py• L1289-1313 aiohttp/client_reqrep.py• L1497-1557

Outbound exchange

Connection acquisition and send

The connector supplies a connection that matches the request destination and policy. The request then sends its headers and body through that connection. Connection routing and proxy choice are described in Client connectivity and proxies.

The response starts only after the request has been sent and response headers are available. If connecting, sending, or response start fails, the session closes the response, connection, and request body before it reports the error. A configured upload tracker also marks each attempt boundary so upload state does not outlive the exchange.

References: aiohttp/client.py• L282-304 aiohttp/client.py• L751-812 aiohttp/client_reqrep.py• L1644-1740

ClientResponse start

ClientResponse is the caller-facing result of a completed header exchange. It carries the status, headers, request information, redirect history, and a stream for the response body.

The body stays tied to the connection until the stream reaches its end or the response is released or closed. This makes response cleanup part of connection-pool behavior rather than only a data-reading concern.

References: aiohttp/client.py• L288-304 aiohttp/client_reqrep.py• L703-754

Redirect handling

Redirect decision

When redirects are enabled, ClientSession treats a redirect response as an intermediate result. It records the response in history, updates cookies, determines the next URL, and starts another request within the same total timeout.

The redirect status controls whether the next attempt keeps its method and body:

  • 303 changes a non-HEAD request to GET.
  • 301 and 302 change POST to GET.
  • 307 and 308 preserve the method and body.

The intermediate response is released before the next attempt. A preserved body must be replayable. If it was consumed, the session raises ClientPayloadError rather than sending an incomplete request.

References: aiohttp/client.py• L821-879 aiohttp/client_reqrep.py• L1435-1479

Redirect trust boundary

The next target must be a valid HTTP or HTTPS URL. A relative target is resolved against the current URL. An invalid target or an unsupported scheme ends the exchange and cleans up the current request and response.

When a redirect crosses origins, the session removes the old authorization, cookie, and proxy-authorization headers before the next attempt. URL credentials can set authorization for the current attempt, but the initial request rejects them when an explicit authorization header is already present. Environment proxy settings are resolved again for each redirect when environment trust is enabled, so proxy credentials do not carry over to an unrelated target.

The configured redirect limit is an error boundary. When the limit is reached, the session closes the current resources and raises TooManyRedirects with the request information and redirect history.

References: aiohttp/client.py• L675-736 aiohttp/client.py• L833-927

Response consumption

Response body access

The response offers both a stream and convenience readers. A full read caches the body for later text or JSON decoding. Chunked reads keep control with the caller and allow back-pressure while the response remains active.

Reading to the end releases a reusable connection automatically. A caller that stops before the end must release or close the response.

References: aiohttp/client_reqrep.py• L756-768 aiohttp/client_reqrep.py• L877-951

Release and close

release() ends response ownership while allowing a safe connection to return to the pool. close() ends the response and closes its connection. Both paths stop unfinished work, but only the first preserves reuse when the exchange is safe.

The response context manager performs response cleanup on exit. The request context manager awaits the request and then delegates to that response context, which makes async with session.get(url) the safe form when the response does not need to outlive the block.

References: aiohttp/client_reqrep.py• L773-837 aiohttp/client_reqrep.py• L953-968 aiohttp/client.py• L1545-1579

Error boundaries

Pre-response failures

Before headers arrive, failures come from request validation, connection setup, or request-body sending. The session does not retry connector setup errors. It can retry one failed persistent connection for an idempotent method, but only while the body can still be reused.

The retry stays inside the same total timeout and reuses the request payload after the failed writer settles. A consumed payload ends that retry path.

References: aiohttp/client.py• L553-640 aiohttp/client.py• L790-818 aiohttp/client_reqrep.py• L1677-1740

Post-response failures

After headers arrive, status handling and body handling form a separate boundary. A response status is not a transport failure by itself. When enabled, raise_for_status converts an HTTP error status into a response error before the response is returned.

A failure during response handling closes the response. This prevents a partial or damaged exchange from returning its connection to the pool as if it were reusable.

References: aiohttp/client.py• L929-957 aiohttp/client_reqrep.py• L877-951

Cleanup on failure

The session closes its timeout handle, response, and request body on every failed exchange. It also emits the request exception through the active trace context. This cleanup applies to validation reached inside the request loop, redirect errors, send failures, and response-status checks.

The returned response is different: after the session returns it, the caller must finish its lifetime. Dropping an active response can keep a connection acquired and can produce an unclosed-response warning.

References: aiohttp/client.py• L959-981 aiohttp/client_reqrep.py• L633-648

Session lifetime

Session context

The session context manager closes the session when its block ends. Closing an owned session closes its connector and releases its acquired resources. A session that uses an external connector does not own that connector.

The one-shot aiohttp.request() context creates a session for one exchange. It closes the response and session when the block ends, and it closes the session if request creation fails.

References: aiohttp/client.py• L1436-1452 aiohttp/client.py• L1533-1543 aiohttp/client.py• L1586-1615 aiohttp/client.py• L1631-1689

Change checklist

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

  • Changes to the request loop must preserve the single timeout scope across retries, redirects, and response use.
  • Changes to redirect method or credential rules must preserve body replay and cross-origin header removal.
  • Changes to retry behavior must keep connector setup errors out of the retry path and must not resend a consumed body.
  • Changes to request body replacement must close the previous payload before a new payload takes ownership.
  • Changes to response or request context managers must keep response cleanup and connector ownership aligned on both success and failure.
  • Changes to failure cleanup must close the request body and response before the exception leaves the session boundary.
  • Changes to upload-attempt tracking must finalize both successful and failed attempts without allowing a tracker to remain bound to another request.

Important failure modes

TriggerConsequenceGuard
The caller abandons an active response.The connection can stay acquired and the session can report an unclosed response.Read the body, release or close the response, or use its context manager.
A redirect preserves a consumed request body.The next attempt raises ClientPayloadError instead of sending an empty body.Use a replayable body or disable redirects.
A redirect target is invalid, non-HTTP, or over the limit.The exchange raises a redirect error and cleans up the intermediate response.Validate redirect targets and set a suitable limit.
A persistent connection fails during an idempotent request.The session may retry once, but a consumed body cannot be resent.Use a replayable body when retry can matter.
Middleware replaces a request body without closing the old payload.A file, stream, or other payload resource can remain open.Use await request.update_body(...) for body replacement.
Response status checking raises after a response arrives.The response is closed before the error leaves the request boundary.Catch the response error and do not assume the response remains usable.
The session closes while a request is starting.New work is rejected or the connector reports a connection failure.Keep the session open until all response work ends.
Upload tracking is bound to more than one active request.Request setup fails before the tracker can safely report attempt state.Give each request its own tracker and let its lifecycle reach finalization.

Key files

FileWhy to read it
aiohttp/client.pyDefines session request setup, retries, redirects, timeout scope, error cleanup, upload-attempt tracking, and context managers.
aiohttp/client_reqrep.pyDefines request body ownership, response ownership, body access, release, close behavior, and upload progress boundaries.
aiohttp/client_proto.pyConnects incoming protocol data to response headers and the streaming body.
aiohttp/connector.pyExplains how connections are acquired, reused, released, and closed.
aiohttp/client_exceptions.pyDefines the error families at request, connection, redirect, payload, and response-status boundaries.

See HTTP client for the wider client model, Client connectivity and proxies for connection routing, and Client state and interception for cookies, headers, middleware, and tracing.