Parallelism, Deadlocks and Conflict Resolution

Agents that work at the same time can overwrite, wait forever, loop and disagree. Plan for all four.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Run agents in parallel when their tasks are independent and the merge is well defined. Protect shared records with atomic version checks or single ownership, give every wait a deadline, detect cycles, cap delegation and total spend, and settle contradictions with evidence and stated rules. When rules cannot decide, show the disagreement to a person instead of averaging it away.

What you will learn: when parallelism pays, race conditions and controls, deadlocks and endless delegation, merging results, resolving contradictions and testing concurrent systems.
Prerequisites: Handoffs, Routing, Shared State and Communication and Distributed Systems, Networking and Databases.

Beginner Working at the same time

When parallel agents help

Good candidatePoor candidate
Searching separate sourcesSteps that depend on one another
Reviewing different files for one ruleSeveral agents editing the same file
Independent attempts to be comparedOne account balance or stock count
Slow calls with little shared contextWork needing constant coordination

Anthropic's account of its research system describes parallel subagents as a strength for broad research, while noting that tasks with many dependencies, including most coding work, were a poorer fit. It also reported duplicated work and gaps when task instructions were vague. Independence has to be designed.

Splitnon-overlapping briefs
Agent Aown scope and budget
Agent Bown scope and budget
Agent Cown scope and budget
Mergededuplicate, check, report gaps
The split and the merge decide whether parallel work is useful.

Elapsed time falls toward the slowest branch, while total cost is the sum of all branches. Both matter.

Plan the split

  • Write what each branch covers and what it excludes.
  • Give each a done condition, tools, budget and deadline.
  • Decide which branches are required and which optional.
  • Define the merge before starting.
  • Limit how many run at once to respect rate limits.

Is it worth it?

Estimate before building. Suppose four independent searches take 20, 25, 30 and 45 seconds, and merging takes 10. One after another they need 130 seconds; together they need about 55, the slowest branch plus the merge. The model usage is roughly the same for the searches either way, but a parallel design often adds a coordinator turn, repeated instructions in each branch and a larger merge. These timings are invented to show the method.

AskIf the answer is no
Can each branch finish without hearing from the others?Run in sequence
Does anyone benefit from the shorter wait?Save the complexity
Can providers and tools accept the extra concurrent calls?Limit the width
Can the merge detect gaps and contradictions?Design the merge first
Can unused work be canceled?Budget for waste

For background work that nobody is waiting on, a queue worked at a steady pace is often cheaper and gentler on rate limits than a burst.

Intermediate Shared state and waiting

Race conditions

A race occurs when the result depends on timing. The classic case: two agents read a value, each adds to it and writes it back. This program controls the order of steps so the problem appears every time.

"""Two agents update one shared record. Order of steps is controlled."""

def naive(store, amount):
    seen = store["spent"]            # read
    yield
    store["spent"] = seen + amount   # write over whatever is there now

def checked(store, amount, limit):
    while True:
        version, seen = store["version"], store["spent"]
        yield
        if seen + amount > limit:
            store["log"].append(f"refused {amount}: limit {limit}")
            return
        if store["version"] == version:      # compare and set, one step
            store["spent"] = seen + amount
            store["version"] += 1
            return
        store["log"].append(f"retry {amount}: record changed")

def run(*workers):
    """Advance each worker one step in turn until all finish."""
    pending = list(workers)
    while pending:
        for worker in list(pending):
            if next(worker, "finished") == "finished":
                pending.remove(worker)

shared = {"spent": 0}
run(naive(shared, 60), naive(shared, 70))
print("naive total:", shared["spent"], "(both spent: 130)")

shared = {"spent": 0, "version": 0, "log": []}
run(checked(shared, 60, 100), checked(shared, 70, 100))
print("checked total:", shared["spent"])
print(*shared["log"], sep="\n")

Output:

naive total: 70 (both spent: 130)
checked total: 60
retry 70: record changed
refused 70: limit 100

Both naive agents spent, yet the record shows only 70: one update vanished and a limit based on that record would be wrong. The checked version notices that the record changed, re-reads and then refuses the second spend. The comparison and write happen in one uninterrupted step here because of how the example is scheduled. In a database, use a conditional update or a transaction with suitable isolation; checking and then writing in two separate statements reintroduces the race.

ControlHow it helpsCost
Single writerOnly one component changes the recordCan become a queue
Optimistic version checkDetects change and retriesRetries under contention
Atomic operationStore applies the change safelyLimited to supported operations
Lock or leaseOne holder at a timeWaiting, expiry and stale holders
Append, then combineNo overwritingCombination rules needed
Isolated copiesWork separately, merge laterMerge conflicts

A model may take many seconds to think between reading and writing, which widens the window enormously. Do not hold a database lock across a model call. Read, think, then apply the change conditionally. And remember that a retry should reconsider the decision, because the new data may change the answer.

Leases need care: a holder that paused too long may still believe it owns the task. Have the resource reject stale holders using an increasing token or version where it can.

Deadlocks

A deadlock happens when each party waits for another in a circle. With agents it often looks polite: the writer waits for review, the reviewer waits for research and the researcher waits for the writer to say what is needed.

Infinite delegation

The related problem is activity without progress: agents pass a task back and forth, or keep splitting it. Nothing is blocked, yet nothing finishes and cost grows.

"""Find agents that wait for each other, and delegation that never ends."""
from graphlib import CycleError, TopologicalSorter

def find_cycle(waits_for):
    try:
        list(TopologicalSorter(waits_for).static_order())
    except CycleError as error:
        return error.args[1]
    return None

healthy = {"writer": {"researcher"}, "reviewer": {"writer"}}
stuck = {"writer": {"reviewer"}, "reviewer": {"researcher"},
         "researcher": {"writer"}}
for name, graph in (("healthy", healthy), ("stuck", stuck)):
    cycle = find_cycle(graph)
    print(f"{name}:", f"{len(set(cycle))} agents in a cycle: "
          f"{', '.join(sorted(set(cycle)))}" if cycle else "no cycle")

def delegate(task, agent, choose, budget=6, chain=()):
    """Stop on a repeated (agent, task) pair or an empty budget."""
    if (agent, task) in chain:
        return f"stopped: {agent} was asked '{task}' again"
    if len(chain) >= budget:
        return f"stopped: {budget} delegations used"
    step = choose(agent, task)
    if step is None:
        return f"{agent} completed '{task}', handoffs used: {len(chain)}"
    return delegate(step[1], step[0], choose, budget,
                    chain + ((agent, task),))

good = {("lead", "report"): ("data", "numbers")}
ping_pong = {("lead", "report"): ("data", "report"),
             ("data", "report"): ("lead", "report")}
for rules in (good, ping_pong):
    print(delegate("report", "lead", lambda a, t: rules.get((a, t))))
print(delegate("part-0", "lead",
               lambda a, t: (a, f"part-{int(t[5:]) + 1}")))

Output:

healthy: no cycle
stuck: 3 agents in a cycle: researcher, reviewer, writer
data completed 'numbers', handoffs used: 1
stopped: lead was asked 'report' again
stopped: 6 delegations used

The wait graph reveals a three-agent cycle. Delegation stops when the same agent receives the same task again, and the budget stops a chain that keeps inventing new subtasks. Matching task text exactly is weak, since a reworded request slips past, which is why the budget is needed as a backstop.

PreventionPractice
One direction of dependencyPlan work as a graph without cycles
Deadlines on every waitProceed with gaps, retry or escalate
Depth and step budgetsEnforced by the runtime across all agents
Progress checkStop when state stops changing
Ordered acquisitionTake shared resources in one agreed order
Supervisor overrideCancel a participant and reassign

Partial failure in a fan-out

With several branches, some will be slow or fail. Decide in advance the minimum needed to continue. Cancel work that is no longer useful, and check that cancellation really stops tool actions. State the missing parts in the result. Silently merging four of five answers can present an incomplete picture as complete. The example in Graphs, State Machines, Parallelism and Sagas shows a deadline with required branches.

Expert Disagreement

Merge without losing information

  • Require structured claims with source and date.
  • Deduplicate by identifier, not by similar wording alone.
  • Keep every conflicting value until a rule resolves it.
  • Count independent sources, not agents repeating one source.
  • Check totals and constraints in code.

Order, duplicates and late results

Results may arrive in any order, more than once, or after the task has moved on. Give each branch an identifier and the version of the task it was asked to work on. The merge accepts one result per identifier, ignores repeats and rejects or flags results for an outdated version. If a user changes the question midway, raise the task version so that earlier work cannot slip into the new answer. Sort by a stable key before merging, so that the same inputs produce the same combined output regardless of timing; this also makes failures easier to reproduce.

Avoid relying on clocks on different machines to decide which write came first. Use versions assigned by the store that holds the record, and keep the timestamps for people to read.

When agents contradict each other

First find out why. Contradictions usually come from different inputs, different times, different definitions or a plain error, and each has a different remedy.

CauseCheckRemedy
Different sourcesWhich source has authority?Source ranking
Different datesWhen was each value true?Prefer current, show history
Different definitionsDoes "revenue" mean the same?Shared glossary or semantic layer
Calculation or reading errorRecompute from evidenceVerification step
Judgment differenceIs there a policy?Decision owner
"""Resolve contradictory findings by stated rules, or escalate."""
from datetime import date

RANK = {"system of record": 3, "signed document": 2, "web page": 1}

def resolve(claims):
    values = {c["value"] for c in claims}
    if len(values) == 1:
        return f"agreed: {values.pop()}"
    best = max(RANK[c["source"]] for c in claims)
    top = [c for c in claims if RANK[c["source"]] == best]
    newest = max(c["as_of"] for c in top)
    top = [c for c in top if c["as_of"] == newest]
    values = {c["value"] for c in top}
    if len(values) == 1:
        c = top[0]
        return f"{c['value']} ({c['source']}, {c['as_of']})"
    return f"escalate: {' vs '.join(sorted(values))}"

def claim(value, source, day):
    return {"value": value, "source": source, "as_of": date(2026, 11, day)}

cases = {
    "price": [claim("90", "web page", 20), claim("90", "web page", 21),
              claim("120", "system of record", 2)],
    "address": [claim("Oslo", "system of record", 1),
                claim("Bergen", "system of record", 18)],
    "owner": [claim("Lee", "signed document", 9),
              claim("Roy", "signed document", 9)],
}
for name, claims in cases.items():
    print(f"{name:<8}{resolve(claims)}")

Output:

price   120 (system of record, 2026-11-02)
address Bergen (system of record, 2026-11-18)
owner   escalate: Lee vs Roy

Two newer web pages do not outrank the older system of record. Between two records of equal rank, the newer wins. Two signed documents of the same day disagree, so the case is escalated. These rules are examples: a stale system of record can be wrong, and a later amendment may matter more than a rank. Write rules with the people who own the data, and show the chosen source and date to the user.

Consensus strategies

Agreement among agents is weak evidence when they share a model and context. Use this order where possible: verify by code or authoritative lookup; apply a written precedence rule; gather more evidence; use an independent judge or vote with its limits understood; ask a person. Limit rounds of argument. If you need consensus between replicated services rather than between opinions, that is a distributed systems problem solved by established algorithms, not by prompting. See Topologies, Specialist Teams and Debate for voting arithmetic.

Report disagreement honestly

When rules cannot settle a point, say so in plain words: give each value, its source and date, what was checked and who can decide. Carry that unresolved state forward so later steps do not treat one value as fact. Block actions that depend on it, while letting unrelated work continue. Record the person's decision with its reason; repeated decisions of the same kind are candidates for a new written rule, reviewed by the data owner.

Conflicting actions

Worse than conflicting statements are conflicting actions, such as one agent canceling an order while another expedites it. Funnel changes to a record through one owner or an execution service that checks the current version and business rules. Make agents propose, and let the service accept the first valid change and reject stale ones with the new state. For multi-step changes, define compensation and who may trigger it.

Isolation for files and code

Agents that edit files are a special case, because a change that looks correct alone can break another. Give each agent its own working copy or branch, keep tasks to separate areas where possible, and merge one at a time with the full tests run after each merge. A clean automatic merge only means the edits did not touch the same lines; it does not mean the behavior is compatible. For example, one agent renames a function while another adds a new call using the old name. Version control accepts both, and only a build or test catches it. See Coding Agent Architecture and Code Understanding.

The same idea applies to documents and configuration: propose changes against a stated version, apply them through one path and re-check the combined result.

Test concurrency deliberately

  1. Replace models with scripted agents.
  2. Control ordering with explicit steps or injected delays.
  3. Try the orders that break assumptions.
  4. Duplicate messages and expire leases.
  5. Kill an agent while it holds a claim.
  6. Check invariants after each run, such as totals within limits.

Random stress runs help find surprises, but save each failing order as a repeatable test. Formal Verification and Testing Foundations introduces property checks and model checking for important invariants.

What to watch

  • Version conflicts and retries by record.
  • Waiting time and tasks past their deadline.
  • Delegation depth and repeated pairs.
  • Branches canceled or missing from results.
  • Contradictions by cause and how each was settled.

A rise in conflicts often signals overlapping responsibilities. Fix the split before tuning retries.

Illustrative example: two agents, one calendar

A scheduling agent and a travel agent both book against a shared calendar, and double bookings appear. The team routes all changes through one calendar service that requires the version last read. A rejected agent receives the new calendar and plans again. They add a test that interleaves both agents in the harmful order.

Common mistakes

  • Parallelizing dependent work.
  • Assuming instructions prevent overlap.
  • Checking and writing in separate steps.
  • Holding locks while a model thinks.
  • Waiting without a deadline.
  • Counting repeated claims as confirmation.
  • Hiding disagreement or missing branches.

Checklist

  • Branches have separate scopes, budgets and done conditions.
  • Required and optional branches are defined.
  • Shared changes are atomic or single-writer.
  • Every wait expires.
  • Delegation depth and total spend are capped.
  • Contradictions follow written rules with escalation.
  • Harmful orderings have repeatable tests.

Frequently asked questions

Can prompting prevent race conditions?

No. Timing is controlled by the system, so protection must be in the code and data store.

How many agents should run at once?

As many as rate limits, budget and useful independence allow. Measure time saved against added cost.

Should a third agent break ties?

Only if it has better evidence or an independent method. Otherwise apply a rule or ask a person.

What if a canceled agent finishes anyway?

Reject its writes by version or ownership, and design actions so that late effects are detected.

References and further reading

Next steps