Every developer who scales a Python HTTP client eventually hits the same wall. Your service talks to three upstream APIs, traffic doubles, and suddenly requests stall with a pool timeout or the upstream starts dropping you mid-flight with connection resets. You find the knob, bump max_connections in your httpx client, and throughput does not improve. That is usually the moment you discover the behavior you are trying to fix lives one layer below httpx entirely, in httpcore.
httpcore is encode’s deliberately minimal transport layer: the engine httpx is built on, currently released as version 1.0.9. The package is 32 files, and its runtime dependencies are exactly three — h11 for HTTP/1.1 parsing, hyper-h2 for HTTP/2, and certifi for TLS roots. There is no framework magic anywhere. Queueing, keepalive expiry, proxy tunneling, ALPN negotiation, even the entire blocking API are plain data structures and functions you can read in an afternoon, which is precisely what this tour does.
What follows is a walk through the real master tree: the pool scheduler in connection_pool.py, the four-state machine in http11.py, the flow-controlled multiplexer in http2.py, the transport abstraction in _backends, and the regex codegen that manufactures the whole sync API from the async one. Two diagrams map the territory before we descend into the code.
encode/httpcore at a glance: one pool dispatches to direct, proxy, and SOCKS connections; each connection picks HTTP/1.1 or HTTP/2 and talks to a swappable network backend.
Reading the overview from left to right:
- AsyncConnectionPool, L43 — the entire scheduler is two plain Python lists, one of connections and one of queued requests, not a heap or anything lock-free.
- _assign_requests_to_connections, L270 — a single function does all the bookkeeping: reap closed and expired connections, then match queued requests by reusing, creating, or evicting.
- PoolByteStream, L389 — the response body wrapper; only when your code closes the stream does the request leave the queue and the connection return to idle duty.
- AsyncHTTPConnection, L38 — dials TCP or a Unix socket, upgrades to TLS, then inspects
selected_alpn_protocol() == "h2"to decide which protocol class owns the socket. - HTTPConnectionState, L36 — an HTTP/1.1 connection’s life is a four-value IntEnum: NEW, ACTIVE, IDLE, CLOSED.
- has_expired, L274 — keepalive expiry compares
time.monotonic()against a deadline, plus a best-effortis_readableprobe that catches server-side disconnects. - AsyncHTTP2Connection, L42 — one socket multiplexes many requests, with incoming events buffered per stream ID and writes gated by four separate locks.
- AutoBackend, L9 — lazily detects whether trio or asyncio is running and delegates every socket operation to the matching transport.
The full map: pool internals, both wire protocols, forward and tunnel proxies plus SOCKS5, four network backends behind one interface, and the generated sync mirror.
The pool is two lists and one function
The most surprising thing about AsyncConnectionPool, L43 is how little state it keeps. self._connections and self._requests are ordinary lists. There is no priority queue, no worker thread, no condition variable. Concurrency limits are enforced by arithmetic, not machinery: max_connections defaults to 10, a None limit becomes sys.maxsize, and max_keepalive_connections is clamped with a min() call so it can never exceed the hard cap. When a request arrives, the pool appends an AsyncPoolRequest, L17 to the queue and runs the assignment pass. A new connection is created only while len(self._connections) < self._max_connections; otherwise the scheduler may evict the first idle connection to make room. The comment block lays out exactly three cases: reuse an existing connection, create a new one, or close an idle one and create. If the assigned connection turns out to be unusable, the request clears its assignment and loops — a ConnectionNotAvailable, L239 retry built into the request loop itself rather than into caller code.
Connection creation in the pool is a dispatch on scheme and proxy configuration. A socks5 or socks5h proxy yields AsyncSocks5Connection, L189; an http scheme through a proxy yields a forward connection; anything else goes through a CONNECT tunnel. And the lock guarding all of this, AsyncThreadLock, L93, is a real threading.Lock in sync mode but a documented no-op in async mode — because inside one event loop, mutation points already run without preemption between awaits.
Connections: dial, negotiate, retry
AsyncHTTPConnection, L38 owns everything that happens once, before requests flow. It dials via the network backend, applies socket options and an optional local address, and for https upgrades the stream with start_tls. The protocol decision is pure ALPN: if the negotiated protocol is "h2", or if HTTP/2 was forced while HTTP/1.1 was disabled, the raw stream is wrapped in the HTTP/2 class; otherwise it becomes an HTTP/1.1 connection. Retries have their own tiny algebra: RETRIES_BACKOFF_FACTOR, L19 is 0.5, and exponential_backoff, L25 yields a geometric sequence — 0s, 0.5s, 1s, 2s, 4s — so each ConnectError or ConnectTimeout costs twice the previous delay.
HTTP/1.1: one socket, four states
The HTTP/1.1 implementation is a thin, careful shell around the h11 parser. AsyncHTTP11Connection, L43 reads in 64 KiB chunks and caps incomplete events at 100 KiB, both as class constants. Its HTTPConnectionState, L36 IntEnum is the contract the pool queries: a connection is only available when IDLE. Two details show the engineering maturity. First, a WriteError while sending the request is deliberately swallowed, because servers sometimes close the request side pre-emptively and still answer with a well-formed error response — the read path will surface the real story. Second, a bare server disconnect before any response is remapped to a RemoteProtocolError with the message “Server disconnected without sending a response,” instead of h11’s cryptic internal event error.
Keepalive is bookkeeping, not magic. When a response closes and both h11 halves are DONE, the connection flips to IDLE, start_next_cycle() resets the parser, and _expire_at is stamped as time.monotonic() + keepalive_expiry. The pool later calls has_expired, L274, which returns true either when the deadline passed or when an idle socket is readable — readable-but-idle means the only legal payload is an EOF, i.e., the server disconnected. Upgrades follow the same discipline: a 101 response or a successful CONNECT hands the raw socket to AsyncHTTP11UpgradeStream, L351, which replays any trailing bytes already read from the wire before passthrough continues.
HTTP/2: flow control in WINDOW_UPDATEs
AsyncHTTP2Connection, L42 runs hyper-h2 with inbound header validation disabled, keeps four locks — init, state, read, write — and buffers incoming ResponseReceived, DataReceived, StreamEnded, and StreamReset events in a dict keyed by stream ID. The pool can treat one HTTP/2 connection as serving many requests because is_available() stays true until the stream ID space is exhausted, the state machine closes, or a connection error occurs. Writes are throttled by _wait_for_outgoing_flow, L488, which takes the minimum of the stream’s local flow window and the max outbound frame size — straight from RFC 7540 section 6.9 — and, when the window hits zero, reads events until a WINDOW_UPDATE frees up space. No request ever blocks another on a busy socket; they block only on their own flow budgets.
From async core to sync mirror: the unasync codegen
The strangest and best fact in this tree is that only half of httpcore/ is hand-written. httpcore/_async/ is the source of truth, and httpcore/_sync/ is generated from it by scripts/unasync.py, which applies a fixed table of regex substitutions: async def becomes def, async with becomes with, await vanishes, aclose becomes close, __aenter__ becomes __enter__, and the pattern Async([A-Z][A-Za-z0-9_]*) strips the prefix, turning AsyncConnectionPool into the ConnectionPool, L43 you actually import. Crucially, AutoBackend is rewritten to SyncBackend, because the sync world has one blocking transport instead of a runtime-detected one.
That transport layer is the other half of the design. AutoBackend, L9 calls current_async_library() on first use and delegates to TrioBackend, L109 or AnyIOBackend, L97. Both implement the same tiny contract defined in base.py: connect_tcp, connect_unix_socket, and sleep on the backend; read, write, close, start_tls, and get_extra_info on the stream. A SyncBackend with a TLS-in-TLS stream for proxy tunnels and a MockBackend for tests round out four implementations of one interface. The build honors the codegen boundary too: ruff is configured to skip httpcore/_sync entirely, and coverage omits the mirror so numbers reflect the hand-written core — the same tooling discipline you would set up with ruff and coverage on a project of your own. Even the package facade participates: the module rewrites __module__ on every exported symbol so reprs and docs say httpcore, not the private submodule path.
Honest Limits
The pool’s simplicity has edges worth knowing before you depend on them. In async mode the guard lock is a no-op, so correctness leans on single-event-loop semantics; sharing one async pool across threads is outside the design. Enjoyed this post? Never miss out on future posts by following us keepalive_expiry defaults to None, meaning idle connections persist until the server closes them, and the is_readable disconnect probe is explicitly best-effort per backend. The HTTP/2 event buffers are per-stream lists without a hard cap, relying on flow control for backpressure, and hyper-h2 is configured with inbound header validation off. Proxy support covers forward HTTP, CONNECT tunnels, and SOCKS5, but there is no HTTP/3 and no WebSocket API — though ws and wss schemes are accepted and ride the 101 upgrade path. The test suite, meanwhile, is pure pytest 8.2 with pytest-trio and pytest-httpbin serving a local fake upstream — a pattern our pytest tour breaks down — run under filterwarnings = ["error"]. None of these limits are hidden; they are each a few lines you can point at in the tree, which is the rarest quality a networking library can have.