Lesson 5 of 9 · 23m
Async Network I/O That Survives the Internet
HTTP client lifecycle, connection pooling, streaming, retries, and the socket-level mistakes that turn partial failures into cascading outages.
Async network code fails in ways synchronous tutorials rarely mention: half-open TCP connections, DNS stalls, servers that accept but never reply, response bodies nobody drains, and retries that arrive after the first attempt actually succeeded. Production asyncio is mostly timeout and lifecycle discipline.
Reuse clients; do not create one per request
from httpx import AsyncClient, Limits, Timeout
client = AsyncClient(
timeout=Timeout(connect=1.0, read=3.0, write=2.0, pool=0.5),
limits=Limits(max_connections=100, max_keepalive_connections=20),
)
async def shutdown():
await client.aclose()Creating a fresh client per request discards connection pooling and DNS caches. Worse, unclosed clients leak sockets. Build shared clients during startup, inject them into the parts of the app that need them, and close them during shutdown.
The timeout object matters. A single timeout=10 is too blunt: you usually want a fast connect timeout, a bounded read timeout, and a tiny pool wait so overload fails early instead of queueing forever inside the client.
Streaming is for large or infinite responses
async with client.stream('GET', 'https://objects.storage/internal/export.ndjson') as resp:
resp.raise_for_status()
async for line in resp.aiter_lines():
await process_line(line)await client.get() buffers the entire body in memory. That is fine for JSON metadata and fatal for a 4GB export. Streaming keeps memory flat and gives you a natural cancellation point between chunks.
Retries amplify partial failure
A timeout means you do not know whether the server completed the operation. Retrying a non-idempotent POST can duplicate charges, emails, or inventory updates. Make mutating operations idempotent with keys, or only retry operations designed for it.
headers = {'Idempotency-Key': payment_key}
await client.post('https://payments.internal/v1/charges', json=payload, headers=headers)Retry policies need exponential backoff, jitter, and a small maximum. backoff libraries can help, but the policy is architectural, not decorative. Three immediate retries triple the load on a dependency that is already failing.
Lower-level streams need explicit closure
reader, writer = await asyncio.open_connection('127.0.0.1', 6379)
try:
writer.write(b'PING
')
await writer.drain()
print(await reader.readline())
finally:
writer.close()
await writer.wait_closed()drain() is flow control: it waits when the outbound buffer is too full. Forgetting wait_closed() can leave connection teardown incomplete. In practice, use a mature protocol client unless you are implementing the protocol itself.
Timeouts belong around the whole operation
A read timeout is not the same as a total deadline. Ten slow chunks can each reset the read timer while the operation runs forever. Wrap business operations in asyncio.timeout() so the user-visible deadline still exists even when progress is technically happening.
Field notes
- Watch file descriptor usage (
/proc/<pid>/fdor process metrics). Sudden growth usually means unclosed clients, streams, or response bodies. - HTTP 429 is capacity information, not just an error. Honor
Retry-Afterwhen present. - DNS and connect behavior vary by platform and resolver configuration; measure them separately from read latency.
- Never log full request bodies or headers by default — authorization tokens and cookies end up in aggregation systems.
Was this lesson helpful?