← Back to FastAPI, page 3

fastapi-0048 · Hard senior

How do you call other services reliably from FastAPI with httpx: shared clients, timeouts, retries and concurrency limits?

Create one httpx.AsyncClient per process in lifespan so connections are pooled, set explicit timeouts (connect, read, write, pool), retry only safe or idempotent calls with exponential backoff and jitter on network errors and 502/503/504, bound concurrency with a semaphore or client limits, and turn upstream failures into clear 502/503/504 responses. Consider circuit breakers and caching when a dependency is unstable. Test with httpx.MockTransport.

Full answer

Calling another service is where most latency and outages come from. A good client has these parts.

One shared client. httpx.AsyncClient() keeps a connection pool with keep-alive. Creating a client per request skips pooling and costs a TLS handshake each time. Create it in lifespan, store it on app.state, close it on shutdown.

Timeouts. httpx defaults to 5 seconds per phase, but set them explicitly: httpx.Timeout(connect=1, read=3, write=3, pool=1). pool is how long to wait for a free connection. A missing timeout turns one slow upstream into a pile of stuck requests.

Retries. Retry only when it is safe:

  • idempotent methods (GET, PUT, DELETE), or POSTs that carry an idempotency key,
  • errors that are probably temporary: connect errors, read timeouts, 502, 503, 504, 429 (honouring Retry-After).
  • Use exponential backoff with jitter (0.1s, 0.2s, 0.4s plus random) and a small maximum (2 to 3 retries), and keep the total under the caller's own deadline. Retrying at every layer multiplies traffic (a retry storm).
  • httpx.AsyncHTTPTransport(retries=n) only retries connection failures. For status-based retries use a loop or a library such as tenacity or stamina.

Limits. httpx.Limits(max_connections=100, max_keepalive_connections=20) bound sockets. A semaphore bounds how many concurrent calls one request fan-out can make.

Failure mapping. Convert upstream problems to proper responses: timeout to 504, connection error or bad upstream status to 502 or 503, with a short message and a log line carrying the request ID. Never leak upstream bodies blindly.

Circuit breaker. After many failures, stop calling for a cool-down period and fail fast, protecting both services. Add fallbacks (cached data) where acceptable.

Testing. httpx.MockTransport(handler) simulates timeouts and 503s with no network.

python
import asyncio
import random
from contextlib import asynccontextmanager

import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.testclient import TestClient

calls = {"n": 0}


def fake_upstream(request: httpx.Request) -> httpx.Response:
    calls["n"] += 1
    if request.url.path == "/flaky":
        if calls["n"] < 3:
            return httpx.Response(503, text="busy")
        return httpx.Response(200, json={"fee_due": 4500})
    if request.url.path == "/slow":
        raise httpx.ReadTimeout("upstream too slow", request=request)
    return httpx.Response(200, json={"ok": True})


TIMEOUT = httpx.Timeout(connect=1.0, read=3.0, write=3.0, pool=1.0)
RETRY_STATUS = {502, 503, 504}


async def get_with_retry(client: httpx.AsyncClient, url: str, attempts: int = 3) -> httpx.Response:
    rng = random.Random(7)                                    # fixed seed so the demo is repeatable
    for attempt in range(1, attempts + 1):
        try:
            r = await client.get(url)
            if r.status_code not in RETRY_STATUS:
                return r
        except (httpx.ConnectError, httpx.ReadTimeout):
            if attempt == attempts:
                raise
        if attempt == attempts:
            return r
        await asyncio.sleep(0.01 * 2 ** attempt + rng.random() * 0.005)   # backoff with jitter


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.http = httpx.AsyncClient(base_url="http://fees.internal", timeout=TIMEOUT,
                                       limits=httpx.Limits(max_connections=50, max_keepalive_connections=10),
                                       transport=httpx.MockTransport(fake_upstream))
    yield
    await app.state.http.aclose()


app = FastAPI(lifespan=lifespan)


@app.get("/fees/{path}")
async def fees(path: str, request: Request):
    try:
        r = await get_with_retry(request.app.state.http, f"/{path}")
    except httpx.TimeoutException:
        raise HTTPException(status_code=504, detail="Fee service timed out")
    if r.status_code >= 500:
        raise HTTPException(status_code=502, detail="Fee service unavailable")
    return r.json()


with TestClient(app) as c:
    print(c.get("/fees/flaky").json(), "after", calls["n"], "upstream calls")
    print(c.get("/fees/slow").status_code, c.get("/fees/slow").json())

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. httpx.MockTransport plays the upstream service, so no network is used. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'fee_due': 4500} after 3 upstream calls 504 {'detail': 'Fee service timed out'}

Key points

  • One shared AsyncClient created in lifespan
  • Explicit connect/read/write/pool timeouts
  • Retry only safe calls, with backoff, jitter and a cap
  • Limits and semaphores bound concurrency
  • Map upstream failures to 502/503/504; test with MockTransport

Common mistakes

  • Creating a new AsyncClient for every request
  • Leaving out timeouts so one slow upstream exhausts the service
  • Retrying non-idempotent POSTs, causing duplicates
  • Retrying at every layer and creating a retry storm
  • Passing upstream error bodies straight to clients

Follow-ups

  • How does a circuit breaker work and where would you place it?
  • How would you propagate a deadline across several service calls?
  • What does httpx's pool timeout protect against?

Tips

  • Name the four timeout kinds
  • State which calls are safe to retry
  • Describe failure mapping and testing with MockTransport