HTTP client lifetime (ARCH2083)
Key python.performance.http-client-lifetime · Severity error · Category performance
Creating a new HTTP client/session on every call discards the connection pool and exhausts sockets. Reuse a single shared client.
Incorrect
Section titled “Incorrect”import httpx
def fetch_user(user_id): client = httpx.Client() return client.get(f"/users/{user_id}").json()Correct
Section titled “Correct”import httpx
_client = httpx.Client()
def fetch_user(user_id): return _client.get(f"/users/{user_id}").json()Create the HTTP client once and reuse it as a shared singleton.