HTTP client architecture
The HTTP client gives an async application one session-based interface for outbound HTTP calls. A session owns shared policy and resource state. A connector manages network access, while a request and response pair carries one exchange from request setup to response use.
Client API
The public client API is centered on aiohttp/client.py. ClientSession provides request methods, session defaults, resource ownership, and access to the resulting ClientResponse. The package also exposes a short-lived top-level request entry point for callers that do not need a long-lived session. That entry point creates and closes its own session and connector unless the caller supplies a connector. (aiohttp/client.py• L307-474, aiohttp/client.py• L1376-1457, aiohttp/client.py• L1620-1688)
Session API
The ClientSession is the boundary for shared client behavior. It combines a base URL with default headers, cookies, time limits, TLS choices, proxy policy, response policy, middleware, and trace settings. Related calls can therefore use one consistent context. A session must run with its connector on the same event loop. The caller must close the session when its work ends. (aiohttp/client.py• L307-474, aiohttp/client.py• L1436-1543)
References: aiohttp/client.py• L307-474 aiohttp/client.py• L1436-1543
Request and response contract
Each session call accepts an HTTP method and URL plus request data and per-call policy. It returns a ClientResponse through an async context manager. The caller can inspect status and headers, then consume text, JSON, or streamed bytes before the connection is released. (aiohttp/client.py• L503-548, aiohttp/client.py• L1376-1434, aiohttp/client_reqrep.py• L417, aiohttp/client_reqrep.py• L703-754, aiohttp/client_reqrep.py• L773-968)
The request object also provides the contract used by middleware that must change request data. A body change must use the async update path so the prior payload can close before the new payload is prepared. This protects file, stream, and other body resources during request changes. (aiohttp/client_reqrep.py• L1435-1557)
Callers that need upload progress can pass a fresh UploadTracker to one request. The tracker reports the current attempt, bytes confirmed as sent, and the final upload result. It keeps the upload contract clear when a connection retry or redirect sends the body again. (aiohttp/client.py• L515-548, aiohttp/client.py• L955-967, aiohttp/client_reqrep.py• L254-414, aiohttp/client_reqrep.py• L1644-1740)
References: aiohttp/client.py• L503-548 aiohttp/client.py• L955-967 aiohttp/client_reqrep.py• L254-414 aiohttp/client_reqrep.py• L417 aiohttp/client_reqrep.py• L703-754 aiohttp/client_reqrep.py• L773-968 aiohttp/client_reqrep.py• L1435-1557 aiohttp/client_reqrep.py• L1644-1740
Outbound call coordination
An outbound call moves through one coordinated path. The session applies shared and per-call policy. The connector obtains a usable connection. The request sends its headers and body. The response turns parsed network data into a readable client object.
The following diagram shows the main hand-off from the caller to the network and back to response use.
flowchart LR
Caller --> Session[ClientSession]
Session --> Request[ClientRequest]
Request --> Middleware[Client middleware]
Middleware --> Connector[Connector]
Connector --> Network[HTTP connection]
Network --> Protocol[ResponseHandler]
Protocol --> Response[ClientResponse]
Response --> Caller
Response --> Pool[Connection pool]
Request preparation
The session turns caller input into a complete request context before network work starts. It resolves the URL, combines headers and cookies, selects request limits and security settings, prepares the body, and records redirect and trace state. The resulting ClientRequest is the contract between session policy and the connector. (aiohttp/client.py• L515-775, aiohttp/client_reqrep.py• L1235-1313)
References: aiohttp/client.py• L515-775 aiohttp/client_reqrep.py• L1235-1313
Connection coordination
The connector is the session’s network resource manager. It reuses suitable open connections, waits when connection limits are reached, or creates a new connection with the required host, TLS, proxy, and server-name context. The session bridge applies response settings and starts the response after the connector returns a connection. After a response releases the connection, the connector either returns it to the keep-alive pool or closes it when the protocol or policy requires closure. See connectivity and proxies for the network path in more detail. (aiohttp/client.py• L280-304, aiohttp/connector.py• L288-391, aiohttp/connector.py• L646-703, aiohttp/connector.py• L747-859)
References: aiohttp/client.py• L280-304 aiohttp/connector.py• L288-391 aiohttp/connector.py• L646-703 aiohttp/connector.py• L747-859
Response handling
The response side separates protocol input from application use. ResponseHandler receives parsed response messages and payload data. ClientResponse exposes status, headers, cookies, history, and body readers. Reading to the end of the body or explicitly releasing the response tells the connector that the resource can be reused. Closing instead ends that connection. (aiohttp/client_reqrep.py• L417-754, aiohttp/client_reqrep.py• L756-891)
References: aiohttp/client_reqrep.py• L417-754 aiohttp/client_reqrep.py• L756-891
Request policies
The client applies policies that affect the full call rather than only one socket write. These policies keep request behavior consistent across redirects, retries, response decoding, and connection reuse.
Redirect and retry policy
Redirect handling stays inside the session because a redirect can change the URL, method, body, credentials, cookies, proxy choice, and request history. The session follows allowed HTTP redirects up to a limit and protects cross-origin requests by removing sensitive headers. It can also retry one failed persistent connection for an idempotent method. See request lifecycles for the ordered call stages. (aiohttp/client.py• L670-929)
References: aiohttp/client.py• L670-929
Timeout and payload policy
Timeouts cover the request as a whole and can also constrain connection and socket-read work. The total request timeout includes request setup, redirects, response work, and data consumption. The request payload policy determines how caller data is sent. It also determines whether the body can be replayed when a redirect or connection retry needs to send it again. The response policy controls decompression, body limits, and whether a status error is raised before the caller consumes the response. (aiohttp/client.py• L630-669, aiohttp/client.py• L931-979, aiohttp/client_reqrep.py• L1435-1479, aiohttp/client_reqrep.py• L1644-1740)
References: aiohttp/client.py• L630-669 aiohttp/client.py• L931-979 aiohttp/client_reqrep.py• L1435-1479 aiohttp/client_reqrep.py• L1644-1740
Client state and interception
The session keeps state that must persist across calls. It also provides hooks that can observe or wrap the call path. This shared state supports application-wide behavior. Interception must preserve the request-to-response contract and the session’s resource ownership. See client state and interception for the state and hook model.
Cookie state
The session cookie jar stores cookies received from responses and filters them into later requests for the target URL. This makes cookies part of session state rather than one-off request data. Callers can replace the jar or use a dummy jar when persistence is not wanted. (aiohttp/client.py• L429-434, aiohttp/client.py• L709-720, aiohttp/client.py• L821-824)
References: aiohttp/client.py• L429-434 aiohttp/client.py• L709-720 aiohttp/client.py• L821-824 aiohttp/cookiejar.py• L44-46
Middleware and tracing
Client middleware wraps the action that obtains a response. It can inspect or change a request and decide whether to continue to the next handler. The session selects per-request middleware when supplied and otherwise uses its session middleware. Tracing is an observation path for request, response, redirect, connection, and DNS events. It reports the call without replacing session resource ownership. See client state and interception for the state and hook model. (aiohttp/client.py• L778-791, aiohttp/client.py• L951-979, aiohttp/client_middlewares.py• L10-58, aiohttp/tracing.py• L44-123)
References: aiohttp/client.py• L778-791 aiohttp/client.py• L951-979 aiohttp/client_middlewares.py• L10-58 aiohttp/tracing.py• L44-123
Error boundary
Client errors distinguish failures before a response from failures after a response. Connection, DNS, TLS, proxy, timeout, URL, payload, status, and content-type failures use the client exception family. Callers can then handle network and response problems at the right boundary. (aiohttp/client.py• L280-304, aiohttp/client.py• L790-820, aiohttp/client.py• L959-979, aiohttp/client_exceptions.py• L22-50, aiohttp/client_exceptions.py• L54-66, aiohttp/client_exceptions.py• L111-141)
References: aiohttp/client.py• L280-304 aiohttp/client.py• L790-820 aiohttp/client.py• L959-979 aiohttp/client_exceptions.py• L22-50 aiohttp/client_exceptions.py• L54-66 aiohttp/client_exceptions.py• L111-141
Related client guides
Use these pages to continue from this architecture view:
- Request lifecycles — ordered request, redirect, retry, and response stages.
- Connectivity and proxies — connection creation, reuse, TLS, DNS, and proxy paths.
- Client state and interception — cookies, middleware, tracing, and shared session policy.
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the
ClientSessionrequest options aligned with the data required byClientRequestand the policy consumed by the connector. - Preserve the request-body replacement contract when changing payload creation or middleware support. The old payload must close before a new one replaces it.
- Preserve the response release and end-of-body contract when changing payload or protocol handling, because it controls connection-pool reuse.
- Keep redirect changes aligned with cookie, authorization, proxy, request-history, and retry behavior.
- Keep middleware and trace event order aligned with the request path, including connection waits, redirects, retries, and failures.
- Keep connector connection-key inputs aligned with every setting that must prevent unsafe connection reuse, such as TLS and proxy context.
- Keep upload tracking aligned with every request attempt and terminal path, including body retries, redirects, cancellation, and upload failure.
- Keep the short-lived
requestentry point aligned with session and connector ownership. A caller that supplies a connector must retain ownership of that connector.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A caller uses a closed session | The call fails before an outbound request starts. | Keep session ownership explicit and close it only after all response work ends. |
| A session and connector use different event loops | Session creation fails before the first request. | Create the session and connector on the same running event loop. |
| Middleware replaces a request body without closing the prior payload | File, stream, or buffer resources can remain open. | Use the async request body update path and await it. |
Middleware reuses one UploadTracker for a second request | Binding fails and the second request cannot use that tracker. | Create one fresh tracker for each request. |
| An upload is cancelled or fails before the body is complete | The tracker reports an aborted or failed upload and the connection cannot be reused for that attempt. | Treat upload completion as a terminal contract and handle its future before relying on progress. |
| A response body is not read or released | The connection may not return to the pool, and resource warnings can appear. | Use the response context manager or call the response release path. |
| Connector limits have no free slot before the connect timeout | The request waits and then raises a connection timeout. | Set limits and connect timeouts for the expected concurrency. |
| A redirect leaves the supported HTTP URL space or exceeds its limit | The session raises a redirect URL or too-many-redirects error. | Validate redirect targets and set an appropriate redirect limit. |
| A redirect needs to replay a consumed request body | The session raises a payload error instead of silently sending an empty body. | Use replayable data or disable redirects for that request. |
| A response has an error status or an unexpected content type when checks are enabled | The caller receives a response or content error instead of decoded application data. | Apply the status and content checks that match the endpoint contract. |
Key files
| File | Why to read it |
|---|---|
| aiohttp/client.py | Defines the public session boundary and coordinates request policy, middleware, redirects, retries, response checks, upload tracking, and cleanup. |
| aiohttp/client_reqrep.py | Defines the request and response contract used between the session, connector, protocol, middleware, and caller. It also defines upload progress state. |
| aiohttp/connector.py | Defines connection ownership, pooling, limits, reuse, and close behavior. |
| aiohttp/client_proto.py | Connects the async transport protocol to response messages and streaming payloads. |
| aiohttp/client_middlewares.py | Defines the request interception contract and middleware chain. |
| aiohttp/tracing.py | Defines the observation signals for request and connection activity. |
| aiohttp/cookiejar.py | Defines the session cookie state used across requests. |
| aiohttp/client_exceptions.py | Defines the error boundary exposed to client callers. |