Skip to content
mentoor

Topic 3 of 5 · 5 min read

Chatty network calls and missing batching

Goal: Spot sequential or per-item I/O in AI code and restructure it with batching, bounded concurrency or pagination.

Chatty I/O means making many small network or disk calls where fewer, larger or parallel ones would do; look for an await, request or file read inside a loop. Time spent waiting on the network usually dwarfs time spent computing, so the number of round trips is the number that matters.

Check yourself · 1 of 3

An AI-written script calls an API once per item in a loop of 500 items, awaiting each call. What is the main cost?

Choose one answer

Why it matters

A call to an API takes tens or hundreds of milliseconds. Fetch 300 items one by one and wait 300 times: at 100 ms each that is 30 seconds of mostly idle waiting. AI assistants write this because a loop with await fetch(...) is easy to read and correct. They also tend to skip things they were not asked for: pagination, caching, timeouts and rate limits.

What to look for

  1. Sequential awaits in a loop. Independent calls run one after another.
  2. Per-item calls where a bulk endpoint exists. Many APIs accept a list of ids or have a batch route.
  3. Unbounded parallelism. Promise.all over 10,000 items opens 10,000 requests, trips rate limits and can exhaust memory or sockets.
  4. Missing pagination. The code reads the first page and treats it as everything, or asks for all rows at once.
  5. No caching of stable data. The same lookup repeats on every request.
  6. No timeout or retry limit. One slow call stalls the whole request.

How to fix it

  • Use the bulk endpoint when there is one.
  • Run independent calls concurrently with a limit, such as 5 to 20 at a time, with a small pool or a library like p-limit or asyncio.Semaphore.
  • Loop over pages until the API says there are no more, with a hard cap.
  • Cache stable results, with an expiry and a size bound.

Before and after

// Weak: 300 requests, one after another
const users = [];
for (const id of ids) {
  users.push(await api.getUser(id));
}

// Better: a bulk call, split into chunks of 100
const users = [];
for (let i = 0; i < ids.length; i += 100) {
  users.push(...(await api.getUsers(ids.slice(i, i + 100))));
}

What goes wrong

  • Parallel with no limit. Faster until the provider returns 429 errors, then slower than the loop.
  • Batching that breaks error handling. One bad id can fail a whole batch; decide what happens.
  • Caching data that changes. A stale price or permission is a bug, not a speedup.

Examples

Unbounded Promise.all

An agent speeds up an import by replacing a loop with await Promise.all(rows.map(r => api.upsert(r))). With 8,000 rows the provider starts returning 429 errors and half the rows fail. A limit of 10 concurrent calls, with a retry on 429, finishes cleanly.

The silent first page

resp = requests.get(f"{BASE}/invoices?status=open")
invoices = resp.json()["data"]

The API returns 50 items per page and gives a next link. The report built from this code is wrong for any customer with more than 50 open invoices, and nothing fails. Loop on next, and stop at a sane maximum.

Key points

  • Count round trips: a request, await or file read inside a loop multiplies latency by the item count.
  • Prefer a bulk endpoint, and chunk the ids to respect its size limit.
  • Run independent calls concurrently but with a fixed limit, never an unbounded Promise.all over a large list.
  • Check that list endpoints are paginated all the way through, with a hard cap on pages.
  • Cache stable data with an expiry and size limit, and add timeouts to every external call.

Common mistakes

  • Accepting an await inside a loop because it is the readable version.
  • Replacing a loop with unbounded parallel calls and calling it optimised.
  • Assuming the first page of results is the full result.
  • Caching responses with no expiry, so stale data lives until a restart.

Check yourself · 2 of 3

A fix replaces a loop of 10,000 API calls with Promise.all over all of them. What is the likely problem?

Choose one answer

Check yourself · 3 of 3

Code reads page 1 of a paginated API and treats it as all results. What should the reviewer ask for?

Choose one answer

Practice items, not counted towards your mastery.

Start here