Module 06 · Lesson 6.5
Orchestration, Concurrency and Task Coordination
On this page
- What you will learn
- What orchestration and concurrency mean
- When running specialists together is safe
- Avoid conflicting writes to one case
- Order the results and set timeouts
- Try it: a lock around a shared case record
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Picture two people editing the same paper form at the same moment. One writes a delivery date in the corner. The other crosses out the whole box to fix a typo. When they finish, the form has half of each change, and nobody can say who did what.
Agents that work at the same time can damage a shared case record in the same way. In this lesson you learn when running agents together is safe, how to prevent conflicting writes, how to put results in a fixed order and how to stop waiting for a slow specialist. Most of the lesson needs no coding. One short Python example at the end shows a lock protecting a shared record.
What you will learn
- Decide which specialist tasks may run at the same time.
- Prevent two agents from overwriting each other, using one owner per field, a lock or a single writer.
- Collect results from concurrent agents in a fixed, predictable order.
- Set a timeout for each specialist and decide what happens when it is missed.
Before you start
- The previous lesson, Avoiding Infinite Loops and Unnecessary Agent Handoffs, and the case record from Shared State and Inter-Agent Communication.
- No coding experience is needed for most of this lesson.
- Optional: Python 3.10 or later, if you want to run the example yourself.
What orchestration and concurrency mean
Orchestration means one program decides which agent works when, passes each its task and gathers the results. Think of a conductor: the conductor plays no instrument, but decides who starts, who waits and when everyone stops. In our shop the orchestrator is ordinary code, with the supervisor model's route as one of its inputs.
Concurrency means two or more tasks are in progress at the same time. Waiting on a model or a tool is slow compared with computing, so a program can start the second task while the first one waits. It is like putting rice on to cook and chopping vegetables while it simmers.
| Style | How it runs | Good for |
|---|---|---|
| One at a time | Task 1 finishes, then task 2 starts. | Tasks that need the earlier result. Easiest to follow and debug. |
| At the same time | Tasks 1 and 2 are both in progress. | Independent tasks where waiting dominates, and the total time matters. |
When running specialists together is safe
The rule is short: run agents at the same time only for work that is independent and read-only. Independent means neither task needs the other's result. Read-only means neither changes anything outside itself.
Take a customer who writes: "Where is QF-1042, and what is your returns policy?" The orders_specialist calls lookup_order. The help_specialist calls search_help. Both only read. Neither needs the other. They can run together, and the customer waits for the slower one instead of for the sum of both.
| Situation | Together? | Why |
|---|---|---|
| Order lookup and help search for one message | Yes | Independent and read-only. |
| Look up an order, then request a return for it | No | The second task depends on the first, and it writes. |
| Two specialists both adding notes to one case | Only with a rule | Writes can collide. Use one of the methods in the next section. |
| Two agents each calling request_return for the same order | No | Two requests for one order is a duplicate. Run one, check the result, then decide. |
Avoid conflicting writes to one case
A conflicting write happens when two agents change the same data at the same time and one change is lost or mixed up. Here are three ways to prevent it, from simplest to most flexible.
Method 1: one owner per field
Give each field of the case record one writer. For example, only the supervisor writes route. Only the orders specialist writes its own part of the results. Nobody else may touch it. With one owner per field there is nothing to collide on, and no lock is needed. This is the method to try first.
Method 2: a lock
A lock is a flag that only one worker can hold at a time. Think of the key to a small meeting room. Whoever holds the key may use the room. Others wait outside until the key is returned. Use a lock when several agents must change the same field, such as appending to notes.
Method 3: a single writer
Agents do not write to the case at all. They return their proposed changes to the orchestrator, and only the orchestrator applies them, one after another, in a fixed order. Think of a shop with one cashier: customers can browse together, but only one person rings up the sale.
| Method | Strength | Watch out for |
|---|---|---|
| One owner per field | Simple, no waiting | Needs a clear table of who owns what. |
| A lock | Lets several workers write the same field | Keep the locked section tiny. Forgetting the lock somewhere breaks the guarantee. |
| A single writer | Easy to audit and to validate every change | The orchestrator becomes the one place that must be right. |
Order the results and set timeouts
Concurrent tasks finish in whatever order the network and the models happen to take. If you display or save results in the order they arrive, two identical runs can give two different outputs. That makes tests flaky and traces confusing.
- Collect first, then order. Wait until all results are in, then sort by a fixed key, such as the agent name or the task number.
- Label every result with the task that produced it, so you can match results to tasks even when they arrive out of order.
- Do not make decisions on whichever result arrives first unless that is the explicit design.
A timeout for each specialist
A timeout is a maximum time you are willing to wait. Without one, a single stuck specialist freezes the whole case. This is the same idea as the tool timeouts in Tool Errors, Retries, Timeouts and Idempotency, applied to a whole agent.
Decide in advance what a missed timeout means. Three options are common:
- Continue with partial results. Reply using what arrived and say what is missing. This suits read-only helpers such as the help search.
- Stop and hand to a person. This suits the case where the missing part is essential.
- Try once more, within the retry limits you already set. Never retry a write without an idempotency key.
A timed-out agent may still be running in the background. Make sure it cannot write to the case after you gave up on it. The single writer method makes this easy, because the orchestrator simply ignores late results.
- Start both specialists
Independent, read-only tasks
- Wait with a timeout
A fixed maximum per specialist
- Collect results
Labelled by agent name
- Sort and merge
One writer, fixed order
- Update the case
Add notes, set the result
Independent read-only work runs together. The orchestrator is the only part that merges and writes.
Try it: a lock around a shared case record
In this script two worker threads, standing in for two specialists, each add three notes to the same case record. A thread is a separate line of work inside one program. A lock protects the notes list and a write counter. Each worker keeps its own answer under its own key, which is method 1 and method 2 together. The program waits for both workers, then prints the notes in a fixed order.
import threading
case = {"case_id": "C-001", "notes": [], "result": None}
stats = {"writes": 0}
results = {} # one key per worker: each key has exactly one owner
lock = threading.Lock()
def worker(name, answer, steps):
for step in range(1, steps + 1):
with lock: # only one thread at a time may change the shared record
case["notes"].append(f"{name}: step {step}")
stats["writes"] += 1
results[name] = answer # no lock needed: nobody else writes this keyPart 1: the shared data and the worker.
threads = [
threading.Thread(target=worker, args=("orders_specialist", "QF-1042 dispatched", 3)),
threading.Thread(target=worker, args=("help_specialist", "KB-03 returns policy", 3)),
]
for t in threads:
t.start()
for t in threads:
t.join(timeout=5) # never wait forever for a worker
print("all finished:", not any(t.is_alive() for t in threads))
for note in sorted(case["notes"]): # fixed order, whatever order the threads ran in
print(note)
case["result"] = " | ".join(results[name] for name in sorted(results))
print("writes:", stats["writes"])
print("result:", case["result"])Part 2: start both workers, wait with a timeout, print in a fixed order. Add it below part 1.
What each part does
lock = threading.Lock()creates the lock, the single key to the meeting room.with lock:takes the key, runs the indented lines and gives the key back, even if something goes wrong inside. Without it, two threads could read the same counter value and both write the same new value, losing one update.results[name] = answerwrites to a key that only this worker uses, so it needs no lock. That is one owner per field.threading.Thread(target=worker, args=(...))prepares a thread that will runworkerwith those arguments.t.start()begins it.t.join(timeout=5)waits for the thread for at most five seconds.t.is_alive()tells you whether it is still running, which is how you notice a missed timeout.sorted(case["notes"])puts the notes in a fixed order. Which thread added its note first may change between runs, but the printed order never does.
all finished: True
help_specialist: step 1
help_specialist: step 2
help_specialist: step 3
orders_specialist: step 1
orders_specialist: step 2
orders_specialist: step 3
writes: 6
result: KB-03 returns policy | QF-1042 dispatchedThe write count is exactly six, and the output is identical on every run. Take the lock away and the output could change from run to run, which is the worst kind of bug to track down. In real agents the notes would also carry a case id and a step number, so sorting is just as simple.
Conclusion and your next step
Run specialists together only when their work is independent and read-only. Protect shared records with one owner per field, a lock or a single writer. Collect results before ordering them, and give every specialist a timeout with a clear rule for what a miss means.
Your next step: put everything from this module into practice in Practical Lab: Build a Supervisor with Two Specialist Agents. You will build the supervisor, two specialists, the case record, a handoff limit and a cycle stop, then compare the result with your single-agent design.
Want to revisit the basics first? See Human-in-the-Loop Approval and Escalation for what happens when a case goes to a person, or Managing Long-Running Tasks and Checkpoints for saving progress.
Common errors and how to fix them
Notes or counters in the case record are sometimes missing or wrong.
Why it happens: Two workers changed the same data at once and one update was lost.
Fix: Give each field one owner, put a lock around shared changes, or let only the orchestrator write.
The same test gives different output on different runs.
Why it happens: Results are printed or saved in the order they arrive, which changes from run to run.
Fix: Collect all results, then sort by a fixed key such as the agent name before printing or saving.
One slow specialist freezes the whole case.
Why it happens: There is no timeout, so the orchestrator waits for ever.
Fix: Set a maximum wait per specialist and decide in advance whether a miss means partial results or a person.
A specialist that timed out still changes the case later.
Why it happens: The task kept running in the background and wrote to the shared record.
Fix: Use a single writer that ignores late results, or check a cancelled flag before each write.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Decide what may run together
For each of the five customer messages below, decide whether the orders specialist and the help specialist may run at the same time, and which write rule you would use for the case record. Give one sentence of reasoning for each.
You will need
- "Where is QF-1042?"
- "Where is QF-1042, and how long does standard delivery take?"
- "I want to return QF-1044 because it is damaged. How does the refund work?"
- "What is your warranty?"
- "Return QF-1044 and also tell me the status of QF-1042."
Acceptance criteria
Your work is done when every one of these is true.
Hints (3)
- Ask two questions: does one task need the other's result, and does either change anything?
- request_return only creates a pending request, but it is still a write.
- When in doubt, run one task at a time and apply the single writer rule.
Show a model answer
Message 1 needs only the orders specialist, and message 4 only the help specialist. Message 2 has two independent read-only tasks, a lookup and a help search, so they may run together. Collect both results, then let the orchestrator add the notes in a fixed order. In message 3 the return is a write, and the refund explanation is a read. The two do not depend on each other, but the safer design finishes the return request first, then answers the policy question, using a single writer for notes. In message 5, the return request is a write and the lookup is a read of a different order. They are independent, but running the write alone, then the read, keeps the traces simple, and one owner per field is enough because the two tasks touch different parts of the record. The point of the exercise is that read-only plus independent is the test, and writes get the most careful treatment.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: A. Both tasks only read and neither needs the other. The second option looks like two independent requests, which makes it tempting, but two writes for one order create a duplicate. In the third option the second task has to wait for the first.
Show the answer and explanation
Answer: A. A lock or a single writer is enforced in code and cannot be forgotten. Asking a model to take turns is only a request, and it has no way to know what the other worker is doing at that moment.
Show the answer and explanation
Answer: B. Arrival order depends on timing, so sort by something stable such as the agent name. Re-running only hides the problem for a while, and removing the lock would make the shared record less safe, not more predictable.
Frequently asked questions
What is concurrency in AI agents?
It means more than one task is in progress at once. For agents this usually means starting two model or tool calls and waiting for both, instead of finishing the first before starting the second. It saves time when the tasks are independent, and it adds risk when they change the same data.
Do I need multithreading to run several agents?
Not always. Many agent libraries and frameworks run concurrent work for you, and a sequential design is often fast enough. Add concurrency only after you have measured that waiting is a real problem, and only for independent read-only work.
What is a race condition?
It is a bug where the result depends on which of two tasks happens to run first. For example, two workers read a counter showing 5, both add one and both write 6, so one update is lost. Locks, single writers and one owner per field all prevent it.
What should happen when one specialist is too slow?
Decide before it happens. For helpful but optional work, such as a help-centre search, carry on with partial results and say what is missing. For essential work, stop and hand the case to a person. Either way, make sure a late result cannot change the case afterwards.
- Written by
- PromptFable Editorial
- Last updated 18 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- How we built our multi-agent research system(opens in a new tab)
Anthropic · Official documentation · An engineering account of running several agents together and the coordination work it needs.
- Building effective agents(opens in a new tab)
Anthropic · Official documentation · Describes workflows where independent subtasks run in parallel and are combined afterwards.
- threading: Thread-based parallelism(opens in a new tab)
Python Software Foundation · Official documentation · Reference for Thread, Lock and join used in the example.
- concurrent.futures: Launching parallel tasks(opens in a new tab)
Python Software Foundation · Official documentation · A higher-level way to run tasks together and wait for their results with a timeout.
- Function calling with the Gemini API(opens in a new tab)
Google · Official documentation · Mentions that a model can request several function calls in one turn.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.