{"slug": "disabling-parallel-tool-calls-does-not-serialize-updates-across-agent-runs", "title": "Disabling parallel tool calls does not serialize updates across agent runs", "summary": "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.", "body_md": "*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](https://blog.worksi.ai/parallel-tool-calls-shared-resource-race).*\n\nSetting `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.\n\nThe 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.\n\nOpenAI's [function calling guide](https://developers.openai.com/api/docs/guides/function-calling) 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.\n\nThat is a property of one response from the model. It is not a lock. It does not know about:\n\nTwo 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.\n\nThe AWS guide on [concurrent updates in DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BestPractices_ImplementingVersionControl.html) 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.\"\n\nAgents 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.\n\nDo 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.\n\nThe setup, as a design test for staging only, with a fictional record:\n\n`sku-test-001`, quantity 10, version 1, in an in-memory fake store.` call-a1`).` call-b1`).\nThe interleaving the test forces:\n\n```\nrun-A: read v1 (qty 10) ──┐\n                          ├── barrier: nobody writes until both have read\nrun-B: read v1 (qty 10) ──┘\nrun-A: write qty 7   (derived from v1)\nrun-B: write qty 6   (derived from v1)\n```\n\nThe 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.\n\n``` python\nimport threading\n\nclass Conflict(Exception):\n    pass\n\nclass FakeStore:\n    \"\"\"Staging-only, in-memory. Not a database. No real records.\"\"\"\n    def __init__(self, rows=None):\n        self.rows = rows or {\"sku-test-001\": {\"qty\": 10, \"version\": 1}}\n        self.log = []                  # authoritative write history\n        self._mu = threading.Lock()    # makes each single write atomic\n\n    def read(self, rid):\n        with self._mu:\n            return dict(self.rows[rid])\n\n    def blind_write(self, rid, qty, actor):\n        with self._mu:\n            row = self.rows[rid]\n            row[\"qty\"] = qty\n            row[\"version\"] += 1\n            self.log.append((actor, \"committed\", qty, row[\"version\"]))\n\n    def conditional_write(self, rid, qty, expected_version, actor):\n        with self._mu:\n            row = self.rows[rid]\n            if row[\"version\"] != expected_version:\n                self.log.append((actor, \"rejected\", qty, row[\"version\"]))\n                raise Conflict(f\"expected v{expected_version}, found v{row['version']}\")\n            row[\"qty\"] = qty\n            row[\"version\"] += 1\n            self.log.append((actor, \"committed\", qty, row[\"version\"]))\n```\n\nEach 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.\n\n``` python\ndef worker(store, run_id, call_id, rid, delta, mode, barrier, go, done, results, errors):\n    try:\n        row = store.read(rid)\n        barrier.wait()                       # both runs have read v1 (times out after 5 s)\n        if not go[run_id].wait(timeout=5):   # the test chooses who writes first\n            raise TimeoutError(f\"write gate timed out: {run_id}\")\n        new_qty = row[\"qty\"] - delta\n        try:\n            if mode == \"blind\":\n                store.blind_write(rid, new_qty, run_id)\n            else:\n                store.conditional_write(rid, new_qty, row[\"version\"], run_id)\n            condition = \"committed\"\n        except Conflict:\n            condition = \"conflict\"\n        results.append({\"run_id\": run_id, \"tool_call_id\": call_id, \"resource_id\": rid,\n                        \"read_version\": row[\"version\"], \"attempted_qty\": new_qty,\n                        \"condition\": condition})\n    except Exception as exc:                 # a fixture failure, not a test outcome\n        errors.append((run_id, repr(exc)))\n    finally:\n        done[run_id].set()\n\ndef scenario(mode):\n    store, rid = FakeStore(), \"sku-test-001\"\n    barrier = threading.Barrier(2, timeout=5)\n    go = {\"run-A\": threading.Event(), \"run-B\": threading.Event()}\n    done = {\"run-A\": threading.Event(), \"run-B\": threading.Event()}\n    results, errors = [], []\n    threads = [\n        threading.Thread(target=worker, args=(store, \"run-A\", \"call-a1\", rid, 3, mode,\n                                              barrier, go, done, results, errors)),\n        threading.Thread(target=worker, args=(store, \"run-B\", \"call-b1\", rid, 4, mode,\n                                              barrier, go, done, results, errors)),\n    ]\n    for t in threads:\n        t.start()\n    go[\"run-A\"].set(); assert done[\"run-A\"].wait(timeout=5), \"run-A did not finish\"\n    go[\"run-B\"].set(); assert done[\"run-B\"].wait(timeout=5), \"run-B did not finish\"\n    for t in threads:\n        t.join(timeout=5)\n    assert not errors, f\"fixture failed: {errors}\"\n    # The fixture must have forced the scenario: both read v1, A wrote before B.\n    assert all(r[\"read_version\"] == 1 for r in results), \"a run did not read v1\"\n    assert [entry[0] for entry in store.log] == [\"run-A\", \"run-B\"], \"unexpected write order\"\n    final = store.read(rid)\n    by_design = {\"blind\": {\"qty\": 6, \"version\": 3},\n                 \"conditional\": {\"qty\": 7, \"version\": 2}}[mode]\n    assert final == by_design, f\"unexpected final state: {final}\"\n    expected_qty = 10 - 3 - 4      # the correct answer, computed without asking the store\n    return expected_qty, final, results, store.log\n```\n\nThe 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):\n\n`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\")`\nIn 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.\n\nThese 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.\n\n| Scenario | Setup | Expected by design | \n|---|---|---|\n| Serial baseline | A reads and writes, then B reads and writes | Quantity 3, version 3, both committed | \n| 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 | \n| Two runs, flag off, blind writes, same resource | Barrier after reads, A then B | Quantity 6, expected 3: lost update | \n| Two runs, different resources | Initialize `sku-test-002` with quantity 10, version 1; B's resource argument is`sku-test-002` | Both commit. `sku-test-001` : quantity 7, version 2.`sku-test-002` : quantity 6, version 2. Confirms the harness causes no interference | \n| Two runs, conditional writes, same resource | Barrier after reads, A then B | One commit, one conflict, quantity 7 | \n| 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 | \n| Conflict with bounded recovery | B re-reads, re-evaluates, retries once | Quantity 3, version 3; or B stops and goes to a person | \n\nFor 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.\n\nThe 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.\n\nA correctly implemented conditional write on the system of record lets exactly one of the stale-version writes commit. DynamoDB's [optimistic locking guide](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BestPractices_OptimisticLocking.html) 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.\n\nA conditional write prevents the lost update only under these assumptions, which you should write down for your own store or API:\n\nThird-party APIs have their own contracts. GitHub's [repository contents API](https://docs.github.com/en/rest/repos/contents) 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.\n\nFor 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.\n\nThe 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.\n\nSo the fresh read must be followed by a fresh decision:\n\n``` python\ndef reserve_with_recovery(store, rid, delta, run_id, max_attempts=2):\n    for attempt in range(1, max_attempts + 1):\n        row = store.read(rid)                    # fresh read every attempt\n        if row[\"qty\"] - delta < 0:               # re-check the rule on new state\n            return {\"status\": \"needs_person\", \"reason\": \"insufficient stock\",\n                    \"read_version\": row[\"version\"]}\n        try:\n            store.conditional_write(rid, row[\"qty\"] - delta, row[\"version\"], run_id)\n            return {\"status\": \"committed\", \"attempt\": attempt}\n        except Conflict:\n            continue\n    return {\"status\": \"needs_person\", \"reason\": \"conflict after retries\"}\n```\n\nThe 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](https://blog.worksi.ai/agent-tool-timeout-retry-idempotency).\n\nIdempotency 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.\n\nAn application lock, a per-resource mutex in a cache or a lock table, is also a valid design; the [AWS concurrent-updates guide](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BestPractices_ImplementingVersionControl.html) lists a lock client with a lease and heartbeat for long-running critical sections. Two costs:\n\nA 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.\n\nFour 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.\n\nA 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](https://blog.worksi.ai/tool-call-succeeded-wrong-outcome). The deciding evidence is the authoritative version and the actor history in the system of record.\n\nIf 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.\n\nRun 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.\n\n*Originally published at [blog.worksi.ai](https://blog.worksi.ai/parallel-tool-calls-shared-resource-race).*", "url": "https://wpnews.pro/news/disabling-parallel-tool-calls-does-not-serialize-updates-across-agent-runs", "canonical_source": "https://dev.to/worksi_25025494650/disabling-parallel-tool-calls-does-not-serialize-updates-across-agent-runs-2bjn", "published_at": "2026-11-16 12:07:22+00:00", "updated_at": "2026-11-16 12:21:26.085302+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "ai-infrastructure"], "entities": ["Worksi", "OpenAI", "Amazon Web Services", "DynamoDB"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/disabling-parallel-tool-calls-does-not-serialize-updates-across-agent-runs", "markdown": "https://wpnews.pro/news/disabling-parallel-tool-calls-does-not-serialize-updates-across-agent-runs.md", "text": "https://wpnews.pro/news/disabling-parallel-tool-calls-does-not-serialize-updates-across-agent-runs.txt", "jsonld": "https://wpnews.pro/news/disabling-parallel-tool-calls-does-not-serialize-updates-across-agent-runs.jsonld"}}