Every Python developer has felt this particular pain: your service calls another service, one day it stalls, and the traceback says httpx.ReadTimeout — but you never configured a read timeout anywhere. Or a connection pool silently holds twenty sockets to a host you stopped calling a minute ago. Or a third-party API answers a POST with a 401, your auth tuple mysteriously works, and you have no idea who added which header. The requests-style top-level API (httpx.get(...)) hides all of this on purpose, and the documentation is excellent about behavior — but behavior is only half the story. When timeouts, proxies, or credentials misbehave in production, the only way out is reading the actual request path in the source.
That source is surprisingly compact. The httpx/ package in encode/httpx is 7,448 lines of Python spread over 24 modules (we counted them from the current tree), and most of the machinery lives in a handful of files: _client.py at 1,770 lines and _models.py at 1,106 lines dominate, while the transport bridge _transports/default.py is only 351 lines. Version 0.29.0 requires Python 3.10+ and declares just four runtime dependencies — certifi, httpcore==1.*, anyio, and idna — because httpx deliberately delegates sockets and pooling to httpcore and asyncio plumbing to anyio. Everything in this article is verified against the real tree; every line number below was grepped, not guessed.
This tour walks the two diagrams below in order. The overview shows the shape of the library: a thin public API, a client layer that composes auth and redirects, message models, and a transport boundary. The detail diagram zooms into the method-level call graph, including the exception translation that happens when httpcore misbehaves. If you have ever wanted to know exactly what happens between client.get(url) and a socket, this is that story.
httpx at a glance: the public API creates one-shot clients, Client composes request building, auth and redirect handling, and every network byte crosses the transport boundary into httpcore pools.
Reading the overview from left to right:
- Client.send, L879 — the public entrypoint; it refuses to run on a closed client by checking
ClientState.CLOSEDat line 900, then flips the state machine toOPENEDat line 903 before anything touches the network. - Client._send_handling_auth, L930 — the first wrapper layer; it drives an auth object’s generator, and the handshake happens at line 949 where
auth_flow.send(response)returns a possibly-modified request back into the loop. - Client._send_handling_redirects, L964 — the redirect loop; it raises
TooManyRedirectspast the limit at line 971 and runs request and response event hooks at lines 976 and 981. - Client._send_single_request, L1001 — exactly one network round trip; it asks
_transport_for_url(line 760) which transport owns this URL, then times the call withtime.perf_counter(). - HTTPTransport.init, L136 — the transport constructor picks its engine once:
httpcore.ConnectionPoolat line 156 for direct traffic,httpcore.HTTPProxyat line 169, orhttpcore.SOCKSProxyat line 196. - map_httpcore_exceptions, L96 — a context manager that translates httpcore exceptions into httpx ones using a lookup table built at line 74; this is why you never see a raw httpcore traceback.
- DigestAuth._ALGORITHM_TO_HASH_FUNCTION, L176 — the hash table covering MD5, SHA, SHA-256 and SHA-512 plus their
-SESSvariants, selected per server challenge. - NetRCAuth, L145 — netrc support that lazily imports the stdlib
netrcmodule at line 153 and reuses the Basic header builder at lines 164 to 172. - Headers, L139 — the case-insensitive multi-dict behind every request and response, stored as raw
(original, lower, value)byte triples at line 149 with an ascii-then-utf-8 decoding fallback at line 173.
The detail view: the four-layer send onion, the transport protocol and its four in-tree backends, generator-based auth, content encoding and decoding, and the exception hierarchy that everything maps onto.
Inside send(): an onion of generator layers
The heart of _client.py is a deliberately boring structure: send() wraps _send_handling_auth(), which wraps _send_handling_redirects(), which calls _send_single_request() once per hop. Each layer is a plain method, but two of them are cooperative because the pieces below them are generators. send() first merges everything you passed to build_request() (line 340) — client-level headers, cookies, query params, auth, timeout — into one Request, then walks down the onion. If you did not ask for stream=True, line 922 eagerly calls response.read() so the connection returns to the pool immediately; the except BaseException at line 926 closes the response on any failure so sockets never leak mid-exception.
The redirect layer is worth reading closely because it explains response.history. The loop rebuilds the request via _build_redirect_request, appends the consumed response to history, and keeps going while the location header says so — up to DEFAULT_MAX_REDIRECTS = 20, defined in _config.py line 248. If follow_redirects=False, it instead parks the next request on response.next_request and returns, which is how you get the intermediate 301 as a first-class object. The auth layer above uses the same history list, so a Digest handshake that re-POSTs your request still ends up with a coherent audit trail.
Transports: one protocol, four backends
The entire transport abstraction is two one-method protocols: BaseTransport.handle_request() (line 14) and AsyncBaseTransport.handle_async_request() (line 65) in _transports/base.py. HTTPTransport picks an httpcore engine in its constructor — connection pool for direct traffic, HTTPProxy for http/https proxies, SOCKSProxy for socks5, with an honest ImportError telling you to install httpx[socks] if you forgot. The async twin at line 279 mirrors this with AsyncConnectionPool (line 300), AsyncHTTPProxy, and AsyncSOCKSProxy. Every handle_request call goes through the map_httpcore_exceptions() context manager, so a httpcore.ConnectError surfaces as httpx.ConnectError with your original Request attached.
The same protocol is implemented three more times without any sockets: ASGITransport (line 63) calls an in-process ASGI app, WSGITransport (line 44) does the classic WSGI dance, and MockTransport (line 15) returns canned responses or whatever a handler callable produces. Because Client treats them all identically, your integration tests can swap _transport and skip the network entirely — that is how the project’s own suite under pytest stays fast and hermetic. Mounts add routing on top: _transport_for_url (line 760) scans the _mounts dict sorted at line 716 so patterns like "https://api.example.com" can steer specific hosts to specific transports.
Auth flows: 401 handling without callbacks
Authentication in httpx is a generator protocol, not a callback interface. The base class Auth (line 22) exposes sync_auth_flow and async_auth_flow around one user-overridable auth_flow() generator that yields requests and receives responses. BasicAuth (line 126) yields once with a prefilled Authorization header. NetRCAuth (line 145) proves the design composes: it reads per-host credentials from a netrc file and simply delegates to the Basic header builder. FunctionAuth (line 113) wraps any plain callable for the trivial cases.
DigestAuth (line 175) is the flagship example. Its auth_flow sends the request untouched, waits for the response, and only reacts to a 401 carrying a Digest challenge (lines 201 to 212). Then it parses the WWW-Authenticate fields in _parse_challenge (line 224), selects a hash function from the algorithm table (MD5 through SHA-512, each with a -SESS mode), computes the response digest, and yields the replayed request. The _nonce_count attribute (line 191) starts at 1 and increments per replay, matching the RFC’s nc parameter. Because the client drives this loop through auth_flow.send(response), there are no threads, no timers, and no callbacks — just a resumable function that remembers where it was.
From 7,448 lines to one request: build facts
A few concrete numbers make the architecture tangible. The default configuration constants sit at the bottom of _config.py: DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0) (line 246), DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20) (line 247), and DEFAULT_MAX_REDIRECTS = 20 (line 248) — three lines that answer half of all “why is my client behaving like this” questions. Headers keeps its data as (original, lower, value) byte triples so nothing is re-encoded, and when it must decode it tries ascii, then utf-8 (line 173). Response text resolution follows a documented priority chain in the encoding property (line 653): explicit assignment first, then the charset from Content-Type via charset_encoding (line 689), then the client’s default_encoding — which may be a callable for charset sniffing — and finally plain utf-8.
Decoding is a chain: _get_content_decoder (line 699) reads the Content-Encoding list and builds MultiDecoder (line 203) instances over gzip (line 85), deflate (line 56), and the optional brotli (line 108) and zstandard (line 161) decoders, which import their packages defensively and degrade to None when the extras are missing. URL handling is fully in-tree too: _urls.py defines URL (line 15) with raw_scheme (line 135), raw_host (line 196), and raw_path (line 283) byte accessors, while _urlparse.py implements the parser itself — urlparse at line 213, IDNA-aware encode_host at line 348, the WHATWG-safe character set at line 385, and port normalization at line 395 — so httpx does not depend on stdlib urllib.parse quirks. The library lint-checks itself with ruff, type-checks with strict mypy settings in pyproject.toml, and its __init__.py re-exports roughly seventy names while rewriting each one’s __module__ to "httpx" (lines 104 to 106) so tracebacks and docs read cleanly. There is even a click-based CLI (main() at line 452, wired as the httpx console script) whose --timeout defaults to 5.0 seconds — the same number as the library default.
Honest Limits
- httpx does not own sockets. Everything below
HTTPTransportlives in the separate httpcore project, so deep pool tuning or connection debugging means reading two repositories, not one. - Sync and async are two parallel implementations.
Client(line 594) andAsyncClient(line 1307) duplicate the whole onion — roughly 700 lines each side of the same file — and a fix to one can silently miss the other; the mirrored test files exist precisely to catch that drift. - HTTP/2 is off by default (
http2: bool = Falseat line 650) and needs thehttp2extra; until you enable it, h2 is never imported. - Optional encodings are genuinely optional: without the
brotliorzstandardextras installed, servers that force those encodings will produce aDecodingErrorrather than silently working. - NetRC authentication only fills Basic credentials from a netrc file; there is no netrc path for Digest, and proxy auth is configured separately through the
Proxyclass (line 201 in_config.py). - The CLI is a thin convenience layer, not a feature-complete curl clone, and it pulls in click, rich, and pygments through the
httpx[cli]extra.
Enjoyed this post? Never miss out on future posts by following us