Reliability · Medium · 20 min

Limit concurrent requests

Sending 50 prompts at once to a local model only fills its queue. Process them two at a time and keep the order.

Write mapLimit(items, limit, fn). Call fn(item, index) for every item, with at most limit calls in flight at once, and return an array of results in the same order as items, even when they finish out of order.

You already have fakeGenerate(prompt, ms), which simulates a model call: it takes ms milliseconds and returns the prompt in upper case. It records the peak number of simultaneous calls in window.__peak.

Challenges 0/4

  • Keeps the order even when calls finish out of order
  • Never more than 2 calls at once with limit = 2
  • With fewer items than the limit, runs them all
  • An empty array returns []

async function mapLimit(items, limit, fn) {
  // start at most `limit` workers; each takes the next index until none are left
  return Promise.all(items.map((item, i) => fn(item, i)));
}

mapLimit(['hola', 'que', 'tal', 'modelo'], 2, (p) => fakeGenerate(p))
  .then((r) => console.log(r, 'peak:', window.__peak));

Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.

Console output appears here (console.log).

Why this matters

Batch jobs are where a local model earns its keep: summarising two hundred emails, tagging an archive of invoices, embedding a folder. Firing every request with one Promise.all does not speed them up; the server processes as many as its configuration allows and the rest wait until they time out. A concurrency limit in the client keeps the queue short, keeps the results in order and leaves the machine usable for someone else. How many requests at once are worth it depends on the server: we measured it in Ollama vs vLLM, same model, same box.

Go deeper: the Ollama reference →

This in production, with your data? Let's talk for 15 minutes →