Skip to content
Sarj Code Standards

no-unscoped-async-client-factory

Inject an HTTPX client instead of hiding a never-closed one inside a returned object.

Why

A factory that wraps a fresh client in its returned object and never closes it leaks one connection pool per call, and callers cannot see the client to close it.

Fix

Open the client in the caller's with or async with scope and inject it, or give the returned object a close or aclose method that closes the client. Keep tenant credentials, cookies and event loops in separate clients; do not replace them with a global client.

Examples

Before — flagged Do not hide a fresh client inside a returned service
app/service.py
import httpx
class Dao:
def __init__(self, client):
self.client = client
class Service:
def __init__(self, dao):
self.dao = dao
def build_service(token):
client = httpx.AsyncClient(headers={"Authorization": token})
return Service(dao=Dao(client))
After — preferred Give the returned object ownership of client closure
app/service.py
import httpx
class Dao:
def __init__(self, client):
self.client = client
class Service:
def __init__(self, dao):
self.dao = dao
async def aclose(self):
await self.dao.client.aclose()
def build_service(token):
client = httpx.AsyncClient(headers={"Authorization": token})
return Service(dao=Dao(client))