Every Python developer ships urllib3 whether they know it or not. It is the engine underneath pip, the layer that requests wraps, and a direct dependency of botocore, google-auth, and a long list of SDKs. So when an endpoint starts returning 503s and your job hammers it thirty times in three seconds, the retry storm you are watching was scheduled by code in src/urllib3/util/retry.py — not by the library you actually called. Reading this source is the fastest way to stop guessing why your client reconnects, why a pool “leaks” sockets under threads, or why a decompressed body suddenly raises a mysterious RuntimeError.
The 2.x series quietly rebuilt most of that machinery. The latest release at the time of writing, 2.8.0 (2026-09-15), fixed a high-severity issue where TLS configuration for HTTPS proxies could be ignored or overridden, and capped a chunk-size buffering path in stream() and read_chunked(). Beneath those changelog lines sits a strict separation of duties: a PoolManager mapping normalized URL keys to pools, one HTTPConnectionPool per host and port, connections that wrap the standard library’s http.client, and a response object that streams decompression on every read. None of it is magic, but all of it is deliberate.
This post walks the real tree at main (the default branch), with every symbol and line number verified against the current source. If you have ever debugged connection handling by print-statement, the two diagrams below — generated from the repository structure itself — are the map you wish you had.
Overview of urllib3's layers: a single PoolManager front door fans out to host-scoped pools, which drive http.client-based connections, TLS wrapping and a streaming response layer, all under the supervision of Retry and Timeout objects.
Reading the overview from left to right:
- PoolManager.urlopen, L436 is the real entry point — the docstring block above the class explains that PoolManager handles redirects itself and always passes
redirect=Falsedown to per-pool urlopen calls. - _default_key_normalizer, L103 lowercases scheme and host before pooling, per RFC 3986 case rules, while carefully preserving the case of an IPv6 zone id.
- RecentlyUsedContainer.setitem, L101 is the LRU heart: an
OrderedDictguarded by a lock, evicting withpopitem(last=False)and handing evicted pools to adispose_functhat closes them. - _get_conn, L262 borrows a socket from the pool queue and discards it immediately if
is_connection_dropped()reports the peer closed it. - urlopen, L583 is the four-hundred-line orchestration loop that turns borrowed sockets, timeouts and Retry objects into one response.
- retries.increment, L836 inside the exception handler rebuilds the Retry object with the failure appended and then calls
retries.sleep(). - get_backoff_time, L324 computes exponential backoff using
math.ldexp(self.backoff_factor, consecutive_errors_len - 1), so each consecutive failure doubles the wait. - _decode, L658 streams every read through the content decoder and refuses
decode_content=Falseafter decoded reads, raising aRuntimeErrorrather than returning mixed bytes. - HTTP2Connection, L85 subclasses
HTTPSConnection, proving the HTTP/2 support is a drop-in connection swap, not a separate stack.
The detail map adds ProxyManager, the socket-to-TLS wrapping chain, the decoder family, the typed error generator and the HTTP/2 connection path that reuses the same pool layer.
The Pool Layer: one key per corner case
PoolManager (poolmanager.py, class at L175) is smaller than people expect because it delegates almost everything. Its state is a single RecentlyUsedContainer(num_pools) — ten pools by default (L214) — plus two dictionaries, pool_classes_by_scheme and key_fn_by_scheme, that let subclasses swap in custom behavior. When a request arrives for a new host, _new_pool() constructs an HTTPConnectionPool or HTTPSConnectionPool and stores it; when the container overflows, the least recently used pool is evicted and closed via dispose_func.
The interesting part is what counts as “the same pool”. PoolKey is a NamedTuple with twenty-nine fields (poolmanager.py, L72 through L100): scheme, host, port, timeout, retries, block, source address, key and certificate files, CA data, SSL version bounds, ssl_context, maxsize, headers, proxy settings, socket options, SOCKS options, hostname assertion, fingerprint and block size. Two requests share a pool only if all twenty-nine match after normalization. _default_key_normalizer() lowercases scheme and host, converts headers into frozensets so the key stays hashable, and leaves the IPv6 zone alone because only the address portion of a scoped address is case-insensitive.
That LRU container deserves a second look because most Python engineers have written a worse version: a hundred lines that model any cache of expensive handles — sockets, database clients, API SDKs — as an evict-on-overflow map with a close callback.
Inside urlopen(): the retry machine
HTTPConnectionPool.urlopen() (L583) is where the design earns its keep. The loop is conceptually simple: borrow a socket with _get_conn() (L262), validate it with _validate_conn() (L343 — a no-op for plain HTTP, a certificate re-check for HTTPS), hand it to _make_request() (L383), and classify whatever comes back.
The failure paths are where subtlety lives. On connection errors, the handler at L836 calls retries.increment(method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]) and then retries.sleep() (L839). The finally block is the part people get wrong when reimplementing pooling: if the attempt did not exit cleanly, the connection is closed and thrown away — conn.close() then conn = None (L850-852) — so a poisoned socket never re-enters the pool. _put_conn() (L300) is deliberately non-blocking: self.pool.put(conn, block=False), and when the queue is full the surplus socket is closed with a warning rather than queued (L321-337). That is why a pool can never exceed maxsize — and why an under-provisioned pool silently burns sockets instead of backpressuring.
The Retry class (retry.py, class at L44) treats itself as immutable: increment() (L473) returns a brand-new Retry built via new(**kw) (L281) with a RequestHistory entry appended, or raises MaxRetryError when a budget hits zero. Backoff is computed from the tail of that history: get_backoff_time() (L324) counts consecutive errors with takewhile(... redirect_location is None ...) (L330-334) so redirects reset the sequence, then doubles with math.ldexp(self.backoff_factor, consecutive_errors_len - 1) (L339), adds uniform jitter, and clamps to backoff_max (L344). The cap default is DEFAULT_BACKOFF_MAX = 120 seconds (L216). Before any computed wait, sleep_for_retry() (L380) checks the server’s Retry-After header — honored by default for status 413, 429 and 503 (L208) — and sleeps exactly as long as the server asked, parsed either as seconds or an HTTP-date.
Responses: streaming decoders and typed errors
HTTPResponse (response.py, class at L728) extends BaseHTTPResponse (L483), an io.IOBase whose backing store is a BytesQueueBuffer (L406). The design choice that surprises people migrating from 1.x: there is no preload_content eager slurp anymore. Decoding happens per read. When headers announce content-encoding, _get_decoder() (L388) picks from DeflateDecoder (L82), GzipDecoder (L153), BrotliDecoder (L229) and ZstdDecoder (L282), and MultiDecoder (L332) chains them in header order for stacked encodings like gzip, br.
_decode() (L658) then does streaming decompression with a max_length hint, and the guard at L668-673 is a load-bearing footgun fix: once decoded bytes have been emitted, a later read(decode_content=False) raises RuntimeError instead of silently mixing raw and decoded bytes. The Brotli decoder notes that Brotli >= 1.2.0 is required to prevent decompression bombs (L254) — the output buffer limit in the C library is the defense. Reads are also wrapped by _error_catcher() (L937), a generator that translates mid-body socket faults into typed exceptions like ProtocolError and ReadTimeoutError, and releases the connection back to the pool as part of cleanup. The default read chunk is _DEFAULT_BLOCKSIZE = 16384 (L61), which is why stream() memory behavior is stable across body sizes.
TLS: context first, socket second
HTTPSConnection (connection.py, class at L697) subclasses HTTPConnection (L122), which itself extends the standard library’s http.client connection — the same class family you would find walking the cpython source. The TLS work is concentrated in two places. create_urllib3_context() (ssl_.py, L184) builds a hardened ssl.SSLContext: minimum and maximum TLS versions replace the deprecated single ssl_version argument, OP_NO_COMPRESSION and ticket options are applied by default, and on Python 3.13+ the context enables VERIFY_X509_PARTIAL_CHAIN and VERIFY_X509_STRICT (L217-218). ssl_wrap_socket() (L367) loads key material — detecting and rejecting encrypted PEM keys without a password (L454) — and returns the wrapped socket.
The single choke point is _ssl_wrap_socket_and_match_hostname() (connection.py, L1032): it wraps the raw socket, applies the context, and asserts hostname or SHA-256 fingerprint on success. SSLTransport (ssltransport.py, class at L22) exists so http.client can keep treating the socket like a plain socket: it implements the socket read/write surface over SSLObject buffers. Finally, HTTPSConnectionPool._validate_conn() (connectionpool.py, L1106) re-checks certificates on every reuse of a pooled TLS connection, not just at creation — the reason a mid-pool certificate rotation is actually caught.
From http.client shim to hardened toolkit: the numbers
The build facts worth memorizing:
- One file, one job.
connectionpool.pyholds both pool classes and the retry loop;connection.pyholds both connection classes and TLS wrapping;response.pyholds decoding and errors. Three files carry almost the whole HTTP story. - 29 fields in
PoolKey(L72-100 of poolmanager.py) versus the two you would guess (scheme, host). The extra twenty-seven exist because sharing an ssl_context or proxy config between “identical” hosts is a correctness bug, not an optimization. - Default budgets.
num_pools=10(poolmanager.py L214), LRUmaxsize=10(_collections.py L84), backoff cap 120s (retry.py L216), read chunk 16 KiB (response.py L61). - Default retry surface.
DEFAULT_ALLOWED_METHODSis exactly HEAD, GET, PUT, DELETE, OPTIONS, TRACE (retry.py L202-204) — POST is intentionally not retried by default because it is not idempotent. Redirects stripCookie,AuthorizationandProxy-Authorization(L211-213). - HTTP/2 without a fork.
HTTP2ConnectionsubclassesHTTPSConnectionand swaps http.client framing for the h2 library’s state machine, with a_LockedObjectguarding concurrent access;HTTP2Response(L325) plugs back into the same response surface. The pool, retry and timeout layers are reused untouched. - 2.8.0 hardening. The 2026-09-15 release closed the HTTPS-proxy TLS override advisory and bounded chunk-size line buffering — both fixes are guards around parsing untrusted input, the classic failure mode of a protocol library.
Honest Limits
The pooling model is per-host: HTTPConnectionPool.maxsize governs concurrent sockets to one host:port pair, and there is no global cross-host cap beyond num_pools evicting whole pools. Thread safety comes from the container lock and queue semantics — two threads can hold two sockets from one pool, but a single connection object must never be used concurrently, the contract HTTP/2’s _LockedObject guards with explicit locking. There is no asyncio support here; event-loop clients live in separate projects, and urllib3 stays a blocking, thread-based engine.
Redirect handling lives in Enjoyed this post? Never miss out on future posts by following us PoolManager.urlopen() — a bare HTTPConnectionPool.urlopen() with redirect=False will not follow redirects, which surprises people who reach for a pool directly. The decode_content=False-after-decode RuntimeError is intentional but remains a common trap in streaming code. HTTP/2 requires the h2 extra, and it applies per connection rather than via protocol auto-negotiation unless you opt in with http2=True. Finally, the test suite that keeps all of this honest — socket-level tests against a local dummyserver harness — runs under pytest, and reading test/with_dummyserver/ is the best way to see every edge case above exercised for real. The source rewards the read: every footgun you have hit in production HTTP is a deliberate, documented decision in one of these files.