12.9 · Single-flight token refresh, streaming lines, multipart bodies and request signing
The harder client features: refreshing a token once for many concurrent calls, reading a response as it arrives, building an upload body by hand, and proving a request was not tampered with.
Mental model. Concurrency makes auth and streaming subtle: one refresh for everyone, bytes arrive in arbitrary pieces, and a signature must cover exactly what the server will see.
Auth under concurrency
Coalescing token refreshes so five 401s cause one refresh.
- Five requests fail with 401 at the same moment. How do you refresh the token once, retry each request once, and avoid a loop?
If every failing request refreshes the token itself you send five refresh calls, and with a rotating refresh token the second one invalidates the first and the…
Bytes and bodies
Line streams and server-sent events, multipart bodies, and HMAC request signing.
- How do you read a response as a stream with URLSession.bytes, and why does lines skip blank lines when you are parsing server-sent events?
session.bytes(for:) returns an AsyncBytes sequence and the response as soon as the headers arrive, so you can process a body incrementally instead of waiting… - What does a multipart/form-data body look like on the wire, and what are the boundary, CRLF and Content-Type rules you must get right?
A multipart body is a sequence of parts separated by a boundary string that must not appear in the data. Each part is --boundary, then headers… - How does HMAC request signing work, what must a canonical string include, and how do you verify a signature safely?
When an API must know a request was not altered and came from a client holding a shared secret, the client sends a signature: an HMAC (here HMAC-SHA256) over a…
More in Networking
- 12.1 · Sessions, configurations, tasks, delegates and background transfers
- 12.2 · HTTP versions, TLS, App Transport Security and certificate pinning
- 12.3 · Pagination, caching and conditional requests, and authentication refresh
- 12.4 · WebSockets, multipart and large transfers, and network path monitoring
- 12.5 · Retries, backoff, idempotency and cancellation
- 12.6 · REST, GraphQL and gRPC, and building a client platform
- 12.7 · Image loading pipelines: download, decode, downsample, cache
- 12.8 · Building URLs, reading headers, classifying errors and timeouts
- 12.10 · Network.framework, background sessions, delegates versus async, diagnosing and measuring