Client connectivity, DNS, TLS, and proxies
The client connectivity layer turns a request destination into a reusable transport. It manages connection reuse, name lookup, TCP and TLS setup, and direct or proxy-based routes. It also converts low-level network problems into errors that client callers can inspect. See HTTP client for the wider client model, client request lifecycle for the request flow around this layer, and client state and interception for related client state.
Connection acquisition
The connector is the connection manager used by a client session. It first looks for a live connection that matches the request, then waits for capacity or creates a new transport. This keeps request code separate from socket setup while allowing many requests to share a small set of connections.
Connection pool
The connection pool stores idle transports by a connection identity. That identity includes the destination, port, TLS mode and settings, proxy route, proxy headers, and server name. A transport is reused only when these values match, because a connection made for one route or TLS identity must not serve another route. (aiohttp/client_reqrep.py• L218-230, aiohttp/client_reqrep.py• L1135-1151)
When a response releases a connection, the connector either returns it to the pool or closes it. Keep-alive expiry removes idle entries. The connector can also force a close after each request. A caller that closes a session or connector closes pooled and active transports and cancels connection waiters. (aiohttp/connector.py• L355-383, aiohttp/connector.py• L459-519, aiohttp/connector.py• L521-597, aiohttp/connector.py• L837-866)
References: aiohttp/connector.py• L355-383 aiohttp/connector.py• L459-519 aiohttp/connector.py• L837-866 aiohttp/client_reqrep.py• L218-230
Connection limits
The connector limits both the total number of active connections and the number for one connection identity. Requests that reach a limit wait in a per-key queue. Release of an active transport wakes a waiting request that can use the new capacity. (aiohttp/connector.py• L607-630, aiohttp/connector.py• L715-755, aiohttp/connector.py• L799-836)
The connection timeout covers the wait for a slot as well as the work needed to create the connection. This makes pool pressure visible to the same client request that is waiting, rather than allowing an unbounded queue to hide the delay. (aiohttp/connector.py• L656-713)
References: aiohttp/connector.py• L607-630 aiohttp/connector.py• L656-713 aiohttp/connector.py• L715-755 aiohttp/connector.py• L799-836
DNS resolution
DNS resolution maps a host and port to one or more stream addresses before TCP setup. The TCP connector uses a default resolver unless the client supplies another resolver. Custom resolvers follow the shared AbstractResolver contract in aiohttp/abc.py, so the rest of the connection path can use event-loop lookup or an asynchronous DNS service through the same interface. (aiohttp/connector.py• L1032-1038, aiohttp/abc.py• L116-149)
Resolver choices
The default resolver selects the available lookup service. It uses AsyncResolver when the installed aiodns service supports address lookup and otherwise uses ThreadedResolver, which runs the event loop's system lookup. Both produce the same stream-address records for the connector. (aiohttp/resolver.py• L9-18, aiohttp/resolver.py• L33-45, aiohttp/resolver.py• L103-124, aiohttp/resolver.py• L263-264)
Default AsyncResolver instances share one DNS service per event loop. Closing a resolver releases its use of that service, which is cancelled after the last user closes. Resolver instances with custom settings use their own DNS service. This keeps shared lookup state within one event loop while allowing callers to isolate custom DNS behavior. (aiohttp/resolver.py• L106-120, aiohttp/resolver.py• L183-193, aiohttp/resolver.py• L196-261)
Resolver lookups request stream addresses with address-configuration filtering. On Windows, a failed filtered lookup for localhost is retried without that filter. IPv6 link-local results retain their scope information so the connector can use the correct local interface. (aiohttp/resolver.py• L21-30, aiohttp/resolver.py• L47-95, aiohttp/resolver.py• L125-181)
References: aiohttp/resolver.py• L9-18 aiohttp/resolver.py• L21-30 aiohttp/resolver.py• L33-100 aiohttp/resolver.py• L103-193 aiohttp/resolver.py• L196-264 aiohttp/abc.py• L116-149
DNS cache
The connector can cache address results in memory. The default cache uses a ten-second lifetime and can hold up to 1,000 host-port entries. Cached addresses rotate as they are used, which spreads new connections across returned addresses. Callers can clear one entry or the full cache when local network state changes. (aiohttp/connector.py• L997-1000, aiohttp/connector.py• L1040-1045, aiohttp/connector.py• L1114-1122)
Concurrent requests for the same host and port share one in-flight lookup. A request may be cancelled while the shared lookup continues for the other waiters. A lookup error is passed to all requests that depend on that lookup. The lookup runs in a task that is shielded from caller cancellation. Its task creation works with the active event-loop type and uses eager task start where the Python runtime supports it. (aiohttp/connector.py• L1170-1218, aiohttp/connector.py• L1220-1267)
References: aiohttp/connector.py• L875-920 aiohttp/connector.py• L997-1000 aiohttp/connector.py• L1040-1045 aiohttp/connector.py• L1114-1122 aiohttp/connector.py• L1170-1267 aiohttp/abc.py• L116-149
Address selection
A numeric IP address bypasses DNS. Host names produce IPv4 or IPv6 stream addresses according to the connector family setting. The connector then uses address racing, known as Happy Eyeballs, so a slow address family does not always block a reachable one. (aiohttp/connector.py• L1123-1142, aiohttp/connector.py• L1504-1523, aiohttp/connector.py• L1557-1597)
The connector rejects non-canonical legacy numeric IPv4 forms before socket setup. This keeps the host checked by client policy aligned with the address used by the socket. (aiohttp/connector.py• L1127-1132)
References: aiohttp/connector.py• L1123-1142 aiohttp/connector.py• L1504-1523 aiohttp/connector.py• L1557-1597
TCP and TLS setup
Direct connectivity follows a staged path: resolve the destination, select a stream address, open TCP, and then perform TLS when the URL or request requires it. Each stage uses the request timeout and returns a response protocol only after the transport is ready for HTTP. The connector can use an optional accelerated network transport for the socket and TLS operations when that support is installed. (aiohttp/connector.py• L1269-1281, aiohttp/connector.py• L1325-1361, aiohttp/connector.py• L1525-1597)
TCP transport
The TCP stage opens a socket from the resolved address list. It can bind the socket to a configured local address and can use a socket factory for caller-specific socket policy. Failed address attempts are removed from consideration until one succeeds or the last error is returned. (aiohttp/connector.py• L1325-1361, aiohttp/connector.py• L1557-1597)
TCP setup is distinct from HTTP exchange. A successful socket does not mean that the server has returned an HTTP response; it means that the connector can hand a live transport to the request layer. This distinction is why connection errors surface before response errors. (aiohttp/client_exceptions.py• L58-66, aiohttp/client_exceptions.py• L124-141)
References: aiohttp/connector.py• L1325-1361 aiohttp/connector.py• L1525-1597 aiohttp/client_exceptions.py• L58-66 aiohttp/client_exceptions.py• L124-141
TLS negotiation
TLS protects an HTTPS transport after TCP is ready. The request can provide an SSL context, use the connector setting, or select verified or unverified defaults. The TLS handshake uses the request host name for server-name indication unless the caller provides an override. (aiohttp/connector.py• L1283-1314, aiohttp/connector.py• L1416-1455)
Certificate checks are part of TLS setup. A caller can also require a certificate fingerprint. A fingerprint mismatch closes the transport and prevents that peer address from being used for the current direct connection. (aiohttp/connector.py• L1465-1474, aiohttp/connector.py• L1581-1593)
The connector closes the underlying transport when TLS setup fails. This prevents a half-upgraded transport from entering the pool or remaining active after a handshake error. (aiohttp/connector.py• L1456-1464)
References: aiohttp/connector.py• L1283-1314 aiohttp/connector.py• L1416-1502 aiohttp/connector.py• L1573-1593
Proxy paths
A proxy changes which host the connector reaches first and which request target the HTTP layer sends. The session may receive a proxy per request, use a session default, or discover a proxy from the environment when trust_env is enabled. Environment lookup runs again for each redirect so a new destination can select a different proxy. (aiohttp/client.py• L552-563, aiohttp/client.py• L658-711, aiohttp/client.py• L1432-1440)
The proxy route has two main forms:
| Target and proxy | Connection path | HTTP target form |
|---|---|---|
| HTTP target through an HTTP proxy | TCP to the proxy | Absolute target URL |
| HTTPS target through an HTTP proxy | TCP to the proxy, then CONNECT and TLS to the target | Target origin form inside the tunnel |
| Any target through an HTTPS proxy | TLS to the proxy, then the selected HTTP or tunnel path | Depends on the target scheme |
This diagram shows how a direct request and the two proxy stages reach the final HTTP transport.
flowchart TD
A[Client request] --> B{Proxy selected?}
B -- No --> C[Resolve target]
C --> D[TCP to target]
D --> E{HTTPS target?}
E -- Yes --> F[TLS to target]
E -- No --> G[HTTP transport]
B -- Yes --> H[Resolve proxy]
H --> I[TCP or TLS to proxy]
I --> J{HTTPS target?}
J -- No --> K[Send absolute URL through proxy]
J -- Yes --> L[Send CONNECT to target]
L --> M{Proxy returns 200?}
M -- Yes --> N[TLS through tunnel]
M -- No --> O[Proxy response error]
Direct proxy requests
For an HTTP target, the proxy receives the request directly. The request uses an absolute URL so the proxy can select the remote target. Proxy authorization belongs on that proxied request, while the destination remains the request URL. (aiohttp/connector.py• L632-654, aiohttp/client_reqrep.py• L939-951)
The proxy route resolves and connects to the proxy host. It does not resolve the target host in this path; the proxy performs the next hop. This means a proxy DNS failure and a target DNS failure can occur in different network locations. (aiohttp/connector.py• L1602-1607, aiohttp/connector.py• L1525-1555)
References: aiohttp/connector.py• L632-654 aiohttp/connector.py• L1525-1555 aiohttp/connector.py• L1599-1607 aiohttp/client_reqrep.py• L939-951
CONNECT tunnels
For an HTTPS target, the connector first connects to the proxy and sends CONNECT host:port. A successful 200 response leaves the proxy transport open, then the connector starts TLS for the target over that tunnel. The intermediate proxy connection is not pooled as if it were a complete target connection; only the upgraded transport represents the usable route. (aiohttp/connector.py• L1600-1673)
The proxy must return 200 for the tunnel request. Any other status becomes ClientHttpProxyError and includes the proxy response details. Proxy credentials are prepared separately from the target request headers, which keeps proxy authorization tied to the proxy hop. If sending the CONNECT request fails, the connector closes the intermediate proxy connection before it re-raises the error. (aiohttp/connector.py• L632-654, aiohttp/connector.py• L1645-1671, aiohttp/client_exceptions.py• L111-117)
References: aiohttp/connector.py• L632-654 aiohttp/connector.py• L1623-1701 aiohttp/client_exceptions.py• L111-117
TLS-in-TLS support
An HTTPS target through an HTTPS proxy needs two TLS layers: one for the proxy and one inside the tunnel for the target. Support depends on the event loop and transport in use. The optional accelerated network transport supports this layered path. When the active runtime cannot start the second layer, the connector warns and raises a client connection error instead of returning a partially secure transport. (aiohttp/connector.py• L1363-1414, aiohttp/connector.py• L1475-1493)
Functional coverage treats this as a runtime capability, not a proxy protocol failure. A runtime with TLS-in-TLS support can reach HTTPS targets through a secure proxy; an unsupported runtime reports the limitation to the caller. (tests/test_proxy_functional.py• L133-160, tests/test_proxy_functional.py• L165-239)
References: aiohttp/connector.py• L1363-1414 aiohttp/connector.py• L1475-1493 tests/test_proxy_functional.py• L133-160 tests/test_proxy_functional.py• L165-239
Transport failure surface
The connector keeps failure classes aligned with the stage that failed. After connection setup, the response protocol keeps that boundary visible by turning socket loss, read silence, incomplete payloads, and HTTP or WebSocket parsing errors into client-facing failures. Callers can use the exception type to tell apart name lookup, proxy reachability, TLS checks, proxy negotiation, and failures during response transport. (aiohttp/client_exceptions.py• L124-189, aiohttp/client_proto.py• L117-192, aiohttp/client_proto.py• L300-315)
Connection error classes
The main transport-level failures are:
| Failure stage | Caller-visible error | Meaning |
|---|---|---|
| Invalid numeric host form | InvalidUrlClientError | The host is not an accepted canonical address. |
| DNS lookup | ClientConnectorDNSError | The resolver could not produce an address. |
| TCP connection to the target | ClientConnectorError | Socket setup failed for a direct route. |
| TCP or TLS connection to the proxy | ClientProxyConnectionError | The proxy endpoint could not be reached or secured. |
| Server certificate validation | ClientConnectorCertificateError or ClientConnectorSSLError | TLS certificate or SSL setup failed. |
| Expected certificate fingerprint | ServerFingerprintMismatch | The peer certificate did not match the required fingerprint. |
Proxy CONNECT response | ClientHttpProxyError | The proxy refused or failed to create the tunnel. |
| Unsupported TLS-in-TLS setup | ClientConnectionError | The runtime could not layer target TLS over the secure proxy transport. |
| Socket read timeout | SocketTimeoutError | The peer did not provide data within the configured read interval. |
| Clean loss before the exchange is complete | ServerDisconnectedError | The peer closed the connection before the expected response data arrived. |
| OSError during an active exchange | ClientOSError | The socket failed after connection setup. |
| Incomplete response payload | ClientPayloadError | The response body ended before its payload was complete. |
| HTTP response parsing failure | HttpProcessingError | The received bytes did not form a valid HTTP response. |
ClientConnectorError carries the connection key and the original OS error. Callers can inspect the host, port, TLS setting, and underlying error when they need to report or classify a failure. (aiohttp/client_exceptions.py• L136-173)
References: aiohttp/client_exceptions.py• L111-189 aiohttp/connector.py• L1127-1132 aiohttp/connector.py• L1338-1361 aiohttp/connector.py• L1475-1493 aiohttp/connector.py• L1645-1655
Response transport
ResponseHandler is the live transport boundary after the connector has created a socket. It feeds HTTP response messages and streaming bodies to client callers, tracks whether the connection can return to the pool, and marks the transport for close when an error, unfinished payload, upgrade, or buffered data makes reuse unsafe. (aiohttp/client_proto.py• L32-57, aiohttp/client_proto.py• L82-91, aiohttp/client_proto.py• L223-230)
When the peer closes the socket, the handler completes a clean close signal or sets a ClientConnectionError on waiters. It also reports an unfinished body as ClientPayloadError, maps an unexpected clean close to ServerDisconnectedError, and wraps socket errors as ClientOSError. This preserves the difference between a failed connection and an incomplete response. (aiohttp/client_proto.py• L117-192)
The handler applies the socket read timeout while the peer is expected to send data. It drops that timer when data arrives, when reading is paused, or when the response body reaches EOF. A timeout sets SocketTimeoutError on both the response path and its active payload. (aiohttp/client_proto.py• L198-221, aiohttp/client_proto.py• L283-315, aiohttp/client_proto.py• L395-403)
References: aiohttp/client_proto.py• L32-57 aiohttp/client_proto.py• L82-115 aiohttp/client_proto.py• L117-192 aiohttp/client_proto.py• L198-221 aiohttp/client_proto.py• L283-315 aiohttp/client_proto.py• L395-403
Timeout and cancellation
Connection work has separate limits for waiting on connector capacity, opening the socket, completing TLS, and reading response data. A socket timeout is re-raised rather than being mislabeled as an operating-system connection error. Cancellation also releases reserved connector state so a cancelled request does not consume a connection slot. (aiohttp/connector.py• L656-713, aiohttp/connector.py• L1325-1361, aiohttp/connector.py• L1431-1482, aiohttp/client_proto.py• L283-315)
References: aiohttp/connector.py• L656-713 aiohttp/connector.py• L1325-1361 aiohttp/connector.py• L1431-1482 aiohttp/client_proto.py• L283-315
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to
ConnectionKeyfields must preserve the rule that pooled transports cannot cross destination, TLS, proxy, proxy-header, or server-name boundaries. - Changes to proxy request construction must keep authorization on the proxy hop and keep absolute-form requests separate from tunneled origin-form requests.
- Changes to DNS cache lifetime, address rotation, or shared lookup handling must preserve behavior for concurrent callers and cache clearing.
- Changes to the DNS lookup task path must remain compatible with supported event-loop types and must keep caller cancellation from cancelling shared lookups.
- Changes to the resolver interface must preserve the address fields that connector address selection needs and the close operation used during connector shutdown.
- Changes to resolver selection or shared
AsyncResolverownership must preserve the one-event-loop boundary and must release shared DNS services when their last user closes. - Changes to the connection and TLS transport adapters must preserve the same timeout and error boundary when an accelerated transport is available or absent.
- Changes to TLS-in-TLS support checks must keep the warning and the caller-visible error aligned with the runtime transport capability.
- Changes to connector error wrapping must preserve the distinction between target DNS errors, proxy connection errors, TLS errors, and non-
200CONNECTresponses. - Changes to response transport state must preserve the rule that incomplete payloads, parser failures, upgrades, buffered bytes, and active exceptions prevent unsafe connection reuse.
- Changes to response read-timeout scheduling must keep the timer aligned with peer reads and must propagate timeout errors to both the response stream and its active payload.
- Changes to session proxy selection must account for redirects because environment proxy lookup is repeated for each request attempt.
- Changes to failed
CONNECThandling must close the intermediate proxy transport before the failure reaches the caller.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A pooled connection is keyed without a changed proxy or TLS identity | A request can use a transport for the wrong route or security setting | Keep all route and TLS identity fields in ConnectionKey. |
| DNS returns no usable address | Connection creation stops before TCP setup | Surface ClientConnectorDNSError and clear or replace the resolver state when needed. |
| The proxy endpoint cannot be resolved or reached | The request never reaches the target | Surface ClientProxyConnectionError for proxy connection setup. |
| A shared DNS lookup is cancelled with its first caller | Other requests waiting for the same host can fail even though they did not cancel | Run the lookup in a shielded task and pass its result or error to all waiters. |
| A shared async DNS resolver is closed while another event loop owns its service | Lookup state can be used across loop boundaries or be cancelled too soon | Keep shared resolver ownership per event loop and release the service only after its last resolver closes. |
An HTTPS proxy refuses CONNECT | No target tunnel exists | Require a 200 response and raise ClientHttpProxyError for other statuses. |
Sending CONNECT fails before a proxy response exists | The intermediate proxy transport can remain open after the request fails | Close the tunnel wrapper in the send error path before re-raising. |
| TLS certificate or fingerprint validation fails | The transport is closed and no response is returned | Use the TLS-specific error or fingerprint mismatch and do not pool the transport. |
| The runtime cannot layer TLS over an HTTPS proxy | Secure target access fails before HTTP exchange | Use an event loop or transport with TLS-in-TLS support. Otherwise warn about the limit and raise ClientConnectionError. |
| The peer stays silent during a response read | The response and active payload fail with SocketTimeoutError | Configure a suitable read timeout and stop the timer while reading is paused or complete. |
| The peer closes before the response body is complete | The body fails and the transport cannot be reused | Surface ClientPayloadError or ServerDisconnectedError and mark the connection for close. |
| Response bytes fail HTTP parsing | The transport closes and no valid response is returned | Surface HttpProcessingError and keep the failed transport out of the pool. |
| A caller abandons a connection without release or close | A transport can remain active and a resource warning can be emitted | Close the response, session, or connector so ownership returns to the connector. |
Key files
| File | Why to read it |
|---|---|
| aiohttp/connector.py | Defines pooling, limits, DNS use, direct TCP and TLS setup, accelerated transport selection, and proxy routing. |
| aiohttp/client_proto.py | Defines the live response transport boundary, read timeout behavior, connection-loss mapping, payload delivery, and connection reuse safety. |
| aiohttp/client_reqrep.py | Defines the connection identity and the request target form used for direct, proxy, and tunnel traffic. |
| aiohttp/resolver.py | Defines the system and asynchronous DNS choices, their shared event-loop ownership, and the address records supplied to the TCP connector. |
| aiohttp/abc.py | Defines the resolver interface and the address data passed from name lookup into connection setup. |
| aiohttp/client.py | Shows how request settings, session defaults, environment proxies, and redirect attempts select a proxy route. |
| aiohttp/client_exceptions.py | Defines the error classes that expose transport and proxy failures to client callers. |
| tests/test_proxy_functional.py | Demonstrates end-to-end direct proxy access and runtime-dependent HTTPS proxy behavior. |
| tests/test_proxy.py | Exercises proxy request construction, proxy DNS and connection failures, tunnel setup, and cleanup after failed CONNECT sends. |
| tests/test_connector.py | Covers connector pooling, DNS cache behavior, address selection, TLS setup, and cleanup boundaries. |