redline
MediumPerformanceawait-in-loop

Await inside a loop (N+1)

Await inside a loop (N+1). await db.get runs once per loop item, one after another. That's an N+1: batch it into one query or call.

This is how the comment reads inline, under the flagged line.

Why it matters

One round trip per item makes the loop as slow as the list is long. With a database call inside, it's the classic N+1 query.

What to do

Fetch everything in one batched call (WHERE id IN (...)), or run independent calls together with a concurrency cap.

Examples

Flagged
for (const id of ids) {
  users.push(await db.user.find(id));
}
Better
const users = await db.user.findMany({ where: { id: { in: ids } } });

What it catches

It reads the shape of the code: functions, blocks, loops and calls. Languages: TypeScript and JavaScript, Python. Scope: All files. These cases are the rule's own tests: the first set must be flagged and the second must not.

Flagged

async function f(ids) {
  for (const id of ids) {
    await db.get(id);
  }
}
src/app.py
async def f(ids):
    for i in ids:
        await db.get(i)

Left alone

async function f(ids) {
  await db.getMany(ids);
}
async function f(s) {
  for await (const c of s) {
    use(c);
  }
}
async function f() {
  for (let attempt = 0; attempt < 3; attempt++) {
    await fetchIt();
  }
}

Research

A query, fetch or await per item in a loop. One round trip per item makes the loop as slow as the list is long.

Turn it off or change it

In a config file for the CLI, or in the API's rules field:

{
  "rules": {
    "disable": [
      "await-in-loop"
    ],
    "severity": {
      "await-in-loop": "low"
    }
  }
}

Read the source or report a false positive.