Cookies, compression, and utility primitives
These shared primitives make HTTP data safe and predictable as it moves between clients, servers, and application code. They preserve cookie scope, decode or encode supported content codings, give structured access to headers and URLs, and apply consistent time and body rules across the HTTP APIs. See HTTP data handling for the wider data flow, payloads, forms, and multipart for payload-specific processing, and client state and interception for the client request lifecycle.
Shared data path
The utilities sit between raw HTTP fields and the higher-level request or response objects. They turn wire values into typed views for application code, then turn application choices back into valid headers and body framing.
flowchart LR
Wire[HTTP wire data] --> Headers[Header and URL views]
Wire --> Cookies[Cookie parsing]
Wire --> Decode[Content decoding]
Headers --> Request[Request APIs]
Cookies --> Jar[Cookie storage and scope]
Decode --> Payload[Readable payload]
Request --> Response[Response APIs]
Jar --> Request
Response --> Encode[Response encoding and headers]
Encode --> WireOut[HTTP wire data]
Cookie exchange
Cookie parsing
Cookie parsing separates a request Cookie header from response Set-Cookie headers because the two formats have different meaning. The parser accepts common real-world variations while rejecting unsafe names and preserving both the decoded value and the original coded value for compatible re-use.
- Request cookies become a read-only name-to-value view on
BaseRequest.cookies. - Response cookie headers become cookie morsels that retain attributes such as domain, path, expiry,
Secure,HttpOnly,SameSite, andPartitionedwhen supported by the runtime. - Quoted values can contain separators. An unmatched opening quote does not discard later cookies.
- URL percent escapes remain in the cookie value. Cookie parsing does not apply URL decoding.
References: aiohttp/_cookie_helpers.py• L167-179 aiohttp/_cookie_helpers.py• L266-283 aiohttp/web_request.py• L617-626 aiohttp/client_reqrep.py• L381-403
Cookie storage
CookieJar is the client-side cookie store. It accepts cookies from a response URL or raw Set-Cookie headers, keeps their domain and path rules, removes expired entries, and filters the result before each request so that only cookies valid for that request are sent.
Structured cookie updates copy caller-owned morsels before storage. Raw header updates use newly parsed morsels, so the jar can normalize them without sharing mutable state with the header parser. Persistence replaces the current jar: saving records cookie attributes, host-only scope, and absolute expiry deadlines, while loading restores that state through the normal acceptance rules. A malformed load leaves the current jar unchanged. The persistence file can contain session or authentication data, so it is created with restricted permissions.
The default jar does not accept cookies from IP addresses. Host-only cookies remain limited to the host that set them, secure cookies require a secure request, and domain or path attributes control wider scope. A configured treat_as_secure_origin marks selected cleartext origins as secure for cookie filtering, including cookies supplied for one client request. The jar also rejects cookie values that cannot be sent in a valid Cookie header. It limits stored cookies by domain and in total, and limits each outgoing header; when a limit is reached, it keeps the most specific or recently used cookies where possible. DummyCookieJar provides the same interface when an application does not want cookie processing.
sequenceDiagram
participant Server
participant Response
participant Jar as CookieJar
participant Request
Server->>Response: Set-Cookie headers
Response->>Jar: Accept with response URL
Jar->>Jar: Apply domain, path, secure, expiry, and size rules
Request->>Jar: Request URL
Jar-->>Request: Cookies valid for the URL and header limits
Request->>Server: Cookie header
References: aiohttp/cookiejar.py• L46-59 aiohttp/cookiejar.py• L66-142 aiohttp/cookiejar.py• L164-283 aiohttp/cookiejar.py• L285-443 aiohttp/cookiejar.py• L453-617 aiohttp/cookiejar.py• L619-742 aiohttp/cookiejar.py• L877-924 aiohttp/abc.py• L154-199 aiohttp/client.py• L647-656
Response cookie storage
Server response objects use cookie helpers to build Set-Cookie fields without mixing them into the ordinary single-value header map. set_cookie updates a cookie and its selected attributes, while del_cookie emits an expired replacement so the client removes the named cookie when it receives the response.
References: aiohttp/helpers.py• L1001-1105 aiohttp/web_response.py• L73-75 aiohttp/web_response.py• L384-389
Content compression
Content coding negotiation
Content compression reduces response size and restores request or response payloads to their original bytes. A server response can enable compression and either choose a coding accepted by the request or force a selected coding; a client can request compressed content and decode it automatically unless that behavior is disabled.
The normal HTTP response codings are gzip and deflate. br and zstd are available for response decoding when their optional libraries are installed. The Content-Encoding header records the selected coding, and a compressed response does not keep an old uncompressed length.
flowchart LR
Accept[Accept-Encoding] --> Choose[Select response coding]
Body[Response body] --> Compress[Compress]
Choose --> Compress
Compress --> Encoded[Content-Encoding and encoded body]
Encoded --> Client[Client parser]
Client --> Decompress[Decode when auto-decompress is enabled]
Decompress --> Plain[Readable payload bytes]
References: aiohttp/web_response.py• L55-66 aiohttp/web_response.py• L182-197 aiohttp/web_response.py• L330-352 aiohttp/client.py• L171-196 aiohttp/client_proto.py• L229-260
Streaming compression
Compression works with streamed data as well as complete response bodies. Small chunks stay in the event loop, while larger chunks can use an executor so compression does not block other asynchronous work. Decompression applies an output limit and supports concatenated gzip, deflate, or zstd members.
Each decoder reports whether it has more output and whether the input ends at a complete stream or member boundary. The HTTP parser uses that completion state at end of input, so a truncated stream is reported even when the codec already produced the full visible payload. A decoder can resume across chunk boundaries and across multiple content codings. A member-count limit prevents excessive work from many concatenated members.
Compression state is shared across successive chunks. If an asynchronous compression operation is cancelled while a final flush or send is still pending, the stream can become invalid; callers must treat that stream as unusable or protect the complete compress, flush, and send sequence as one operation.
References: aiohttp/compression_utils.py• L186-295 aiohttp/compression_utils.py• L298-371 aiohttp/compression_utils.py• L373-443 aiohttp/compression_utils.py• L445-496 aiohttp/compression_utils.py• L498-561 aiohttp/http_parser.py• L1215-1257 aiohttp/http_parser.py• L1260-1333 aiohttp/http_writer.py• L87-94 aiohttp/http_writer.py• L168-221
Decompression limits
The HTTP parser feeds decoded bytes into the payload stream in bounded output units. This keeps compressed input from expanding into one unbounded allocation and turns codec errors into content-encoding errors. Concatenated streams are supported, but a member-count limit prevents a peer from forcing excessive decoder work with many empty members.
References: aiohttp/http_parser.py• L1260-1333 aiohttp/compression_utils.py• L49-56 aiohttp/compression_utils.py• L251-295
Header and URL views
Header views
Header helpers provide case-insensitive access to repeated fields while keeping the raw header form available when an exact wire view matters. They also expose comma-separated field values as logical items, including quoted values and comments, so separators inside a value do not split it. Content type values expose a media type and parameters, content length becomes an integer or None, and HTTP dates become UTC datetimes when they parse correctly.
The same rules support conditional requests and responses. ETags are represented as structured values with weak and wildcard forms, and response framing removes content length or body data when the method or status requires an empty body.
References: aiohttp/helpers.py• L744-831 aiohttp/helpers.py• L1107-1159 aiohttp/web_request.py• L532-609 aiohttp/web_response.py• L281-316 aiohttp/web_response.py• L410-425
URL views
URLs use yarl.URL as the shared representation for request targets, base URL joining, host and scheme lookup, query access, and route-generated links. The request exposes both decoded path-oriented properties and a raw path view so routing and security checks can distinguish the received target from its interpreted form.
Path helpers quote unsafe characters when they create route URLs and preserve existing percent escapes when they normalize paths. The optional path-normalization middleware can redirect a request to a form with merged slashes or a consistent trailing-slash policy; it checks that the changed path resolves before redirecting.
References: aiohttp/web_request.py• L466-524 aiohttp/client.py• L459-463 aiohttp/web_urldispatcher.py• L1232-1248 aiohttp/web_middlewares.py• L49-119
Header and URL safety
Helpers validate values that can cross an HTTP boundary. Basic authentication rejects a colon in the login name, ETags reject characters outside their allowed value set, content-disposition parameters are quoted or encoded for their target format, and URL path generation preserves the distinction between data and separators.
Host validation also rejects legacy numeric IPv4 spellings that a socket layer could map to an address. Only canonical dotted-quad IPv4 text is accepted for direct IP resolution, which keeps connector policy aligned with the host value that the application supplied.
References: aiohttp/helpers.py• L160-176 aiohttp/helpers.py• L399-497 aiohttp/helpers.py• L500-533 aiohttp/helpers.py• L1107-1159 aiohttp/web_urldispatcher.py• L1232-1248 aiohttp/connector.py• L1147-1157
Timeout coordination
Timeout scopes
ClientTimeout gives one request a total deadline plus narrower connection, socket-connect, and socket-read limits. The default total timeout is five minutes. A value of None disables a scope; zero is not the disable value for the total timeout.
The client uses the total deadline around the request and applies the narrower limits to connection creation and socket reads. Read activity refreshes the read timer, while a stalled socket raises a socket timeout and closes the affected work path.
References: aiohttp/client_reqrep.py• L86-129 aiohttp/client.py• L294-354 aiohttp/client.py• L232-254 aiohttp/connector.py• L655-689 aiohttp/client_proto.py• L272-299
Timeout scheduling
Timeout helpers schedule work against the event loop clock instead of wall-clock time. Delays above the configured ceiling are rounded to an event-loop second boundary. This reduces timer churn, so a timeout can occur slightly after its nominal delay.
The same scheduling rule is used for connection waits and socket setup. A timeout context converts cancellation caused by its own deadline into TimeoutError, while cancellation that existed before entering the context can continue to the caller.
References: aiohttp/helpers.py• L552-741 aiohttp/connector.py• L667-689 aiohttp/connector.py• L1317-1345
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the two cookie parsers distinct. Request
Cookiepairs have no attributes, while responseSet-Cookievalues use attributes to update the jar. - If cookie update paths change, preserve the distinction between caller-owned morsels and freshly parsed morsels so storage does not create unexpected shared mutable state.
- Preserve host-only scope and absolute expiry when changing cookie persistence. Loading must not widen a host-only cookie to subdomains or lose its deadline.
- Preserve restricted file permissions when changing cookie persistence because the file can contain session or authentication tokens.
- If the secure-origin setting changes, preserve its propagation to temporary jars used for per-request cookies so secure-cookie filtering stays consistent.
- If cookie limits change, keep storage admission, eviction order, outgoing header limits, and the unlimited per-request jar aligned. A limit must not silently change which more-specific cookie wins.
- If a content coding is added or removed, align negotiation, parser selection, optional dependency checks, and the
Content-Encodingheader behavior. - Preserve the output limit, member continuation, and stream-completion checks when changing decompression. Payload readers depend on more data being available after a decoder reaches a member boundary and on truncated input failing at EOF.
- When changing content length or compression, check the empty-body status and method rules. Body framing and
Content-Lengthmust remain consistent. - When changing URL quoting or path normalization, check both route matching and redirect targets. Encoded slashes and percent escapes must not change meaning silently.
- When changing host validation, keep the helper's canonical IPv4 rule aligned with connector resolution so legacy numeric forms cannot bypass URL policy.
- When changing timeout fields, update the scope that consumes each field and keep
Nonesemantics distinct from invalid or immediate timeout values.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A cookie is set for an unrelated domain | The jar rejects it and the next request does not carry it | Domain matching uses the response host and RFC cookie scope rules |
| A secure cookie is selected for an insecure URL without a configured secure origin | The cookie is omitted from the request | Filter cookies by request scheme and apply only explicitly trusted origins |
| Per-request cookies use a temporary jar without the session's secure-origin setting | A secure cookie can be omitted on a configured cleartext origin | Copy the parent jar's secure-origin policy to the temporary jar |
| A persisted host-only marker is lost during save or load | The cookie can leak to matching subdomains | Preserve host-only scope as part of the persisted cookie state |
| A persisted absolute expiry is lost during save or load | An expired cookie can remain usable longer than intended | Store and restore the absolute expiry deadline |
| A cookie persistence file is created with broad access | Other users on the system can read session or authentication tokens | Create the file with restricted permissions |
| A cookie store or outgoing header exceeds its limit | New cookies are dropped or lower-priority cookies are omitted from the request | Enforce domain, total, per-request, and header-size limits with specificity-aware selection |
| A cookie contains control characters or cannot be encoded for a header | The jar does not store or send it | Validate the complete cookie name and value before storage |
| A malformed cookie persistence record is loaded | The current jar stays unchanged and loading raises an error | Load into a separate jar and adopt it only after all records pass validation |
A response uses an unavailable br or zstd decoder | The payload fails with a content-encoding error | Install the optional codec or disable unsupported compressed responses |
| A compressed stream exceeds the decoder output budget | Decoding pauses with pending input instead of returning an oversized body | Continue decoding through the payload reader with its size limit |
| A compressed stream ends before a member or frame is complete | The payload fails at EOF instead of being accepted as complete | Check each decoder's stream-completion state before feeding payload EOF |
| Compression is cancelled before its flush and send complete | The compressor state can corrupt later bytes | Close the stream or shield and serialize the full compression operation |
A response enables compression after setting Content-Encoding | The helper leaves the existing encoding in place and avoids double compression | Treat an existing content encoding as authoritative |
| A handler writes a body for a status or method that forbids one | HTTP framing becomes invalid or the body is discarded | Apply the shared empty-body rules before writing headers and data |
| A request remains idle past its socket-read limit | The client raises a socket timeout and marks the connection for closure | Set a suitable read timeout or send data within the allowed interval |
| A URL uses a legacy numeric IPv4 spelling | The connector rejects the host instead of resolving an unintended address | Accept only canonical dotted-quad IPv4 text for direct IP resolution |
Key files
| File | Why to read it |
|---|---|
| aiohttp/_cookie_helpers.py | Defines the shared boundary between raw cookie headers and cookie morsels. |
| aiohttp/cookiejar.py | Shows how client cookie scope, expiry, persistence, secure-origin policy, header updates, filtering, and cookie-size limits work as one policy. |
| aiohttp/helpers.py | Groups header views, cookie response helpers, URL-adjacent safety helpers, dates, ETags, and timeout scheduling. |
| aiohttp/compression_utils.py | Defines the common compression and decompression contract, including optional codecs and output limits. |
| aiohttp/http_parser.py | Shows where response content coding becomes a readable payload and where decode failures surface. |
| aiohttp/web_request.py | Connects headers, URLs, conditional fields, and request cookies to the server request API. |
| aiohttp/web_response.py | Connects response cookies, compression negotiation, headers, and body framing to the server response API. |
| aiohttp/client.py | Shows the client-wide cookie, URL, compression, and timeout choices that shape each request. |
| aiohttp/client_reqrep.py | Shows the client response cookie view and the shared timeout model at the request boundary. |
| aiohttp/connector.py | Applies host validation before direct IP resolution and shows where URL safety reaches network connection setup. |