Skip to content

loop-unpooled-client (EFF102)

Family: Execution Effects (EFF) · Heuristic · Off by default · Severity warning (slower code) · No automatic fix

Allocating an unpooled HTTP/DB/RPC client or sessionless request inside a loop.

Heuristic

This rule is heuristic: a premise of its claim can be open ("What a report states" lists them), so a report can be wrong about the code. It runs when select or extend-select names its code or name, and with lint.heuristic = true (--heuristic) also by default and for its prefixes and ALL. Of 50 sampled reports (round 3, 2026-11-21), 54% were right about the code. See Rule Precision.

What it does

Checks loops that allocate a network or database client on every iteration: module-level request helpers that open a new connection per call (requests.get, httpx.get), client constructors, sync and async (requests.Session(), httpx.AsyncClient(), aiohttp.ClientSession(), boto3.client(...)), connection factories (sqlite3.connect, redis.Redis, create_async_engine, ...), and connection pools (psycopg_pool.ConnectionPool), directly or through project functions, including the getter of a property read in the loop (self.client.get(url) where the client getter builds a new client).

A function a builtin calls once per item runs in a loop too: the function handed to map, filter, itertools.starmap, itertools.filterfalse, and functools.reduce, and the key of sorted, list.sort, min, max, and itertools.groupby (list(map(fetch, urls))), whether it is a lambda, a project function, a bound method, or a functools.partial of one. The loop is as long as the items, which are sized as a for loop's iterable: map(fetch, ("a", "b")) is not reported, nor is max(a, b, key=fetch), which compares two values. A lambda written in the same function as another lambda is not followed: every lambda of a function has the same name (f.<locals>.<lambda>), and heki keeps one summary per name.

The iterable of a for loop is evaluated once and is not reported; neither are calls in loops whose size the code fixes, when no data-sized loop is around them: displays of at most 16 items (also through a name or a module constant bound to one that nothing in the project grows, a tuple whatever other code does with it short of rebinding it, and through enumerate / zip / reversed / sorted / .items()), range of integer constants with at most 16 steps (range(ATTEMPTS - 1)), what a builtin constructor, a comprehension, or a fixed loop of appends makes of those (list(range(7)), [n.upper() for n in ("a", "b")]), slices with a constant bound (for case in cases[:3]), iterables a length test on every path to the loop caps (if len(cases) > 3: raise ...), a while loop over a counter the code starts, steps, and limits with constants (i = 1 ... while i < 6: ... i += 1, at most 16 times), retry loops, and daemon polling loops.

A retry loop repeats one attempt: its body leaves the loop on success or sleeps in an exception handler, and it runs over a small constant range or a target named like attempt / retry (also one name of a tuple target: for attempt, proxy in enumerate(proxies)). A loop that waits on every path back to its test is paced by time, as polls and retries are: a while loop, or a for loop whose body never reads its target (for _ in range(30):), in which every iteration sleeps or waits with a timeout (time.sleep(5), stop.wait(1), in a coroutine await asyncio.sleep(5); sleep(0) only yields, and a sleep an exception can skip or a coroutine does not await does not count). A daemon polling loop runs until a flag or an event says to stop (while self._running:, while not self._stopped:, while not stop_event.is_set():), or is a while True: loop that waits on every iteration. A for loop reading its target steps through items, also when it sleeps per item.

A client that is only created while an attribute is unset, which the code then sets (lazy initialization: if not self._sock: self._sock = connect(), if self._sock: return before connecting, if not hasattr(self, "_sock"):, a None test of getattr(self, "_sock", None), or the except AttributeError: clause of a try reading self._sock; the store may be setattr or object.__setattr__), is created once per object, not on every iteration: the call is not reported unless a data-sized loop around it constructs the object in each iteration (Connection().send(cmd)); conn.send(cmd) on a connection made before the loop, taken from a pool, or held by the receiver is not reported. The receiver of a bound method, the arguments a functools.partial holds, and the items a builtin passes are no new objects either: map(self.fetch, urls), where fetch sets self._session once, is not reported. A functools.cached_property getter (also imported through a module that re-exports it, such as kombu.utils.cached_property) runs once per instance in the same way, and a lazy initialization of a module global (global _session) once per process.

A client created only while a local variable the loop carries is unset (if conn is None: conn = connect(), conn = conn or connect()), or only while a first-iteration flag holds (if first: ...; first = False), is created once per run of the loop, and so is one created where every way on leaves the loop (return s.get(url), connect(); break, raise after it). Still reported: a variable or flag set back in the loop (also by an except handler), or set there to a value the branch does not compute (prev = row, which may be None), a global the function also sets back to None (before the test, or after the initialization), a branch that does not always set it, a loop around that starts it unset again in each iteration, and a break out of an inner loop, which runs again in each iteration of the outer one.

A call whose arguments switch off the branch that creates the client is not followed into it: load(name, cache=False) does not reach the urlopen under if cache: in load. This covers constant arguments and the literal defaults of omitted ones (False, None, 0, "", empty displays), tests the caller has already made on the same value (isinstance, is None, truthiness), and wrappers that pass the value on.

What a report states

A report states that every iteration of the loop allocates a new client (or opens a new connection) through the call shown.

Its premises:

  • Resolves: each call on the chain is to the function shown, through the calls heki resolves. Open through a method call: one candidate implementation that leads on is enough.
  • Reaches: each function on the chain reaches the next call. Open: one path is enough, and a branch heki cannot decide counts as taken; only the branches the caller's arguments switch off, and the cases listed above, are left out.
  • On every iteration: the call runs on every iteration of the loop. Open: it counts as running on every iteration unless heki shows that it runs once per object, per process, or per run of the loop (the cases above).
  • Data-sized: the code does not fix the size of the loop at 16 or fewer. Open: a size heki cannot bound counts as data-sized.
  • Allocates: the call builds a client, as the ecosystem catalog describes it.

Not part of the claim: how many items the loop has, and what a client costs.

Why is this bad?

Each new client pays for DNS, TCP, and TLS setup again and throws its connection pool away. In a loop this dominates the run time and exhausts sockets.

Example

import requests


def fetch_all(urls: list[str]) -> list[str]:
    out = []
    for url in urls:
        out.append(requests.get(url).text)  # EFF102: a new connection per iteration
    return out

Use instead:

def fetch_all(urls: list[str]) -> list[str]:
    with requests.Session() as session:
        return [session.get(url).text for url in urls]

A reused client keeps state from one request to the next. A requests.Session persists the cookies that responses set across all requests made from it, and sends the auth and headers set on it with each of them (Session Objects). An httpx.Client also persists cookies across requests, and applies the headers and auth passed to its constructor to every request (Clients). When the loop makes requests for unrelated parties (other sites, other users), keep one client per party: clearing the cookies (client.cookies.clear() in both libraries) leaves the auth and the headers set on the client, so the next party's requests still carry the first party's credentials. A client shared across parties needs all three reset before each party's requests.

Fix safety

No automatic fix.