Production Executive Summary: httpx.AsyncClient is the right HTTP client for a Python service that talks to a dozen dependencies at once, and in production it fails in four ways that never look like an HTTP error: PoolTimeout arrives while the dependency is perfectly healthy, RemoteProtocolError appears in bursts that track a load balancer’s idle timeout instead of your release schedule, keeping one client per request exhausts file descriptors and ephemeral ports long before CPU is a problem, and a well-meaning retry decorator turns a five-second blip into a five-minute outage by multiplying load exactly when the dependency has the least capacity to absorb it.
This runbook takes each failure in turn, reproduces it against a real loopback HTTP server, prints the numbers the probe actually measured, and then assembles the client that prevents them: explicit pool accounting, a keep-alive lifetime shorter than the server’s, a retry predicate that knows which failures are safe to repeat, full-jitter backoff through tenacity, and a circuit breaker that stops calling a dependency that has already stopped answering. Everything was measured on Python 3.12.16 with httpx 0.28.1, httpcore 1.0.9, anyio 4.16.0 and tenacity 9.2.1 on a two-vCPU Linux container; the verification section lists every probe and how to re-run it.
Why These Four Belong In One Runbook: Three of the four failure modes end in the same place: the caller cannot tell the difference between an HTTP failure and a client-side bookkeeping failure, so the on-call engineer debugs the dependency while the real fault is a queue that lives inside the API gateway’s own process.
| Failure | What the caller sees | What is actually true | First metric to check |
|---|---|---|---|
PoolTimeout | Exception after the pool deadline | The dependency answered every request it received; the client refused to queue | Pool waits per second, connections in use vs max_connections |
RemoteProtocolError | “Server disconnected without sending a response” | Either the peer closed an idle connection the pool still trusted, or the peer died mid-request | Error rate correlated with idle gap, not with RPS |
| FD / port exhaustion | OSError: Too many open files, connect stalls | Connections are being created and destroyed instead of reused | Client FD count, TIME_WAIT sockets, connection churn per request |
| Retry storm | Latency cliff, then the dependency falls over | Each failed call became three to five calls at the same instant | Retries divided by logical requests, peak arrivals per 100 ms |
1. The Ownership Model: Which Layer Owns Which Timeout
Every httpx failure mode is a question of ownership. Four parties can stop a request: the client’s pool, the client’s connection, the server, and the network between them. Each one has its own clock, and only one of them is the budget your caller cares about. Confusing them is the reason a service can log PoolTimeout at peak while its p99 dependency latency is 40 ms.
| Clock | Owner | httpx setting | Default | What it measures |
|---|---|---|---|---|
| Pool wait | httpcore connection pool, per origin | Timeout(pool=...) | 5.0 s | Time to be handed a connection slot from the queue |
| Connect | The socket backend | Timeout(connect=...) | 5.0 s | TCP handshake, and TLS handshake when the origin is https |
| Write | The connection | Timeout(write=...) | 5.0 s | Time to push the request bytes into the socket |
| Read | The connection | Timeout(read=...) | 5.0 s | Idle time between response bytes, restarting on each chunk |
| Keep-alive | The pool entry | Limits(keepalive_expiry=...) | 5.0 s | How long an idle connection may sit in the pool before the client closes it |
| Server idle | The dependency, or its load balancer | Not yours to set | 5 s on uvicorn and on Node, 2 s on Gunicorn, 75 s on nginx, 60 s on most cloud balancers (Table 8) | How long the server keeps an idle connection open before sending FIN |
Two of these clocks are not timeouts at all. keepalive_expiry is a client-side eviction policy, and the server’s idle timeout is a server-side eviction policy. They do not negotiate. When the client’s value is larger than the server’s, the pool can end up holding a connection the peer has already closed: a reuse usually notices the close and reconnects, and every so often it does not, and the request that was written into the dead socket fails with RemoteProtocolError even though nothing is wrong with either system. Section 4 measures exactly that window.
One more thing about the argument named timeout: in httpx 0.28 it is not a total. httpx.Timeout(30) means connect 30, read 30, write 30 and pool 30, because the number is copied into every phase you did not override, and the object prints as Timeout(timeout=30.0) to say so. A call that waits for a pool slot, connects, writes and then reads can legally spend all four, so timeout=30 is a two-minute ceiling in the worst case and says nothing about how many attempts your retry layer will spend it on. When you need one ceiling for the whole operation, it has to come from outside httpx: asyncio.timeout() around the call, as the production module in section 7 does.
The Most Expensive Single Argument In httpx: timeout=30 is not a thirty-second budget. It is four separate thirty-second allowances, one per phase — connect, read, write and pool — so the wall clock can reach two minutes for a single attempt before your retry layer even adds a wait. Write the arithmetic down before you deploy.
2. PoolTimeout Is Queue Arithmetic, Not A Network Error
The pool is a fixed number of reusable connections per origin, and every request must hold one for its whole lifetime. PoolTimeout is raised when a request cannot be handed a connection inside the pool deadline. That makes it a statement about concurrency and latency, which is why it appears during an incident whose cause is a slow dependency rather than a broken one.
Little’s law gives you the sizing arithmetic in one line: the connections you need are the requests arriving per second multiplied by the seconds each request holds one. Twenty requests in flight against a dependency that answers in 300 ms is 20 connections, and the same statement in rates is required_connections = required_rps × p99_latency: 50 rps against a dependency whose p99 is 300 ms is 15 connections, not 5 and not 200.
The arithmetic belongs in the code that builds the client, not in a comment, because the traffic profile changes and a comment does not. A twenty-line object makes the calculation reviewable and keeps the dependency’s own connection ceiling in the same expression.
"""Little's law as a startup assertion instead of a 03:00 surprise."""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class PoolBudget:
"""Connections a dependency needs, derived from its own traffic and latency."""
peak_rps: float
p99_latency: float
headroom: float = 1.2
max_connections_cap: int = 200
def required_connections(self) -> int:
"""peak_rps x p99, plus headroom, never above what the dependency allows."""
wanted = self.peak_rps * self.p99_latency * self.headroom
return max(1, min(self.max_connections_cap, round(wanted)))
def explain(self) -> str:
return (
f"{self.peak_rps:.1f} rps x {self.p99_latency * 1000:.0f} ms p99 x "
f"{self.headroom:.1f} headroom = {self.required_connections()} connections"
)
The probe ran 20 concurrent requests against a fixed 300 ms upstream and varied only the pool size and the pool deadline. The server counted how many requests ever arrived, which is the number that decides whether the dependency saw load or only heard about it later.
| max_connections | pool deadline | 200 OK | PoolTimeout | Requests reaching upstream | p50 | p99 |
|---|---|---|---|---|---|---|
| 1 | 0.2 s | 1 | 19 | 1 | 406.3 ms | 406.3 ms |
| 1 | 1.0 s | 20 | 0 | 20 | 3,178.0 ms | 6,045.9 ms |
| 2 | 0.1 s | 2 | 18 | 2 | 312.3 ms | 312.4 ms |
| 2 | 0.25 s | 2 | 18 | 2 | 310.3 ms | 310.4 ms |
| 2 | 0.5 s | 20 | 0 | 20 | 1,668.5 ms | 3,027.6 ms |
| 5 | 0.25 s | 5 | 15 | 5 | 313.5 ms | 314.5 ms |
| 5 | 5.0 s (default) | 20 | 0 | 20 | 763.7 ms | 1,216.1 ms |
| 20 | 5.0 s | 20 | 0 | 20 | 319.2 ms | 1,339.9 ms |
Read the fourth column against the fifth. In every row where the pool deadline is shorter than the upstream latency, the requests that timed out never reached the server at all: 18 of 20 callers were told the dependency was unavailable when the dependency was healthy and idle. That is the diagnostic signature of a client-side queue error: the dependency’s own dashboards show a handful of requests, all answered in 300 ms, while the caller’s error rate is 90 percent.
The second lesson is less comfortable. With one connection and a one-second pool deadline, all 20 requests succeeded, but the last caller waited 6,045.9 ms to be told its 300 ms request succeeded. The pool deadline did not bound that wait, because the deadline is applied to each attempt at acquiring a connection rather than to the total time spent queued. Instrumenting httpcore’s wait_for_connection for that run counted 119 waits, the longest 310.9 ms, none of them at or beyond the one-second deadline, while the total queue time reached three seconds.
The practical consequence: a pool deadline is a safety valve for pathological queueing, not a request budget, and a large pool is not a substitute for an honest latency budget. If you need “fail in 500 ms or give up”, that guarantee has to be written with asyncio.timeout() around the call, or with a semaphore that measures the queue explicitly.
None of that arithmetic decides anything until the number reaches the pool. AsyncClient(limits=...) is only consulted when httpx builds the transport itself: pass your own AsyncHTTPTransport — because you want retries=0, or a socket option, or a proxy — and the limits object is accepted and then ignored while httpcore answers with its own defaults of 100 connections, 20 keep-alive and a 5 s expiry. The pool still works; it is simply not the pool you declared, and nothing in the constructor call says so. The probe ran the same ten callers three ways against a cap of five:
| Case | Declared cap | Transport | Server connections | Requests in the first 50 ms | p50 | p99 |
|---|---|---|---|---|---|---|
| Limits on the client, no transport | 5 | httpx builds it | 5 | 5 of 10 | 536.1 ms | 613.3 ms |
| Limits on the client, plain transport | 5 | AsyncHTTPTransport(retries=0) | 10 | 10 of 10 | 311.7 ms | 313.4 ms |
| Limits on the client and the transport | 5 | AsyncHTTPTransport(retries=0, limits=limits) | 5 | 5 of 10 | 461.5 ms | 613.3 ms |
With the limits in the right place the number does what it says, and the proof is where the sixth call goes. Six callers against a cap of five opened exactly five connections: five requests reached the server inside the first millisecond, and the sixth reached it about 300 ms later — one full service time — because it was waiting in the pool queue for a slot to come back. The client timed that call at 610.9 ms end to end for a 300 ms dependency: about 301 ms queued and about 309 ms in service, so the wait is visible in the total and invisible in the service time. Shorten the pool deadline to 200 ms and that same sixth caller is refused with PoolTimeout after 201.1 ms without ever opening a socket, so the dependency sees five requests for six calls — the client-side queue signature in the first row of Table 5, arriving through a different door. At this article’s own setting the same rule held: 41 callers against max_connections=40 opened exactly 40 sockets, and 41 callers against a cap of 100 opened 41.
| Symptom | Diagnosis | Fix |
|---|---|---|
PoolTimeout with a healthy dependency | Required connections exceed max_connections | Raise max_connections to peak_rps × p99 and lower the pool deadline to the latency budget |
| Pool waits long but no timeouts | Pool deadline is a per-assignment valve | Wrap the logical call in asyncio.timeout() and alert on queue wait percentiles |
| Timeouts only at deploy or scale-down | Connections in flight to a draining replica | Lower keep-alive expiry, respect Connection: close, retry only idempotent methods |
| Everything healthy but latency is 3x | Pool is serialising behind one slow endpoint | Separate pools per dependency so a slow endpoint cannot starve a fast one |
One Client Per Dependency: Separate pools per dependency are a design decision, not a tuning knob. A single shared AsyncClient puts every endpoint of one origin in one queue, so a slow report endpoint consumes the connections a checkout call needs. One client per dependency, each with its own limits object, keeps the queues independent.
3. Keep-Alive Exhaustion: File Descriptors, Ports and Handshakes
The opposite mistake is invisible until it is expensive. Building an AsyncClient inside a request handler, or inside a Celery task, or per call in a loop, looks tidy: the client owns its own lifecycle, so nothing leaks. What it actually does is discard the connection every time, which means a fresh TCP handshake (and a fresh TLS handshake for https) per request, a socket in TIME_WAIT for every call, and a file descriptor churn rate that scales with traffic.
"""The two shapes that decide whether an httpx client survives production."""
from __future__ import annotations
import httpx
async def fetch_order_bad(order_id: str) -> dict:
"""WRONG: a new pool, a new TCP handshake and a new TLS session for every call."""
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(f"https://api.internal.example/orders/{order_id}")
response.raise_for_status()
return response.json()
async def fetch_order_good(client: httpx.AsyncClient, order_id: str) -> dict:
"""RIGHT: one long-lived client, a pooled connection and a bounded deadline."""
response = await client.get(
f"/orders/{order_id}",
timeout=httpx.Timeout(5.0, connect=1.0, pool=1.0),
)
response.raise_for_status()
return response.json()
The probe measured the difference over 200 sequential requests to the same origin. The client ran in its own process so the file descriptor counts belong to the client only, and each phase started against a fresh server so the connection counts are exact.
| Pattern | Concurrency | p50 | p99 | Wall for 200 req | Peak client FDs | TIME_WAIT delta | Server connections |
|---|---|---|---|---|---|---|---|
| One shared client | 1 | 0.8 ms | 1.4 ms | 309.1 ms | 8 | +1 | 1 |
| Client per request | 1 | 1.7 ms | 10.0 ms | 1,866.1 ms | 8 | +195 | 201 |
| One shared client | 50 | – | – | 1,479.9 ms | 57 | – | 51 |
| Client per request | 50 | – | – | 1,712.8 ms | 57 | – | 51 |
| One shared client | 200 | – | – | 2,128.5 ms | 107 | – | 201 |
| Client per request | 200 | – | – | 8,236.4 ms, 168 OK + 32 ReadTimeout | 207 | – | 169 |
Over loopback the handshake cost is close to zero, and the per-request pattern still took six times longer, because every call allocated and tore down an object graph and a socket. The counted damage is the last two columns: 201 server-side connections for 200 requests instead of one, and 195 sockets left in TIME_WAIT by a single two-second burst. On a real network each of those connections also pays a TCP round trip and, for https, a TLS handshake of one to two round trips plus certificate verification; against a cross-region dependency at 40 ms RTT that is 80 to 120 ms of latency added to every single request.
The arithmetic that turns churn into an outage is simple and worth memorising. A client’s usable ephemeral port range is finite: this container reports 32768-60999, which is 28,232 ports, and each closed connection holds one of them in TIME_WAIT for 60 seconds. A sustained 500 requests per second with a client per request would leave roughly 30,000 local ports in TIME_WAIT at any moment, which is more than the range holds for one destination. The arithmetic is approximate in both directions — the entry is keyed by destination address and port, and tcp_tw_reuse lets the kernel recycle a tuple it judges safe — but the conclusion does not depend on the exact count: at that rate the range runs out in about a minute. The error is not an HTTP status: it is OSError: [Errno 99] Cannot assign requested address or a ConnectError storm, and it arrives with zero load on the dependency.
File descriptors fail the same way, earlier than you expect. The container’s ulimit -n is 1024, the baseline process holds 8 descriptors, and 200 concurrent per-request clients peaked at 207. Under a per-request lifecycle the descriptor ceiling therefore arrives at roughly a thousand concurrent requests, and when it does, the exception is EMFILE raised from inside the event loop, which also breaks logging, metrics exporters and health checks that need a socket. Under a shared client the same 200 concurrent requests peaked at 107 descriptors, because the pool owns the sockets and reuses them.
The One Structural Rule: Create the client once, at startup, and close it at shutdown. In FastAPI that is a lifespan handler; in Celery it is a worker-init signal; in a script it is async with around the whole run. Every other placement is the anti-pattern in Table 6.
4. RemoteProtocolError: The Keep-Alive Race With Your Load Balancer
RemoteProtocolError: Server disconnected without sending a response. is the most misread exception in the httpx family. It means exactly one thing at the transport level: the connection closed before a complete HTTP response arrived. It does not say why, and the three causes have completely different fixes: the server crashed mid-request, a proxy timed out the request, or the pool reused a connection that the server had already closed as idle.
The third cause is the one that fools teams, because it is a race between two configuration values nobody wrote next to each other. The client’s keepalive_expiry defaults to 5 seconds; a load balancer’s idle timeout is typically 60 seconds but is frequently lowered to 10 or 15, and some proxies use 5. When the client’s value is the larger of the two, the pool is willing to hold a connection the server has already closed. It does not hand it over blind: httpcore checks the socket before reuse, and a socket that is readable while idle can only be about to return b"" — the FIN that ends the connection — so the pool drops that connection instead of using it (HTTP11Connection.has_expired() reads is_readable, and _assign_requests_to_connections() removes what expired). What is left is a boundary: the check passes on a connection that is still alive, the request is written, and the FIN arrives before the answer does. The write succeeded because the socket is half-closed, the read returns EOF, and a call that was already on the wire fails with RemoteProtocolError. The probe reproduced exactly that boundary with a server whose idle timeout is 0.3 s and a pool that keeps connections for 5 s, sampling the idle gap in four windows of 100 rounds each.
| Idle gap before reuse | 200 OK | RemoteProtocolError | Server connections |
|---|---|---|---|
| 0.280 – 0.300 s | 92 | 8 | 15 |
| 0.290 – 0.305 s | 95 | 5 | 57 |
| 0.295 – 0.315 s | 96 | 4 | 89 |
| 0.300 – 0.320 s | 100 | 0 | 101 |
The four rows are a microscope, not a traffic sample. Below the band the FIN has not arrived yet, so the connection is alive and reuse is perfect. Above it the FIN arrived before the pool looked, the connection was thrown away on that readability check and replaced, so nothing can fail — which is why the last row needs 101 connections for 100 requests. Only inside the 20-30 ms window does the close land between the check and the answer, and the 4 to 8 percent is the share of requests that lose that coin flip. Widen the gap and the client simply pays for a new connection instead, which is the cost Table 6 prices.
Two numbers in that table matter. In the first row, 100 requests opened only 15 connections and 8 of them died anyway: keep-alive was working, which is exactly when the race exists. In the last row, every request opened its own connection and nothing failed, because every reuse candidate was caught by the FIN check and replaced before a request could be written into it. A service that “fixed” its RemoteProtocolError by lowering keep-alive to zero has traded that 4 to 8 percent band for the full cost of Table 6.
A separate run makes the mechanism visible without a band: against the same 0.3 s server, ten requests spaced 50 ms apart reused a single connection and all answered 200; the same ten spaced one second apart — three times the server’s idle timeout, so the FIN had long since arrived — also answered 200, on six connections instead of one. The dead socket was detected and replaced, not used. That is the whole reason the failure is rare: it needs the close to happen while a request is already in flight.
The correct fix is still ordering, and now it is clear why: the client’s keepalive_expiry must be strictly shorter than every idle timeout on the path, including the load balancer, the ingress controller and the application server. A shorter expiry does not narrow the race, it removes it: the client closes the socket and drops it from the pool first, so the server’s FIN never finds a live entry. Fifteen seconds under a sixty-second load balancer is a safe default; five seconds under a five-second proxy is not. The production module enforces this at startup with a validation step that refuses to boot with an inverted pair, because the failure it prevents only appears under load.
The numbers to compare against are not guesses. Every server in the path ships an idle timeout, and the projects’ own defaults are far apart:
| Server | Setting | Default idle timeout | What it means for a 5 s client |
|---|---|---|---|
| uvicorn | --timeout-keep-alive | 5 s | A tie with httpx’s default: both sides close at the same moment |
Node.js http | server.keepAliveTimeout | 5 s | Same tie, and Node closes first under its own timer precision |
| Gunicorn | keepalive | 2 s | Below the client: the server closes first, so a reuse either finds the FIN and reconnects or races it |
| Apache httpd | KeepAliveTimeout | 5 s | Another tie, on a server nobody thinks of as a proxy |
| nginx | keepalive_timeout | 75 s | Safe for the default client; a client set to 90 s is not |
| Cloud load balancer (ALB-class) | idle timeout | 60 s | Safe for 5-15 s clients, unsafe for a 5-minute one |
That table is why server_idle_timeout in the module is a required field rather than a constant to copy, and why it has no default at all. The value to compare against is the smallest idle timeout on the path, and behind uvicorn or a bare Node server it is 5 s — the same number httpx uses by default, which is a tie and therefore a race. A defaulted 60 s would let a service pass validation against a number nobody looked up, which is the false confidence this table exists to remove; without a default, leaving the field out is a TypeError where the settings object is built. The module’s validation then refuses to start when the pair is inverted, which turns this table into a deploy-time error instead of a 4 percent error rate under peak traffic.
The other two causes, and why the retry decision differs
When the server closes the connection mid-request, or when a proxy’s request timeout fires, the client sees the same exception class but the request may well have been processed. That difference is the whole retry decision, and it is why the predicate in section 7 looks at the method and the status code rather than at the exception name alone. The probe measured all three transport outcomes against real sockets:
| Scenario | Exception | Measured latency | Safe to retry? |
|---|---|---|---|
| Connection closed before any response byte (50 calls) | RemoteProtocolError 50/50 | p50 1.3 ms, p99 72.2 ms | Only for idempotent methods or with an idempotency key: the server may have processed it |
| Connection accepted, no answer, read timeout 0.5 s (20 calls) | ReadTimeout 20/20 | p50 503.3 ms, p99 503.8 ms | Same as above: unknown outcome, so the method decides |
| Nothing listening on the port (20 calls) | ConnectError 20/20 | p50 0.6 ms, p99 1.1 ms | Yes, always: the request never left the client, so no side effect can exist |
The ConnectError row deserves attention for a second reason: it fails in 0.6 ms. A dependency that is down at the TCP level rejects attempts almost instantly, so a retry loop with no backoff and no breaker can issue thousands of attempts per second per client. That is the mechanism behind the storm in section 5, and it is why backoff must be measured against a connection that fails fast rather than a request that times out slowly.
Idempotency keys are necessary but not sufficient, and the probe makes the limit concrete. Twenty logical orders were sent as a POST whose response the server never delivered, retried up to three times. The server committed 60 charges: 40 duplicates. The client sent the same Idempotency-Key header on every attempt, and it made no difference, because the duplicate suppression has to be implemented and enforced by the server. Retrying a POST is only safe when the receiving service deduplicates on that key; without server-side support, the header is decoration.
Before You Retry Any POST: A retry policy is a contract with the server, not a client-side setting. Before enabling retries for a write, confirm three things: the endpoint accepts an idempotency key, the key is stored with the committed result, and a repeated key returns the original result instead of executing again.
5. Retry Storm Defense: Jitter, Budget and a Breaker
A retry multiplies load by design. Three attempts means three requests per logical call; add a timeout at the gateway and a queue at the dependency and the multiplication compounds. The probe measured the plain version of that fact: 100 logical requests, four attempts each, against a dependency answering 503 for the whole window, produced 400 requests at the server, an amplification of 4.0 with every policy tested.
Amplification alone is not the storm, though; synchronisation is. The probe timed every attempt on the client and measured how tightly each retry wave bunched, defined as the largest number of retries landing inside any 10-millisecond window. A fixed delay keeps every client in lockstep, and so does exponential backoff without jitter, because doubling the same interval for every client still produces the same instant.
| Policy | Attempts | Amplification | Wave 2 peak/10 ms | Wave 3 | Wave 4 | Wall clock |
|---|---|---|---|---|---|---|
| Fixed 200 ms, no jitter | 400 | 4.00 | 40 | 28 | 20 | 2.86 s |
| Exponential 200 ms, no jitter | 400 | 4.00 | 33 | 29 | 26 | 2.91 s |
wait_exponential (tenacity, no jitter) | 400 | 4.00 | 27 | 24 | 18 | 3.55 s |
| Full jitter, uniform(0, 200 ms × 2n) | 400 | 4.00 | 6 | 5 | 4 | 3.76 s |
wait_random_exponential (tenacity) | 400 | 4.00 | 5 | 4 | 3 | 2.82 s |
Full jitter held the herd to 6 requests per 10 ms in every run, while the fixed and unjittered policies landed 31 to 44 in the same window across three runs of the script — a factor of five to seven, without changing the number of attempts or the time to give up. That is the entire argument for jitter: it does not reduce load, it spreads it, and spreading is what keeps a recovering dependency below the concurrency that killed it.
Jitter is necessary and still insufficient, because it bounds the shape of the retries and not the decision to make them. During a real outage every caller keeps retrying forever, each with a well-behaved jittered backoff, and the dependency never gets the quiet second it needs to recover. The component that stops this is a circuit breaker, and its effect is measurable in requests that never happen: 100 logical calls issued one at a time with a 5-25 ms gap — a 1.5 s arrival window — against a permanent 503 produced 400 requests without a breaker and 156 with one, an amplification of 1.56 instead of 4.0.
| Variant | Requests reaching upstream | Amplification | Rejected client-side | p50 of rejection | Breaker trips | Wall clock |
|---|---|---|---|---|---|---|
| No breaker | 400 | 4.00 | 0 | – | 0 | 2.64 s |
| Breaker, threshold 5, reset 1 s | 156 | 1.56 | 61 | 0.0 ms | 7 | 1.52 s |
The 61 rejected calls returned in essentially zero milliseconds, because the breaker refuses before any socket is opened. That is the second benefit: a failing dependency stops costing the caller thread time, connection attempts and timeout waits, and the service keeps answering on its own responsibility even while one dependency is unavailable. Trips reached 7 because the breaker’s half-open probe kept being admitted and kept failing, which is the intended sawtooth of a dependency that is still down.
Retries Are Not Resilience On Their Own: Retries protect against transient failures. Breakers protect against sustained ones. A service with retries and no breaker converts a two-second dependency blip into a two-minute outage; a service with a breaker and no retries turns every blip into a user-visible error even though a second attempt would have worked. Production needs both, sized against the same budget.
6. The Retry Predicate: Decide By Effect, Not By Exception Name
Most retry bugs are predicate bugs. A decorator that retries “any exception” will retry a 400 caused by malformed input five times, spend the request budget, and report a timeout. A predicate that retries only TimeoutException will miss the ConnectError that is instantly retryable and the 503 that carries a Retry-After worth honouring. The question to ask about every failure is not “what class is it” but “could the server have already acted on this request”.
"""Which httpx failures are safe to retry, and which only make an outage worse.
The decision is a function of the exception class, the HTTP method and whether the
request carried an idempotency key, because "did the server see it, and did it act
on it?" is the only question that matters for a retry.
"""
from __future__ import annotations
import httpx
IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"})
#: The server refused before doing any work: 408 never received the request, 425 and
#: 429 are explicit "not now", 503 has no capacity. Repeating one cannot duplicate a
#: side effect, so these are retryable for every method.
REFUSED_STATUS = frozenset({408, 425, 429, 503})
#: The server may have started the work and lost the answer. Safe only when the call
#: itself is safe to repeat: 500, 502 and 504 can each follow a committed write.
UNKNOWN_STATUS = frozenset({500, 502, 504})
RETRYABLE_STATUS = REFUSED_STATUS | UNKNOWN_STATUS
#: The request never reached the server, so it cannot have been processed.
NEVER_SENT = (httpx.ConnectError, httpx.ConnectTimeout)
#: The request may have been processed even though the client saw no answer.
AMBIGUOUS = (httpx.RemoteProtocolError, httpx.ReadTimeout, httpx.WriteTimeout, httpx.ReadError)
#: The client had no connection to spend: retrying immediately makes the queue worse.
CAPACITY = (httpx.PoolTimeout,)
class RetryableStatus(httpx.HTTPStatusError):
"""A status code a bounded retry may resolve, carrying the response for Retry-After."""
@property
def retry_after(self) -> float | None:
header = self.response.headers.get("Retry-After")
if header is None:
return None
try:
return float(header)
except ValueError:
return None
def is_retryable(exc: BaseException, method: str, idempotency_key: str | None = None) -> bool:
"""Return True only when another attempt cannot duplicate a side effect."""
safe = method.upper() in IDEMPOTENT_METHODS or idempotency_key is not None
if isinstance(exc, RetryableStatus):
code = exc.response.status_code
if code in REFUSED_STATUS:
return True
return code in UNKNOWN_STATUS and safe
if isinstance(exc, AMBIGUOUS):
return safe
return isinstance(exc, NEVER_SENT)
def retry_after_seconds(exc: BaseException, cap: float = 30.0) -> float | None:
"""Honour Retry-After when the server states it, bounded by `cap`."""
if isinstance(exc, RetryableStatus) and exc.retry_after is not None:
return min(exc.retry_after, cap)
return None
Three details in that module are load-bearing. NEVER_SENT is retryable for every method, including POST, because a connection that was never established cannot have produced a side effect; that single rule recovers most of the transient failures in a blue-green rollout. AMBIGUOUS is retryable only when the method is idempotent or an idempotency key is present, which is the only honest way to describe a request whose response was lost. CAPACITY is deliberately not retried: a PoolTimeout means the client has no connection to spend, and retrying it immediately pushes more work into the same queue.
The status codes get the same treatment, and this is the part most retry decorators get wrong. A 503 means the server had no capacity to do the work, and a 408, 425 or 429 means it declined or never received the request: repeating any of those cannot duplicate a side effect, so they are retryable for every method. A 500, 502 or 504 is different in kind — the server may have committed the write and then lost the answer, exactly like a dropped connection — so those three are retried only when the call is safe to repeat. The probe makes the difference visible with the same POST against two endpoints: three attempts against a 503, and exactly one against a 500 that had already charged the order, because a second attempt would have been a second charge. Add an Idempotency-Key and the same 500 is retried three times; whether that is safe depends on the server actually deduplicating, which in the probe it does not: three attempts committed three charges.
Of those, 429 is the one that usually arrives with a Retry-After header stating exactly how long the server wants you to wait, and honouring it is not politeness: it is the difference between a queue that drains and one that is hammered. A 425 or a 503 can carry the same header, and the wait strategy reads it from any of them. The effect is visible in the attempt timeline of the next section: attempts at 0, 1,003 and 2,007 milliseconds, because that endpoint answers 503 with Retry-After: 1 and the client waited the second the server asked for.
7. The Client: Settings, Pool, Timeout and One Request Function
What follows is the module the probes ran, not a sketch of one. It is assembled from a frozen settings object, a factory that builds exactly one client, and a single function that every call site uses, so the retry policy and the breaker cannot be bypassed by a convenient direct client.get() somewhere in the codebase.
Budgets, timeouts and a wait strategy that honours Retry-After
"""Budgets for one egress dependency, expressed as objects that can be validated."""
from __future__ import annotations
import logging
import random
from dataclasses import dataclass, field
import httpx
from .retry_policy import retry_after_seconds
log = logging.getLogger("egress.http")
@dataclass(frozen=True)
class EgressSettings:
"""Every number here is a budget, and each one has to leave room for the next."""
#: The smallest idle timeout anywhere on the path to this dependency, in seconds.
#: There is deliberately no default: uvicorn and Node ship 5 s, Gunicorn 2 s,
#: nginx 75 s and most cloud load balancers 60 s, so a copied constant validates a
#: service against a server it may never talk to. Look the number up per platform
#: and pass it in; leaving it out is a TypeError where the settings are built.
server_idle_timeout: float
base_url: str = "https://api.internal.example"
max_connections: int = 40
max_keepalive_connections: int = 20
keepalive_expiry: float = 15.0
connect_timeout: float = 2.0
read_timeout: float = 5.0
write_timeout: float = 5.0
pool_timeout: float = 2.0
request_budget: float = 9.0
max_attempts: int = 3
backoff_base: float = 0.15
backoff_max: float = 1.5
breaker_threshold: int = 5
breaker_reset: float = 10.0
def validate(self) -> None:
"""Fail at startup, not at 03:00, when the arithmetic cannot work."""
if self.max_keepalive_connections > self.max_connections:
raise ValueError("max_keepalive_connections cannot exceed max_connections")
# server_idle_timeout has no default, so a missing value cannot slip through this
# check with a 60 s guess standing in for the platform actually in front of us.
if self.keepalive_expiry >= self.server_idle_timeout:
raise ValueError(
f"keepalive_expiry ({self.keepalive_expiry}s) must stay below the server's "
f"idle timeout ({self.server_idle_timeout}s) or every reuse races a close"
)
per_attempt = self.connect_timeout + self.read_timeout
if self.max_attempts * per_attempt > self.request_budget:
log.warning(
"attempt budget %.1fs exceeds the %.1fs request budget: retries will be cut short",
self.max_attempts * per_attempt,
self.request_budget,
)
@property
def worst_case_attempts_seconds(self) -> float:
"""What the retry layer can spend before backoff is added."""
return self.max_attempts * (self.connect_timeout + self.read_timeout)
@dataclass
class EgressMetrics:
"""Counters to export; the ratio of retries to requests is the storm in one number."""
requests: int = 0
retries: int = 0
transport_errors: int = 0
pool_timeouts: int = 0
short_circuited: int = 0
in_flight: int = 0
peak_in_flight: int = 0
breaker_state: int = 0
durations: list[float] = field(default_factory=list)
error_classes: dict[str, int] = field(default_factory=dict)
def record(self, elapsed: float) -> None:
"""One successful attempt, timed from the request hook (so the queue is included)."""
self.durations.append(elapsed)
if len(self.durations) > 1000:
del self.durations[:500]
def enter(self) -> None:
"""One attempt starts: it is now demand on the pool, holder or waiter."""
self.in_flight += 1
self.peak_in_flight = max(self.peak_in_flight, self.in_flight)
def leave(self) -> None:
self.in_flight -= 1
def record_error(self, exc: BaseException) -> None:
"""Transport failures are only useful by class: RemoteProtocolError means two things."""
self.transport_errors += 1
name = type(exc).__name__
self.error_classes[name] = self.error_classes.get(name, 0) + 1
def timeout_for(settings: EgressSettings) -> httpx.Timeout:
"""One timeout object, so no phase can silently default to five minutes."""
return httpx.Timeout(
timeout=settings.request_budget,
connect=settings.connect_timeout,
read=settings.read_timeout,
write=settings.write_timeout,
pool=settings.pool_timeout,
)
def wait_strategy(settings: EgressSettings):
"""Full jitter, overridden by the server's own Retry-After when it states one."""
def wait(state) -> float:
outcome = state.outcome
if outcome is not None and outcome.exception() is not None:
forced = retry_after_seconds(outcome.exception())
if forced is not None:
return forced
ceiling = min(settings.backoff_max, settings.backoff_base * 2 ** (state.attempt_number - 1))
return random.uniform(0, ceiling)
return wait
The validation is not defensive decoration. An inverted keep-alive pair is the race in Table 7, and it is invisible in review because the two numbers are set in different files, by different teams, for different reasons. Making startup fail on that combination converts that 4 to 8 percent band into a message in the deploy log — and the field it compares against has no default, so a service that never looked up its platform’s idle timeout fails when the settings are built instead of validating happily against a 60 s guess.
The wait strategy inside tenacity
The wait strategy is where tenacity earns its place. Its AsyncRetrying hands the wait callable the full retry state, including the exception that failed, so a Retry-After header can override the computed backoff without leaving the retry loop. Everything else falls through to full jitter: a uniform draw between zero and the exponential ceiling, which is the policy that produced the 6-per-10-ms wave in Table 10.
One client, one request function, hooks for latency
"""The egress client this runbook prescribes: one pool, one budget, jittered retries, a breaker."""
from __future__ import annotations
import asyncio
import logging
import time
import httpx
from tenacity import AsyncRetrying, retry_if_exception, stop_after_attempt
from .breaker import BreakerOpen, BreakerState, CircuitBreaker
from .retry_policy import RETRYABLE_STATUS, RetryableStatus, is_retryable
from .settings import EgressMetrics, EgressSettings, timeout_for, wait_strategy
log = logging.getLogger("egress.http")
#: The value exported for the breaker gauge: 0 closed, 1 half-open, 2 open.
BREAKER_STATE_CODE = {BreakerState.CLOSED: 0, BreakerState.HALF_OPEN: 1, BreakerState.OPEN: 2}
def build_client(settings: EgressSettings, metrics: EgressMetrics) -> httpx.AsyncClient:
"""Create the one long-lived client. Never build this per request."""
settings.validate()
limits = httpx.Limits(
max_connections=settings.max_connections,
max_keepalive_connections=settings.max_keepalive_connections,
keepalive_expiry=settings.keepalive_expiry,
)
async def on_request(request: httpx.Request) -> None:
request.extensions["tb_started"] = time.perf_counter()
log.debug("-> %s %s", request.method, request.url.path)
async def on_response(response: httpx.Response) -> None:
started = response.request.extensions.get("tb_started")
if started is not None:
metrics.record(time.perf_counter() - started)
log.debug("<- %s %s", response.status_code, response.request.url.path)
# httpx builds a transport from `limits` only when it is allowed to build the
# transport itself, so a client that hands in its own transport silently keeps
# httpcore's defaults (100 connections / 20 keep-alive / 5 s). The limits have to
# travel with the transport as well; bench_limits.py measures both variants.
transport = httpx.AsyncHTTPTransport(retries=0, limits=limits)
return httpx.AsyncClient(
base_url=settings.base_url,
limits=limits,
timeout=timeout_for(settings),
transport=transport,
event_hooks={"request": [on_request], "response": [on_response]},
)
async def fetch(
client: httpx.AsyncClient,
breaker: CircuitBreaker,
settings: EgressSettings,
metrics: EgressMetrics,
method: str,
path: str,
*,
idempotency_key: str | None = None,
body: dict | None = None,
) -> httpx.Response:
"""One logical call: bounded retries, jittered waits, and a hard wall-clock budget."""
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
retrying = AsyncRetrying(
retry=retry_if_exception(lambda exc: is_retryable(exc, method, idempotency_key)),
wait=wait_strategy(settings),
stop=stop_after_attempt(settings.max_attempts),
reraise=True,
)
def guard() -> bool:
"""Ask the breaker for permission and export the state it answered with.
Returns True only when this call was given a half-open probe slot, which is
the token the finally block needs to hand that slot back.
"""
try:
owns_probe = breaker.before_call()
except BreakerOpen:
metrics.short_circuited += 1
metrics.breaker_state = BREAKER_STATE_CODE[breaker.state]
raise
metrics.breaker_state = BREAKER_STATE_CODE[breaker.state]
return owns_probe
try:
async with asyncio.timeout(settings.request_budget):
async for attempt in retrying:
with attempt:
owns_probe = guard()
metrics.requests += 1
metrics.retries += int(attempt.retry_state.attempt_number > 1)
metrics.enter()
try:
response = await client.request(method, path, json=body, headers=headers)
if response.status_code in RETRYABLE_STATUS:
breaker.on_failure()
raise RetryableStatus(
f"{response.status_code} from {method} {path}",
request=response.request,
response=response,
)
breaker.on_success()
return response
except httpx.TransportError as exc:
metrics.record_error(exc)
if isinstance(exc, httpx.PoolTimeout):
metrics.pool_timeouts += 1
breaker.on_failure()
raise
finally:
# Every exit path, cancellation included, returns the slot and
# the half-open probe it actually took: a probe nobody releases
# locks the breaker, and a probe released by a call that never
# held one frees a slot another live probe is using.
metrics.leave()
if owns_probe:
breaker.release_probe()
metrics.breaker_state = BREAKER_STATE_CODE[breaker.state]
except TimeoutError as exc:
raise httpx.TimeoutException(
f"request budget of {settings.request_budget}s exhausted for {method} {path}"
) from exc
raise RuntimeError("retry loop exited without returning a response")
AsyncHTTPTransport(retries=0) is deliberate. The transport can retry at connection setup, but those retries are invisible to your metrics, your breaker and your outage budget, so the policy lives one layer up where it can be counted. The same object carries the limits, and that is not redundancy: a client that passes its own transport never has its own limits consulted (Table 4), so the cap above is the value the pool actually enforces. The event hooks record the wall-clock duration of every response in the same place, which is the only latency number that includes the queue wait the pool imposed.
The finally block inside the retry body is the part that is easy to leave out. It returns the in-flight count, hands back a half-open probe this call actually held, and refreshes the breaker gauge, on every exit path including cancellation. Without it a probe that is cancelled by the request budget leaves the breaker half-open with a slot nobody holds, which is the bug the next section describes.
What the request function guarantees
Three properties of that function are worth naming. The outer asyncio.timeout() gives the logical call a real deadline that no phase-level timeout can exceed, which is the gap identified in section 2. The breaker is consulted inside the retry body, so a breaker that opens mid-retry stops the remaining attempts instead of letting them run against a dependency that has just been declared down. And every exit path updates one of four counters, so the retry ratio is always available as a metric rather than something to reconstruct from logs.
The breaker itself
"""A closed / open / half-open circuit breaker small enough to audit.
The breaker is the only component in this design that reduces load during an
outage; retries can only add to it. It is driven by the same loop that makes the
calls, so it needs no lock as long as one event loop owns the client.
"""
from __future__ import annotations
import time
from dataclasses import dataclass, field
from enum import Enum
class BreakerState(str, Enum):
CLOSED = "closed"
OPEN = "open"
HALF_OPEN = "half_open"
class BreakerOpen(RuntimeError):
"""Raised instead of calling a dependency the breaker has stopped trusting."""
@dataclass
class CircuitBreaker:
failure_threshold: int = 5
reset_timeout: float = 10.0
half_open_max_calls: int = 1
state: BreakerState = field(default=BreakerState.CLOSED, init=False)
opened_at: float = field(default=0.0, init=False)
_failures: int = field(default=0, init=False)
_probes: int = field(default=0, init=False)
_trips: int = field(default=0, init=False)
@property
def trips(self) -> int:
"""How many times this breaker has opened, the metric worth alerting on."""
return self._trips
@property
def probes(self) -> int:
"""Probes currently holding a half-open slot, the counter that can leak."""
return self._probes
def before_call(self) -> bool:
"""Ask permission to call; True means this call took a half-open probe slot.
The return value is the ownership token for release_probe(): only a call that
answered True owns a slot, and only an owner may give one back. A call admitted
while the breaker was closed owns nothing, even if the breaker is half-open by
the time that call ends.
"""
if self.state is BreakerState.OPEN:
if time.monotonic() - self.opened_at >= self.reset_timeout:
self.state = BreakerState.HALF_OPEN
self._probes = 0
else:
remaining = self.reset_timeout - (time.monotonic() - self.opened_at)
raise BreakerOpen(f"open, {remaining:.2f}s until the next probe")
if self.state is BreakerState.HALF_OPEN:
if self._probes >= self.half_open_max_calls:
raise BreakerOpen("half-open probe already in flight")
self._probes += 1
return True
return False
def release_probe(self) -> None:
"""Give back the half-open slot this call took, when it ended without a verdict.
A probe is counted in before_call(), but only on_success() and on_failure()
clear it. A probe that is cancelled in between (task cancellation, or the
asyncio.timeout() budget firing) leaves the counter at 1, and from then on
every call is refused with "half-open probe already in flight" even though
nothing is in flight: the breaker stays half-open for the life of the process.
A caller that owns the probe must release it in a finally block.
Ownership, not politeness: release only when before_call() returned True. A
call that started while the breaker was closed can still be running after the
breaker has tripped, waited out its reset window and admitted somebody else's
probe; an unconditional release in that call's finally block would decrement a
slot it never held, and the next call would be admitted beside a live probe.
"""
if self._probes > 0:
self._probes -= 1
def on_success(self) -> None:
"""The call worked: back to closed, with the failure count and probes cleared."""
self.state = BreakerState.CLOSED
self._failures = 0
self._probes = 0
def on_failure(self) -> None:
self._failures += 1
if self.state is BreakerState.HALF_OPEN or self._failures >= self.failure_threshold:
self._trip()
def _trip(self) -> None:
self.state = BreakerState.OPEN
self.opened_at = time.monotonic()
self._failures = 0
self._probes = 0
self._trips += 1
The breaker is deliberately small: closed, open, half-open with a single permitted probe. It has no lock because one event loop owns it, and no persistence because a breaker that survives a restart would keep the new process from probing a dependency that has already recovered. The one subtlety worth copying is that the half-open probe is counted before the call, so a slow probe cannot be joined by a second probe and turn recovery into another burst.
The price of that design is a counter that can leak, and it is a bug this runbook had to fix in its own module. The probe is counted in before_call() and cleared by on_success() or on_failure(). A probe that is cancelled in between — the asyncio.timeout() budget firing, or the calling task being cancelled — reaches neither, so the counter stays at 1 and every later call is refused with “half-open probe already in flight” for the life of the process, long after the dependency recovered. release_probe() closes the hole, and the test behind it does the A/B: with release_probe() stubbed out, the call after a cancelled probe is refused with exactly that message and the breaker never closes; with it, the same call answers 200 and the breaker returns to closed.
That fix has a second-order bug of its own, and it is worth naming because the same finally shape creates it. A release that runs on every exit path releases slots the call never took. A slow request admitted while the breaker was closed can still be in flight when the breaker trips, waits out its reset window and goes half-open; if that request ends now, its finally decrements the counter belonging to the probe that is actually running. The counter then reads zero while a probe is live, the next caller is admitted beside it, and the single-probe design turns recovery into the burst it was supposed to prevent. before_call() therefore returns whether it took a slot, and only an owner gives one back: if owns_probe: breaker.release_probe(). The test drives both bugs, including a closed-state call cancelled while another call holds the only probe — the live slot stays at 1, where an unconditional release would have freed it and admitted a second probe beside it.
The end-to-end probe exercised exactly this module against the probe server, which is the difference between an article and a code review.
| Case | Outcome | Attempts (client timestamps) | Server-side effect |
|---|---|---|---|
| Dependency fails twice, then answers 200 | HTTP 200 | 3 (0, 97, 147 ms) | Two retries, breaker stayed closed |
| Dependency answers 503 forever, breaker threshold 2, reset 0.5 s | RetryableStatus 503 | 3 (0, 1,003, 2,007 ms) | Retry-After: 1 honoured; breaker tripped twice, ended open |
| Next call while the breaker is open | BreakerOpen, “0.48 s until the next probe” | 0 | No socket opened at all |
POST whose response was lost, with Idempotency-Key | RemoteProtocolError | 3 (0, 91, 213 ms) | 3 charges committed for 1 order: the server does not deduplicate |
| Same POST without a key | RemoteProtocolError | 1 (0 ms) | 1 charge |
The second row of the timeline is the most useful lesson in the table. The breaker’s reset window was shorter than the backoff the server had asked for, so each retry arrived after the breaker had moved to half-open and was admitted as a probe. It failed, re-tripped the breaker, and the cycle repeated. A breaker’s reset timeout has to be longer than your backoff plus the largest Retry-After you are willing to honour, or every retry becomes a probe and the breaker becomes a slow retry loop with extra state.
8. Observability: The Five Numbers That Identify Which Failure You Have
All four failure modes produce the same user-visible symptom, an elevated error rate with normal CPU, so the on-call diagnosis comes from five client-side numbers. All five are cheap: they are counters and histograms maintained by the code that makes the call, which is why the production module keeps them in a plain object rather than parsing access logs after the fact.
| Metric | Field in EgressMetrics | Definition | Alert threshold (starting point) | What it distinguishes |
|---|---|---|---|---|
egress_attempts_per_call | requests, retries | Attempts per logical call | > 1.5 for 5 min | Retry storm in progress |
egress_request_seconds | durations | Per-attempt duration from the request hook, so the pool wait is inside it | p99 > 60% of the request budget | The queue growing before PoolTimeout fires |
egress_in_flight | in_flight, peak_in_flight | Attempts issued and unanswered: slot holders plus waiters. Counted per attempt, so a call in its second attempt counts once for that attempt | At max_connections for 10 min | Which dependency needs a bigger pool |
egress_transport_errors_total | transport_errors, error_classes | Transport failures by exception class | RemoteProtocolError > 1% of calls | Keep-alive race versus a real outage |
egress_pool_timeouts_total | pool_timeouts | Calls that never got a connection at all | Any increase | Client-side capacity failure: the dependency was never asked |
EgressMetrics object in section 7, that separate the four failure modes in Table 1.Two of these deserve a note on instrumentation. httpx does not export the moment a request is handed a pool slot, so there is no honest pool-wait timer to read: what the module exports instead is the duration timed from the request hook, which fires before the pool is consulted and therefore contains the queue wait, plus the in-flight gauge that shows the queue forming. That gauge is per attempt, not per logical call, because a retry in backoff is not holding or waiting for a connection; the attempts-per-call ratio above it is what turns the two into a caller count. PoolTimeout is the one case where the wait is measurable to the millisecond, because the elapsed time of the exception is the deadline that expired (201 ms for a 200 ms deadline in Table 4) — and it is also the one case that never reaches the histogram, which is why it is a counter of its own. And transport errors must be counted by exception class, because RemoteProtocolError with a healthy dependency is a configuration bug in the client, while the same class during a deployment is a fact about the deployment; the class alone cannot tell them apart, but the class together with the idle-gap correlation can. The same object also carries short_circuited and breaker_state, so the two numbers that say “load was removed on purpose” come from the same snapshot as the rest.
9. The Checklist: Shipping An Egress Client In A New Service
The order matters, because each step constrains the next. Budget first, then pool, then keep-alive, then retries, then the breaker, and only then the metrics that prove the whole thing behaves.
| Step | Decision | Rule of thumb | Failure it prevents |
|---|---|---|---|
| 1 | Latency budget per dependency | Set by the caller’s SLO, not by the dependency’s p99 | Unbounded waits hidden behind phase timeouts |
| 2 | Pool size | peak_rps × p99_latency, plus 20% headroom, ceiling by database limits | PoolTimeout under normal load |
| 3 | Pool deadline | About 25% of the latency budget, never the default 5 s in a 1 s budget | Queueing that outlives the caller’s patience |
| 4 | Keep-alive expiry | Strictly below every idle timeout on the path; 15 s under a 60 s balancer | RemoteProtocolError bursts from a reuse race |
| 5 | Retry predicate | Effect-based: never-sent always, a refused status always, 500/502/504 only when safe | Duplicate side effects and retried 4xx |
| 6 | Backoff | Full jitter, cap below the caller’s patience | Synchronised retry waves |
| 7 | Breaker | Threshold 5, reset above backoff plus Retry-After | Sustained outages amplified by retries |
| 8 | Metrics and alerts | The five numbers in Table 13, exported from the same code path | Diagnosis by guesswork |
One deployment detail closes the loop. During a rolling deploy, old and new pods share the dependency, so a client that retries aggressively during connection resets will multiply load exactly while the fleet is half-sized. That is why ConnectError and ConnectTimeout are retryable for every method including POST: during a rollout, the dominant failure is a connection refused by a pod that has already gone, and it can be retried without any risk of a duplicate charge.
10. Verification: What Was Measured, and How To Re-run It
Every number in this article came from a probe in the article’s sandbox, not from a vendor benchmark and not from intuition. The environment was Python 3.12.16, httpx 0.28.1, httpcore 1.0.9, anyio 4.16.0, tenacity 9.2.1, on a two-vCPU Linux container with ulimit -n of 1024 and an ephemeral port range of 32768-60999. The dependency under test was an instrumented http.server.ThreadingHTTPServer on loopback with HTTP/1.1 keep-alive, Content-Length on every response and TCP_NODELAY enabled, running in its own process so that client file descriptor counts are the client’s alone.
The probes are six scripts, each of which writes a JSON log: bench_pool.py for the pool matrix and the wait accounting, bench_keepalive.py for the lifecycle comparison, bench_protocol.py for the transport failures, keep-alive race and duplicate charges, bench_retry.py for the policy comparison and the breaker, bench_limits.py for where the pool limit comes from and what happens at the cap, and bench_client.py for the production module end to end. Two more scripts are assertions rather than benchmarks — test_breaker_cancel.py and test_retry_policy.py — and they exit non-zero on failure; the numbers quoted in sections 6 and 7 come from their output. Every Python block in this article is extracted verbatim from modules those scripts import and was parsed with ast.parse and checked with pyflakes before publication.
Three limitations are worth stating rather than hiding. Loopback removes network latency, so the per-request lifecycle in Table 6 is understated relative to a cross-region dependency, where each connection costs one to three round trips; the measured 6x wall-clock gap is a floor, not a ceiling. The probe server is a thread per connection, which is why the 200-way per-request run produced 32 ReadTimeout exceptions: that number reflects the probe’s accept throughput, not a client defect — and it is also why the 41-caller runs in section 2 are quoted as connection counts rather than as latencies. And the file descriptor peak of 207 for the per-request pattern would have been higher if the server had shared the process, which is exactly why the probes were split into two processes.
One measurement artefact turned into its own lesson. The first version of the probe server did not set TCP_NODELAY, and sequential keep-alive requests measured 44.0 ms p50 while the per-request pattern measured 2.5 ms, which looked like an argument against keep-alive. It was not: the server wrote headers and body in two segments and paid Nagle plus delayed-ACK on every request. With TCP_NODELAY the same keep-alive path measured 0.8 ms p50. If a benchmark tells you keep-alive is slower, check the server’s socket options before you believe it.
Frequently Asked Questions
Q: Should I raise max_connections or lower the pool timeout when I see PoolTimeout? Neither, immediately. Find out whether the queue is caused by concurrency above your pool size or by latency above your budget, because those have opposite fixes. If concurrency is legitimately higher than the pool, size the pool with peak_rps × p99; if latency grew, the pool is a symptom and a bigger pool moves the queue to the dependency, where it is more expensive.
Q: Why does timeout=30 not stop a request after thirty seconds? Because the number is copied into connect, read, write and pool as four separate allowances, not into one clock that starts when the call does; each phase may spend its whole allowance, so the ceiling is roughly four times the number you wrote. Write httpx.Timeout(30.0, connect=2.0, pool=1.0) when you mean a default with two exceptions, and asyncio.timeout() around the logical call when you need one ceiling that also covers retries.
Q: Is RemoteProtocolError always a keep-alive problem? No, and the distinction changes the response. If the error rate correlates with traffic that follows an idle period, it is the reuse race in Table 7 and the fix is configuration. If it correlates with a deployment, a restart or a dependency’s own error rate, the peer is dying mid-request and the fix is capacity or a breaker. Both produce the same exception string.
Q: How many retries are enough? Two to three attempts for transient failures, never more than the latency budget can afford. With a 900 ms budget and a 300 ms dependency, three attempts plus backoff already consume most of it; four attempts guarantee that a slow dependency becomes a timeout for the caller. The number of attempts is a budget decision, not a resilience decision.
Q: Do I need a circuit breaker if I already have retries with jitter? Yes, if the dependency can be down for longer than a few seconds. Jitter only decides when the retries arrive, not whether they arrive; a permanently failing dependency receives an amplified, well-spaced stream of attempts forever. The breaker is the only component in the design that reduces the number of requests, and Table 11 measures the reduction: 400 to 156.
Q: HTTP/2 changes any of this? Some of it. Multiplexing removes the one-request-per-connection limit so a small pool serves far more concurrency, and GOAWAY gives the peer an explicit way to retire a connection instead of racing an idle timeout. The pool accounting, the retry predicate and the breaker are unchanged, because they are about effects and budgets rather than about the wire protocol.
Closing: The Client Is Part Of The Dependency’s Capacity
The uncomfortable common thread is that the client is not a passive consumer of a dependency’s capacity; it is part of that capacity’s arithmetic. A pool that is too small refuses work the dependency could have done, a lifecycle that churns connections spends ports the kernel needs elsewhere, and a retry policy that fires in lockstep is an amplifier wired directly into an incident. None of that appears in a dependency’s dashboard, which is why the four failure modes in this runbook are so often attributed to the wrong system for the first hour.
The design that survives is deliberately boring: one client per dependency created at startup, a pool sized by arithmetic, a keep-alive lifetime shorter than every timeout on the path, a retry predicate that reasons about side effects, full jitter behind every backoff, a breaker that is the only component allowed to give up, and five metrics that make the difference visible before the customer notices.
To go deeper on the layers around this one, read the companion runbooks: asyncio concurrency in Python for the event-loop mechanics behind thousands of concurrent requests, FastAPI on Gunicorn and UvicornWorker for the worker model that hosts this client, Redis caching and distributed locks for the cache that absorbs the load retries would otherwise send to the database, and Celery production architecture for moving long calls out of the request path entirely.
Related production runbooks: SQLAlchemy 2.0 async in production for the same pool arithmetic applied to database sessions, memory leaks in Celery and asyncio workers for the growth that a per-request client hides inside the heap, Kubernetes pod tuning and OOMKilled defense for the file descriptor and memory limits that cap this pool, and PostgreSQL slow query optimization for the latency that makes the pool queue in the first place.
Two more from the library frame the rest of the stack: Docker multi-stage builds and distroless images for Python, which is how the container above ships with a predictable descriptor and memory budget, and The TechBobby Stack, the tooling map this runbook belongs to.
Download the AI Prompt Master Pack for Engineers ($0+ Pay What You Want), with curated prompts for incident timelines, pool budget calculations and postmortem drafts: Get the AI Prompt Master Pack on Gumroad →
Subscribe to the TechBobby Substack for one measured production runbook a week: runtime internals, HTTP client behaviour, database scaling, and the deployment mechanics that decide whether your p99 survives a Tuesday.
