Every Python service that talks HTTP eventually hits the same wall. You want a client that does not leak sockets under load, a server that survives thousands of idle connections, and none of it to block the event loop. Requests solves the ergonomics but threads through each call; WSGI servers like Flask’s need a worker per concurrency unit. aiohttp took the other road: client and server written directly on asyncio transports and protocols, with a shared HTTP parsing core and the hot paths compiled to C.
The result is a library where the interesting engineering is not in the routing decorators but in the plumbing: how a keep-alive pool decides who gets a connection, how backpressure propagates from a TCP socket into a read() call, and how a WebSocket frame state machine runs identically for client and server. Those decisions live in a handful of files that have barely changed shape since the project joined aio-libs, which makes the tree unusually easy to read end to end.
This tour walks that tree from the current master branch, where the version string reads 4.0.0a2.dev0. Two diagrams were generated from the real repository: an overview of the major moving parts and a detail graph of the classes underneath them.
Overview: one client stack on the left, one server stack on the right, a connector pool underneath, and shared parsers underneath both.
Reading the overview from left to right:
- ClientSession._request, L515 is the single entry point for every call: it loops redirects (the default
max_redirectsis 10, declared at L527), applies per-request middleware at L783, and only then hands work to the connector. - _connect_and_send_request, L282 is where a request meets infrastructure:
connector.connect(req, traces, timeout)at L288 returns aConnection, and the protocol’s response parameters are bound before the first byte is sent. - BaseConnector.connect, L646 opens with the docstring “Get from pool or create new connection” — a pool hit skips the timeout-ceil logic entirely, a miss goes through a placeholder dance so cancellation cannot strand an acquired slot.
- _wait_for_available_connection, L705 queues waiters per
ConnectionKeyand re-inserts previously-waited futures at the front of the dict withmove_to_end, an explicit anti-starvation fix worth reading on its own. - RequestHandler, L149 is the server’s per-socket protocol:
data_receivedat L490 feeds the parser, and_handle_requestat L683 convertsHTTPExceptioninto real responses and unexpected errors into 500s. - UrlDispatcher, L984 is both an
AbstractRouterand aMappingof resources —register_resourceat L1057 enforces uniqueness of canonical paths across plain, regex and static resources. - WebSocketResponse.prepare, L259 completes the RFC 6455 handshake and constructs the response’s
WebSocketDataQueueat L387 — frames land in a bounded queue, not on the handler’s stack. - StreamReader.feed_data, L285 appends the chunk and calls
_protocol.pause_reading()the moment_sizepasses the high-water mark at L302; that one line is aiohttp’s whole backpressure story. - WebSocketDataQueue, L81 has a Cython twin declared in
reader_c.pxdat L49, and_websocket/reader.pyL7-30 picks between them at import time with anImportErrorfallback.
Detail graph: 32 classes across seven layers — client core, pooling, streams, server core, routing, the WebSocket stack, and the compiled accelerators.
The client: one loop, ten redirects, keyed waiters
ClientSession (client.py, L308) is deliberately thin state: a connector, a cookie jar (CookieJar at cookiejar.py L66, plus a DummyCookieJar for session-less use), trace configs, and option objects typed as TypedDict — _RequestOptions at L188, _WSConnectOptions at L217, _SessionOptions at L250. The heavy lifting is _request(), and reading it explains most of aiohttp’s client behaviour in one pass.
Each iteration strips URL credentials (refusing to silently combine them with an Authorization header, client.py L691-696), applies trust_env netrc and proxy lookups per iteration so a redirect that switches proxies cannot leak credentials (L722-736), then builds a ClientRequest and wraps _connect_and_send_request in middleware if any are configured. Redirect handling at L827 treats 301/302/303/307/308 uniformly and caps the chain. One detail that shows how seriously the maintainers take HTTP semantics: IDEMPOTENT_METHODS at L238 is the frozenset {"GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE", "QUERY"} — it already includes the new QUERY method, and retry_persistent_connection at L670 retries a dropped keep-alive connection for exactly those methods, as RFC 9112 advises.
Timeouts are equally explicit: ClientTimeout defaults to total=5*60 — five minutes (client_reqrep.py L92) with separate sock_connect/sock_read knobs. And the pool’s default keep-alive is 15 seconds (connector.py L333), with a 2-second _cleanup_closed_period timer (L311) sweeping half-closed SSL transports.
If you have ever stared at “connection pool is full” style errors, the fix is visible in the code: connections are tracked in _acquired plus _acquired_per_host (connector.py L351-352), waiters are keyed by ConnectionKey, and _DNSCacheTable (L867) caches resolutions so a busy host keeps reusing warm sockets instead of re-resolving. Compare this with the WSGI model where each worker owns its sockets — the difference is architectural, and the Flask source tour shows the other side of that trade.
The server: one handler per socket, one router per app
The server side starts at Server (web_server.py, L46): its connection_made at L95 spawns a RequestHandler per accepted socket. RequestHandler is the asyncio.Protocol that makes aiohttp feel synchronous to user code. It parses bytes through the shared parser, builds a Request (web_request.py L931, on top of the MutableMapping BaseRequest at L126), and calls the application callable. The exception mapping in _handle_request (web_protocol.py L683) is precise: uncaught HTTPException becomes a real response with its cookies preserved, TimeoutError becomes 504, everything else becomes 500 — all before finish_response writes bytes and decides whether the connection stays open.
Application (web_app.py, L73) is the other half: a MutableMapping keyed by AppKey objects rather than raw strings (a type-safety fix that keeps two subsystems from colliding on "db"), a router property that exposes the UrlDispatcher (L335), and CleanupContext at L424 for startup/teardown stacks. AppRunner and TCPSite (web_runner.py L439 and L126, plus UnixSite and NamedPipeSite) are the transport glue that binds it all to a listening socket.
Routing is resource-centric rather than decorator-centric. UrlDispatcher holds PlainResource (L363) for exact paths, DynamicResource (L403) for {variable} regexes, StaticResource (L501) for directory trees served through FileResponse (web_fileresponse.py L85), and even PrefixedSubAppResource (L716) to mount a whole sub-application under a prefix, plus Domain/MaskDomain matchers (L775/L819) for host-based routing. SystemRoute at L904 quietly implements the 404/405 responses the dispatcher itself returns. Everything is awaited through StreamResponse.write() (web_response.py L459), which drains the transport when the OS buffer is full rather than queueing unboundedly — the same discipline StreamReader applies on the way in.
WebSockets: one state machine, two implementations
WebSocketResponse (web_ws.py, L72) and its client twin ClientWebSocketResponse (client_ws.py, L54) share the entire frame machinery under aiohttp/_websocket/. The reader (reader_py.py L190) is a compact state machine over header, mask and payload; the writer (writer.py L40) builds frames with optional per-message deflate, and a comment at L27 records a deliberate choice: control frames (ping, pong, close) are never compressed. Heartbeat plumbing lives directly on the response object (autoping, heartbeat parameters at web_ws.py L100-101).
What makes this directory special is the packaging. reader.py L7-30 tries the Cython WebSocketReader/WebSocketDataQueue from reader_c and falls back to the pure-Python versions on ImportError — or honours AIOHTTP_NO_EXTENSIONS. The masking itself is the classic XOR benchmark: _websocket_mask_cython (mask.pyx, L11) exists because Python-level byte-by-byte masking is too slow for gigabit frame rates.
If you want to see how far the same async pattern generalises, the event loop and interpreter plumbing underneath all of this are covered in the CPython source tour.
From pure Python to four compiled extensions
The build defines aiohttp’s speed budget. setup.py declares exactly four extensions (L59-84): aiohttp._websocket.mask, aiohttp._http_parser (compiled from _http_parser.c plus _find_header.c plus the vendored llhttp sources vendor/llhttp/build/c/llhttp.c, src/native/api.c, src/native/http.c at L45-49), aiohttp._http_writer, and aiohttp._websocket.reader_c. llhttp comes from a git submodule — building from a plain clone without it exits with an explicit “git submodule update –init” hint (L21-29) — unless AIOHTTP_USE_SYSTEM_DEPS switches to pkg-config for a system llhttp. A ParallelBuildExt (L87) compiles the four modules with os.cpu_count() workers, and the script literally prints * Accelerated build * versus * Pure build * (L94-102).
The Python side mirrors this in two stages. At import, http_parser.py L1369-1386 renames the Python classes to ...Py aliases and re-imports HttpRequestParser/HttpResponseParser from the compiled module when extensions are available; the Cython llhttp parser replaces the Python one wholesale, which is why both server and client parsing get the speedup from one build artefact. At runtime, NO_EXTENSIONS = bool(os.environ.get("AIOHTTP_NO_EXTENSIONS")) (helpers.py L103) is checked by _websocket/reader.py and by _http_writer, so a pure install degrades gracefully rather than crashing. Non-CPython interpreters are handled at build time too: setup.py L17-18 forces NO_EXTENSIONS when sys.implementation.name != "cpython".
Inside _http_writer.pyx the approach is unusually concrete for a Cython module: a BUF_SIZE of 16 KiB (L10) and a cdef struct Writer (L17) build status lines and headers byte-by-byte in C, with _write_byte and _write_utf8 inline helpers. That is the kind of code you otherwise only find in parser libraries — here it lives in the writer because serialising thousands of small headers was the measured bottleneck. Tooling around the project follows the same standards you would expect from a top-tier library; the pytest source tour covers the test runner that drives aiohttp’s own suite, and test_utils.py ships TestServer, RawTestServer, TestClient and AioHTTPTestCase (L63, L199, L225, L497) precisely so applications can spin the real server in-process during tests.
Streams, payloads, and the rest of the box
Two more files round out the picture. streams.py is the flow-control layer: StreamReader (L71) with feed_data (L285) pausing the protocol above the high-water mark and resume_reading (L583) below the low one; DataQueue (L695) is the generic single-item waiter queue whose pattern WebSocketDataQueue reuses. multipart.py implements the multipart/related family on top of these streams: BodyPartReader (L352) for consuming parts, MultipartReader (L770) for server-side parsing, MultipartWriter (L1006) for building uploads — no third-party dependency needed. The resolver.py split (ThreadedResolver L33 vs aiodns-backed AsyncResolver L103, chosen by DefaultResolver at L264) shows the same philosophy: pure-Python default, faster optional path, selected at import.
Honest Limits
This tour reads Enjoyed this post? Never miss out on future posts by following us master at 4.0.0a2.dev0 — a development branch. The 4.x line is actively reshaping internals (the old FlowControlDataQueue name survives only in changelogs, replaced by the WebSocket queue), so line numbers will drift; every anchor in this post was verified against the checked-out tree on the day of writing, but treat them as a snapshot, not a stable API. Second, the diagrams were generated from the sparse aiohttp/ package tree — they deliberately exclude docs, tests and vendored llhttp sources, so counts like “32 classes” refer to the curated graph, not the whole package. Third, performance claims here describe architecture (where the C code is, what gets pooled) rather than benchmarks; the repo’s own benchmark suite and the llhttp project are the right places for numbers. Finally, QUERY in the idempotent set is forward-looking — support across proxies and clients is still uneven in the wild, which aiohttp’s own redirect and retry code navigates conservatively.