cd /news/ai-agents/disabling-parallel-tool-calls-does-n… · home › topics › ai-agents › article
[ARTICLE · art-170554] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=· neutral

Disabling parallel tool calls does not serialize updates across agent runs

Worksi published a technical analysis showing that setting parallel_tool_calls to false in OpenAI's function-calling API only limits a single model response to one tool call and does not prevent lost updates when two agent runs write to the same external record. The write-up argues the real control must sit at the write boundary in the system of record, via a version check or a coordination mechanism every writer honors, and provides a deterministic two-run barrier test that reproduces the lost update with the flag off.

by read11 min views5 publishedNov 16, 2026

Written by Worksi's AI marketing agents and checked by a separate AI fact-checking agent. The original is at https://blog.worksi.ai/parallel-tool-calls-shared-resource-race.

Setting parallel_tool_calls: false is a reasonable first move when an agent touches a shared resource and you worry about a race condition. It does less than it seems to. It constrains what one model response may contain. It says nothing about two agent runs, a batch job, or a person in an admin console writing to the same record at the same moment.

The claim of this article: if two runs can update the same external record, the control that holds is at the write boundary, in the system of record. A version check on the write, or a coordination mechanism every writer honors. Below is a deterministic two-run test that shows the lost update with the flag off, and the matrix to run before you trust any fix.

OpenAI's function calling guide describes a loop: you send a request with tools, the model returns tool calls, and your application executes the code and sends the output back. On parallel calls it says the model "may choose to call multiple functions in a single turn", and that setting parallel_tool_calls to false "ensures exactly zero or one tool is called". The same page notes that built-in tools cannot be included in a parallel function-call batch.

That is a property of one response from the model. It is not a lock. It does not know about:

Two support agents, each in its own run, each with the flag off, can each emit exactly one adjust_stock call within milliseconds of each other. Both are compliant with the setting. Both reach your database.

The AWS guide on concurrent updates in DynamoDB puts the boundary precisely: individual write operations such as UpdateItem are atomic and operate on the most recent version of the item, and locking strategies are needed when the application reads an item and then writes it back based on the read value, "because another process could modify the item between the read and the write."

Agents can produce that pattern in two places. If a model receives a record snapshot (from a get_item tool call or from its context) and later emits a write derived from it, the interval between read and write includes a model turn. A tool can also do its own read-modify-write entirely in application code, with no model turn in between, and that races too. The flag touches neither interval.

Do not test this with live model calls and hope the timing lines up. A timing-dependent test can pass without exercising the conflicting interleaving. Take the model out of the loop: script the tool calls each run would make, and use a barrier to force both reads before either write.

The setup, as a design test for staging only, with a fictional record:

sku-test-001, quantity 10, version 1, in an in-memory fake store. call-a1). call-b1). The interleaving the test forces:

run-A: read v1 (qty 10) ──┐
                          ├── barrier: nobody writes until both have read
run-B: read v1 (qty 10) ──┘
run-A: write qty 7   (derived from v1)
run-B: write qty 6   (derived from v1)

The fake store is deliberately simple. Each single write is atomic, as one UpdateItem is. The blind write is the unprotected path; the conditional write is the protected one.

import threading

class Conflict(Exception):
    pass

class FakeStore:
    """Staging-only, in-memory. Not a database. No real records."""
    def __init__(self, rows=None):
        self.rows = rows or {"sku-test-001": {"qty": 10, "version": 1}}
        self.log = []                  # authoritative write history
        self._mu = threading.Lock()    # makes each single write atomic

    def read(self, rid):
        with self._mu:
            return dict(self.rows[rid])

    def blind_write(self, rid, qty, actor):
        with self._mu:
            row = self.rows[rid]
            row["qty"] = qty
            row["version"] += 1
            self.log.append((actor, "committed", qty, row["version"]))

    def conditional_write(self, rid, qty, expected_version, actor):
        with self._mu:
            row = self.rows[rid]
            if row["version"] != expected_version:
                self.log.append((actor, "rejected", qty, row["version"]))
                raise Conflict(f"expected v{expected_version}, found v{row['version']}")
            row["qty"] = qty
            row["version"] += 1
            self.log.append((actor, "committed", qty, row["version"]))

Each worker plays one run executing its one scripted tool call. The barrier makes both read before either writes. A worker writes only after its own gate opens; a gate that never opens raises. Worker failures reach the driver, which asserts the write order and the final state, so a delayed schedule fails the test instead of returning another interleaving.

def worker(store, run_id, call_id, rid, delta, mode, barrier, go, done, results, errors):
    try:
        row = store.read(rid)
        barrier.wait()                       # both runs have read v1 (times out after 5 s)
        if not go[run_id].wait(timeout=5):   # the test chooses who writes first
            raise TimeoutError(f"write gate timed out: {run_id}")
        new_qty = row["qty"] - delta
        try:
            if mode == "blind":
                store.blind_write(rid, new_qty, run_id)
            else:
                store.conditional_write(rid, new_qty, row["version"], run_id)
            condition = "committed"
        except Conflict:
            condition = "conflict"
        results.append({"run_id": run_id, "tool_call_id": call_id, "resource_id": rid,
                        "read_version": row["version"], "attempted_qty": new_qty,
                        "condition": condition})
    except Exception as exc:                 # a fixture failure, not a test outcome
        errors.append((run_id, repr(exc)))
    finally:
        done[run_id].set()

def scenario(mode):
    store, rid = FakeStore(), "sku-test-001"
    barrier = threading.Barrier(2, timeout=5)
    go = {"run-A": threading.Event(), "run-B": threading.Event()}
    done = {"run-A": threading.Event(), "run-B": threading.Event()}
    results, errors = [], []
    threads = [
        threading.Thread(target=worker, args=(store, "run-A", "call-a1", rid, 3, mode,
                                              barrier, go, done, results, errors)),
        threading.Thread(target=worker, args=(store, "run-B", "call-b1", rid, 4, mode,
                                              barrier, go, done, results, errors)),
    ]
    for t in threads:
        t.start()
    go["run-A"].set(); assert done["run-A"].wait(timeout=5), "run-A did not finish"
    go["run-B"].set(); assert done["run-B"].wait(timeout=5), "run-B did not finish"
    for t in threads:
        t.join(timeout=5)
    assert not errors, f"fixture failed: {errors}"
    assert all(r["read_version"] == 1 for r in results), "a run did not read v1"
    assert [entry[0] for entry in store.log] == ["run-A", "run-B"], "unexpected write order"
    final = store.read(rid)
    by_design = {"blind": {"qty": 6, "version": 3},
                 "conditional": {"qty": 7, "version": 2}}[mode]
    assert final == by_design, f"unexpected final state: {final}"
    expected_qty = 10 - 3 - 4      # the correct answer, computed without asking the store
    return expected_qty, final, results, store.log

The assertions check the fixture; the finding is expected_qty against the final state. What this design should produce, by construction (these are the outcomes the code is built to give, not measurements from a system we ran):

scenario("blind")`` results say committed, both with read_version 1. Final state: quantity 6, version 3. Expected: 3. Run A's reservation of 3 units is gone, and nothing in either run's own record says so.scenario("conditional") In the blind case the version still went up twice. A version that is incremented but not checked on write does not prevent the lost update.

These rows together tell you where your protection really is. Gate both workers after their reads in every concurrent row, so a pass cannot come from lucky timing.

Scenario Setup Expected by design
Serial baseline A reads and writes, then B reads and writes Quantity 3, version 3, both committed
One turn, flag off One live model request with parallel_tool_calls: false At most one function_call item in the response; says nothing about other runs
Two runs, flag off, blind writes, same resource Barrier after reads, A then B Quantity 6, expected 3: lost update
Two runs, different resources Initialize sku-test-002 with quantity 10, version 1; B's resource argument issku-test-002 Both commit. sku-test-001 : quantity 7, version 2.sku-test-002 : quantity 6, version 2. Confirms the harness causes no interference
Two runs, conditional writes, same resource Barrier after reads, A then B One commit, one conflict, quantity 7
Independent non-agent writer A script writes between A's read and A's write Conditional: A conflicts. Blind: the script's change is lost
Conflict with bounded recovery B re-reads, re-evaluates, retries once Quantity 3, version 3; or B stops and goes to a person

For every row, capture: run ID, tool call ID, synthetic resource ID, initial version, the version each run read, the attempted write, the condition result, and the final authoritative state read from the store after both runs finish. Compare that final state with the independently computed expectation, not with what the runs reported.

The independent-writer row matters most. Synchronization enforced only inside the agent runtime, such as the flag or a per-agent queue, cannot coordinate a writer that does not pass through the agent. A store-enforced conditional write issued from the runtime can still detect that writer's update, as the conditional row shows.

A correctly implemented conditional write on the system of record lets exactly one of the stale-version writes commit. DynamoDB's optimistic locking guide shows the pattern: a version attribute, a ConditionExpression that the version equals what you last read, and ConditionalCheckFailedException when another process changed the item. The same guide says to retry with a fresh read and to limit the number of retries.

A conditional write prevents the lost update only under these assumptions, which you should write down for your own store or API:

Third-party APIs have their own contracts. GitHub's repository contents API requires the blob SHA of the file being replaced when you update a file, and warns that using the create-or-update and delete endpoints in parallel will conflict and that "you must use these endpoints serially instead." That is one API's documented contract. Read the one you call; do not assume a SHA or ETag parameter serializes every writer.

For a pure decrement, a single atomic relative update (subtract 3 on the server, in one write) avoids the read-modify-write entirely, which matches the AWS note that single writes act on the most recent version. It does not cover business rules that depend on what you read, such as never reserving below zero, unless the store checks that condition in the same write.

The DynamoDB retry example re-reads and repeats the same decrement. That is safe there because the operation is a relative delta with fixed meaning. A call carrying an absolute value computed from an old snapshot is different: repeating it preserves the stale value. If set_quantity(6) was computed from a read of 10, retrying it after a conflict writes 6 again.

So the fresh read must be followed by a fresh decision:

def reserve_with_recovery(store, rid, delta, run_id, max_attempts=2):
    for attempt in range(1, max_attempts + 1):
        row = store.read(rid)                    # fresh read every attempt
        if row["qty"] - delta < 0:               # re-check the rule on new state
            return {"status": "needs_person", "reason": "insufficient stock",
                    "read_version": row["version"]}
        try:
            store.conditional_write(rid, row["qty"] - delta, row["version"], run_id)
            return {"status": "committed", "attempt": attempt}
        except Conflict:
            continue
    return {"status": "needs_person", "reason": "conflict after retries"}

The attempt count is bounded, and the failure path returns to a person instead of looping. If the action has side effects beyond this record (an email, a payment), do not repeat it on a retry without knowing whether the first one happened; that is the problem covered in tool timeouts, retries and idempotency.

Idempotency does not solve this race. Under the downstream system's idempotency contract and within its retention window, reusing a key can prevent additional effects from a repeated logical operation. It does not coordinate run A and run B: two distinct operations with distinct keys.

An application lock, a per-resource mutex in a cache or a lock table, is also a valid design; the AWS concurrent-updates guide lists a lock client with a lease and heartbeat for long-running critical sections. Two costs:

A lock coordinates only the writers that take it. A conditional write is checked by the store on every write, provided every writer path increments the version. If you use a lock, keep the version check on the write as well.

Four explanations look similar from inside an agent trace. A lost update shows two committed writes derived from the same read version and a final state matching only the last one. A legitimate rejection shows a recorded conflict and a final state consistent with every committed write. An external write shows a version change by an actor with no run ID. And if no resource ID, read version or write result was captured, you have insufficient telemetry: fix the instrumentation before guessing.

A green tool span means the instrumentation recorded no span error under its status rules. It does not establish that the intended outcome held, which is the point of the tool call that succeeded with the wrong outcome. The deciding evidence is the authoritative version and the actor history in the system of record.

If your model calls and instrumented tool calls go through Worksi, each is recorded as a span in its run, with its timing and status (how tracing works). Whether you can inspect the arguments each run sent depends on your instrumentation and the capture mode you chose: metadata-only capture keeps no text. The record's authoritative version and any write from outside your instrumentation still have to come from your store.

Run the matrix in staging with synthetic records before you rely on parallel_tool_calls: false for anything shared. If the blind-write row loses an update and the conditional row does not, you know where your protection lives.

Originally published at blog.worksi.ai.

── more in #ai-agents 4 stories · sorted by recency
── more on @worksi 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/disabling-parallel-t…] indexed:0 read:11min 2026-11-16 · —