Skip to main content
Back to all articles
AI Engineering 5 min readUpdated August 31, 2026

Parallel Tool Calls Need Concurrency Limits and Failure Semantics

Running independent agent tools concurrently can cut latency, but production code needs dependency detection, bounded concurrency, cancellation, deterministic result ordering, and explicit partial-failure behavior.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-agents#parallelism#bounded-concurrency#backpressure#asyncio#typescript#python#distributed-systems
On this page

The easiest way to make a tool-using agent faster is often not a faster model.

It is to stop waiting for independent I/O one request at a time.

If an agent needs a customer profile, recent orders, subscription state, and open support tickets, those reads may have no dependency on each other. Executing them serially turns four 300 ms calls into something close to 1.2 seconds before the model can continue.

Promise.all() looks like the obvious fix.

It is also where a second class of problems begins.

What if one dependency fails? What if the model proposes twenty independent searches? What if the user cancels halfway through? What if results finish in a different order every run and change the way context is assembled? What if five agent requests each fan out into twenty calls against the same third-party API?

Parallelism is useful. Unbounded fan-out is an outage pattern.

The example here is a customer-support agent that gathers information from several backend services before deciding how to answer a ticket.

Build an execution plan before launching calls

I do not want the executor to infer independence from timing. The planning layer should make dependencies explicit.

TypeScript
type PlannedCall = {  id: string;  tool: string;  args: unknown;  dependsOn: string[];};​const plan: PlannedCall[] = [  { id: "profile", tool: "get_customer", args: { customerId: "c_91" }, dependsOn: [] },  { id: "orders", tool: "list_orders", args: { customerId: "c_91" }, dependsOn: [] },  { id: "subscription", tool: "get_subscription", args: { customerId: "c_91" }, dependsOn: [] },  { id: "tickets", tool: "list_tickets", args: { customerId: "c_91" }, dependsOn: [] },];

A later call might depend on one of those results:

TypeScript
{  id: "shipment",  tool: "get_shipment",  args: { orderIdFrom: "orders.latest.id" },  dependsOn: ["orders"]}

The exact plan representation can vary. The useful property is that concurrency is derived from a dependency graph rather than from “the model emitted several calls, so run them all.”

Parallelize a ready set, not the entire plan

At each step, find calls whose dependencies have completed.

TypeScript
function readyCalls(  plan: PlannedCall[],  completed: Set<string>,  started: Set<string>,): PlannedCall[] {  return plan.filter(    (call) =>      !started.has(call.id) &&      call.dependsOn.every((dependency) => completed.has(dependency)),  );}

This is essentially a small DAG scheduler. For simple agents you may never need a general graph implementation; a few explicitly grouped calls can be easier to maintain.

The important part is not to parallelize calls that have a real data dependency just because concurrency looks attractive.

Bound concurrency even for independent calls

A semaphore is enough for many services.

TypeScript
import pLimit from "p-limit";​type ToolExecutor = (  call: PlannedCall,  signal: AbortSignal,) => Promise<unknown>;​async function executeBatch(  calls: PlannedCall[],  executor: ToolExecutor,  signal: AbortSignal,  concurrency = 4,): Promise<SettledToolResult[]> {  const limit = pLimit(concurrency);​  return Promise.all(    calls.map((call, index) =>      limit(async () => {        try {          const value = await executor(call, signal);          return {            index,            callId: call.id,            ok: true as const,            value,          };        } catch (error) {          return {            index,            callId: call.id,            ok: false as const,            error: normalizeToolError(error),          };        }      }),    ),  );}

The concurrency value should be a configuration backed by downstream capacity, not a number chosen because it looked reasonable in a tutorial.

I often need limits at more than one level:

  • per agent run;
  • per tenant;
  • per dependency/provider;
  • globally for the worker pool.

A concurrency limit of four inside each run does not protect an API when 500 runs start at once.

Define partial-failure behavior deliberately

Promise.all() rejects when one child rejects. That behavior is sometimes correct and sometimes terrible.

If an agent needs three independent market prices to compute an exact arbitrage, one missing price may make the whole operation invalid.

If a support agent gathers profile, orders, and tickets, it may still produce a useful answer when the ticket service is temporarily unavailable.

I make the result type explicit:

TypeScript
type SettledToolResult =  | {      index: number;      callId: string;      ok: true;      value: unknown;    }  | {      index: number;      callId: string;      ok: false;      error: {        kind: string;        message: string;        retryable: boolean;      };    };

The planner then gets a structured observation such as:

JSON
{  "profile": { "ok": true, "value": { "tier": "pro" } },  "orders": { "ok": true, "value": { "count": 2 } },  "tickets": { "ok": false, "error": { "kind": "timeout", "retryable": true } }}

That is much more useful than cancelling every completed call because one sibling timed out.

Preserve deterministic presentation order

Concurrent calls finish nondeterministically. The prompt does not have to be nondeterministic too.

In the batch executor above, every result carries the original index. I sort before rendering:

TypeScript
function orderResults(results: SettledToolResult[]): SettledToolResult[] {  return [...results].sort((a, b) => a.index - b.index);}

Why bother?

Because changing observation order can change model behavior, complicate cacheability, and make replay harder to compare. If call completion order has no semantic meaning, I do not let network timing decide prompt order.

Cancellation should fan out with the work

When the user cancels a run, every in-flight child should see the same cancellation signal.

TypeScript
const controller = new AbortController();​const execution = executeBatch(  ready,  executeTool,  controller.signal,  4,);​// From request disconnect, user action, or parent deadline:controller.abort();​await execution;

The tool adapters must actually propagate that signal to fetch calls, database operations where supported, subprocesses, or child workflows.

Cancelling the parent promise while leaving twenty HTTP calls running is not cancellation. It is only abandoning their results.

Python with asyncio and a semaphore

Python
import asynciofrom dataclasses import dataclassfrom typing import Awaitable, Callable​@dataclass(frozen=True)class PlannedCall:    id: str    tool: str    args: dict[str, object]​@dataclass(frozen=True)class ToolResult:    call_id: str    index: int    ok: bool    value: object | None = None    error: str | None = None​async def execute_batch(    calls: list[PlannedCall],    executor: Callable[[PlannedCall], Awaitable[object]],    concurrency: int = 4,) -> list[ToolResult]:    semaphore = asyncio.Semaphore(concurrency)​    async def run(index: int, call: PlannedCall) -> ToolResult:        async with semaphore:            try:                value = await executor(call)                return ToolResult(call.id, index, True, value=value)            except asyncio.CancelledError:                raise            except Exception as exc:                return ToolResult(call.id, index, False, error=str(exc))​    results = await asyncio.gather(        *(run(index, call) for index, call in enumerate(calls))    )    return sorted(results, key=lambda item: item.index)

The explicit CancelledError branch matters. Cancellation should not be swallowed and converted into an ordinary tool failure.

For Python 3.11+ workflows, asyncio.TaskGroup is also useful when you want structured concurrency and fail-together semantics. The right primitive depends on whether sibling failures should cancel each other.

Concurrency limits should reflect downstream quotas

Suppose the CRM permits ten requests per second and your worker permits twenty concurrent calls. A bursty agent can still hit rate limits even when concurrency is technically bounded.

Concurrency and rate are different controls.

I often combine:

  • semaphore: maximum in-flight requests;
  • token bucket or leaky bucket: request rate;
  • retry policy: what happens after 429/5xx;
  • circuit breaker: stop hammering a dependency that is clearly unhealthy.

Those controls belong in the connector/platform layer so every agent run shares the same understanding of downstream capacity.

Avoid parallel writes by default

Independent reads are the easy case.

Parallel writes can create ordering problems, conflicting side effects, and more complicated compensation.

If an agent wants to:

  1. update a CRM record;
  2. send a customer email;
  3. create an invoice note;

those operations may look independent, but the business workflow may require the CRM update to succeed before communication is sent.

I only parallelize side effects when their independence is explicit and their idempotency/compensation behavior is understood.

“Can run at the same time” is not only a data-dependency question. It is a business consistency question.

Put a fan-out budget on model-proposed batches

Even bounded concurrency can perform too much total work.

A model could propose 1,000 searches that execute four at a time for an hour.

I add run-level budgets:

TypeScript
type ExecutionBudget = {  maxToolCalls: number;  maxParallelCalls: number;  maxElapsedMs: number;};​function validateBatch(  calls: PlannedCall[],  usedCalls: number,  budget: ExecutionBudget,): void {  if (usedCalls + calls.length > budget.maxToolCalls) {    throw new Error("Tool-call budget exceeded");  }​  if (calls.length > budget.maxParallelCalls * 10) {    throw new Error("Proposed batch is unreasonably large");  }}

The second rule is only an example. Some workloads legitimately process large collections through queues or code execution. In that case I would move bulk work out of the interactive agent loop rather than make the LLM schedule hundreds of calls itself.

Trace child calls under one parent span

Parallel execution is much easier to understand in traces than in interleaved logs.

I want a parent span for the batch and a child span for each tool call, including:

  • call ID/tool name;
  • queue wait caused by concurrency limits;
  • execution duration;
  • result status;
  • retry count;
  • cancellation;
  • downstream rate-limit response.

That makes a useful latency question answerable: did the agent spend 1.8 seconds because one slow child held up the whole batch, or because calls were queued behind our own semaphore?

When serial execution is the better choice

Parallelism is not automatically an optimization.

Keep calls serial when:

  • the next arguments depend on the previous result;
  • ordering is part of the business contract;
  • a downstream service is sensitive to burst load;
  • the calls are extremely fast and scheduling complexity buys little;
  • a failed early call should prevent later work.

The objective is end-to-end reliability and latency, not maximum concurrency.

Once agents can fan out work, they start behaving like distributed systems. The familiar rules come back immediately: dependency graphs, bounded concurrency, rate limits, cancellation propagation, deterministic aggregation, and clear semantics for partial failure.

Promise.all() is a useful primitive. It is not an execution policy.

KEEP READING

Related engineering notes